diaryx_core 1.0.0

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
//! 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 types;

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

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

use serde::{Deserialize, Serialize};
use serde_yaml::Value;
use ts_rs::TS;

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;

/// How to generate filenames from entry titles.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
#[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, TS)]
#[ts(export, export_to = "bindings/")]
pub struct WorkspaceConfig {
    /// Format for `part_of` and `contents` links.
    /// Defaults to MarkdownRoot if not specified.
    #[serde(default)]
    pub link_format: LinkFormat,

    /// Subfolder for daily entries (e.g., "Daily" or "Journal/Daily").
    /// If not specified, daily entries are created at workspace root.
    #[ts(optional)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daily_entry_folder: Option<String>,

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

    /// Link to the daily entry template (in link_format style).
    /// If absent, uses the built-in "daily" template.
    #[ts(optional)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daily_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 that designates files for public viewing/publishing.
    /// Replaces the old hardcoded "private" magic. Files with this audience tag
    /// are included in public exports; files without it are excluded.
    #[ts(optional)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub public_audience: Option<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 and contents 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 and contents 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> {
        use crate::path_utils::normalize_path;

        if let Ok(Some(Value::String(part_of))) =
            self.get_frontmatter_property(file_path, "part_of").await
        {
            let file_dir = file_path.parent().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(&file_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()
    }

    /// 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)
    }

    /// 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)
    }

    /// 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)
    }

    /// 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",
                    Value::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.
    pub async fn get_workspace_config(&self, root_index_path: &Path) -> Result<WorkspaceConfig> {
        let index = self.parse_index(root_index_path).await?;
        let extra = &index.frontmatter.extra;

        let link_format = extra
            .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 daily_entry_folder = extra
            .get("daily_entry_folder")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

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

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

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

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

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

        let filename_style = extra
            .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 public_audience = extra
            .get("public_audience")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        Ok(WorkspaceConfig {
            link_format,
            daily_entry_folder,
            default_template,
            daily_template,
            sync_title_to_heading,
            auto_update_timestamp,
            auto_rename_to_title,
            filename_style,
            public_audience,
        })
    }

    /// Set a workspace configuration field in the root index file's frontmatter.
    ///
    /// # Arguments
    /// * `root_index_path` - Path to the root index file
    /// * `field` - Field name to set (e.g., "link_format", "daily_entry_folder")
    /// * `value` - Value to set as a string; boolean strings ("true"/"false") are
    ///   stored as YAML booleans so that `as_bool()` works when reading back.
    pub async fn set_workspace_config_field(
        &self,
        root_index_path: &Path,
        field: &str,
        value: &str,
    ) -> Result<()> {
        let yaml_value = match value {
            "true" => Value::Bool(true),
            "false" => Value::Bool(false),
            _ => Value::String(value.to_string()),
        };
        self.set_frontmatter_property(root_index_path, field, yaml_value)
            .await
    }

    /// 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(),
                children: Vec::new(),
                properties: std::collections::HashMap::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();

        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(),
                children: Vec::new(),
                properties: std::collections::HashMap::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
                );

                // 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,
                                children: Vec::new(),
                                properties: std::collections::HashMap::new(),
                            });
                        }
                    }
                }
                // Ignore non-existent paths (as per spec: "ignore by default")
            }
        }

        Ok(TreeNode {
            name,
            description: index.frontmatter.description,
            path: root_path.to_path_buf(),
            children,
            properties: std::collections::HashMap::new(),
        })
    }

    /// 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
    pub async fn build_filesystem_tree_with_depth(
        &self,
        root_dir: &Path,
        show_hidden: bool,
        max_depth: Option<usize>,
    ) -> Result<TreeNode> {
        self.build_filesystem_tree_recursive(root_dir, show_hidden, max_depth)
            .await
    }

    async fn build_filesystem_tree_recursive(
        &self,
        dir: &Path,
        show_hidden: bool,
        max_depth: Option<usize>,
    ) -> Result<TreeNode> {
        // 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(dir).await {
                if let Ok(parsed) = self.parse_index(&index).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

            // Filter out hidden files and temporary files to get accurate count
            let entries: Vec<_> = entries
                .into_iter()
                .filter(|entry| {
                    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);
                    !hidden && !temp
                })
                .collect();

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

                for entry in 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 {
                        // Recurse into subdirectory with decremented depth
                        if let Ok(child_tree) = Box::pin(self.build_filesystem_tree_recursive(
                            &entry,
                            show_hidden,
                            next_depth,
                        ))
                        .await
                        {
                            children.push(child_tree);
                        }
                    } else {
                        // It's a file - skip index files (already represented by parent dir)
                        if self.is_index_file(&entry).await {
                            continue;
                        }

                        // Get title from frontmatter if it's a markdown file
                        let (file_title, file_desc) =
                            if entry.extension().is_some_and(|e| e == "md") {
                                if let Ok(parsed) = self.parse_index(&entry).await {
                                    (
                                        parsed.frontmatter.title.unwrap_or(file_name.clone()),
                                        parsed.frontmatter.description,
                                    )
                                } else {
                                    (file_name.clone(), None)
                                }
                            } else {
                                (file_name.clone(), None)
                            };

                        children.push(TreeNode {
                            name: file_title,
                            description: file_desc,
                            path: entry,
                            children: Vec::new(),
                            properties: std::collections::HashMap::new(),
                        });
                    }
                }
            }
        }

        Ok(TreeNode {
            name,
            description,
            path: node_path,
            children,
            properties: std::collections::HashMap::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(Value::String(s))) => Some(s),
                    Ok(Some(Value::Number(n))) => Some(n.to_string()),
                    Ok(Some(Value::Bool(b))) => Some(b.to_string()),
                    Ok(Some(Value::Sequence(seq))) => {
                        // Join sequence values with ", "
                        let strings: Vec<String> = seq
                            .iter()
                            .filter_map(|v| match v {
                                Value::String(s) => Some(s.clone()),
                                Value::Number(n) => Some(n.to_string()),
                                Value::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<Value>> {
        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, Value> =
                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: Value,
    ) -> 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, Value> = 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, Value> =
            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(Value::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(Value::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", Value::Sequence(items))
                        .await?;
                    return Ok(true);
                }
                Ok(false)
            }
            Ok(None) => {
                // Create contents with just this entry (normalized)
                let items = vec![Value::String(normalized_entry.to_string())];
                self.set_frontmatter_property(index_path, "contents", Value::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(Value::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(Value::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", Value::Sequence(items))
                        .await?;
                    return Ok(true);
                }
                Ok(false)
            }
            Ok(None) => {
                // Create contents with just this entry
                let items = vec![Value::String(formatted_entry)];
                self.set_frontmatter_property(index_path, "contents", Value::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));

        match self.get_frontmatter_property(index_path, "contents").await {
            Ok(Some(Value::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", Value::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",
                ),
            });
        }

        // 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?;

        // 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", Value::String(part_of))
            .await?;

        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<()> {
        use crate::path_utils::relative_path_from_file_to_target;

        // No-op if same path
        if from_path == to_path {
            return Ok(());
        }

        // Get filenames and parent directories before moving
        let old_parent = from_path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: from_path.to_path_buf(),
            message: "No parent directory for source path".to_string(),
        })?;
        let new_parent = to_path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: to_path.to_path_buf(),
            message: "No parent directory for destination path".to_string(),
        })?;
        let _new_file_name = 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(),
            })?
            .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,
            })?;

        // Find old parent index by following part_of (the moved file still has its
        // original part_of at this point). This is more robust than searching by
        // directory, which fails when the moved file was itself the index in old_parent.
        let old_index_path = self.resolve_part_of_to_path(to_path, old_parent).await;
        let new_index_path = self.find_any_index_in_dir(new_parent).await.ok().flatten();
        let same_index_parent = old_index_path
            .as_ref()
            .zip(new_index_path.as_ref())
            .is_some_and(|(old_idx, new_idx)| old_idx == new_idx);

        // 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 to_path_canonical = self.get_canonical_path(to_path);
            let title = self.resolve_title(&to_path_canonical).await;
            self.add_to_index_contents_canonical(new_index_path, &to_path_canonical, &title)
                .await?;

            // Update moved entry's part_of only when parent index actually changes.
            if !same_index_parent {
                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, &to_path_canonical)
                } else {
                    relative_path_from_file_to_target(to_path, new_index_path)
                };
                self.set_frontmatter_property(to_path, "part_of", Value::String(part_of_value))
                    .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(from_path);
            if let Err(e) = self
                .remove_from_index_contents(old_index_path, &from_canonical)
                .await
            {
                log::warn!(
                    "move_entry: failed to remove old contents reference '{}' from '{}': {}",
                    from_canonical,
                    old_index_path.display(),
                    e
                );
            }
        }

        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(Value::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(&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 {
            // 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;
            if let Ok(children) = self.fs.list_md_files(parent).await {
                for child in children {
                    if child == new_path {
                        continue;
                    }
                    let part_of_value = if self.root_path.is_some() {
                        let child_canonical = self.get_canonical_path(&child);
                        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, &new_path)
                    };
                    if let Err(e) = self
                        .set_frontmatter_property(&child, "part_of", Value::String(part_of_value))
                        .await
                    {
                        log::warn!(
                            "rename_entry: failed to update child part_of for '{}': {}",
                            child.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(),
                })?;

            // 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 from old directory to new directory and track children
            let mut children_paths: Vec<PathBuf> = Vec::new();
            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?;
                        children_paths.push(new_path);
                    }
                }
            }

            // Update all children's part_of to point to new index
            // Update children's part_of to point to renamed parent
            let new_file_canonical = self.get_canonical_path(&new_file_path);
            let new_file_title = self.resolve_title(&new_file_canonical).await;
            for child_path in &children_paths {
                let part_of_value = if self.root_path.is_some() {
                    let child_canonical = self.get_canonical_path(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(child_path, &new_file_path)
                };
                if let Err(e) = self
                    .set_frontmatter_property(child_path, "part_of", Value::String(part_of_value))
                    .await
                {
                    log::warn!(
                        "rename_entry: failed to update child part_of for '{}': {}",
                        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(&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 {
                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(&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",
                                Value::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",
                        Value::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", Value::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", Value::Sequence(vec![]))
            .await?;

        // Update part_of path since file moved one level deeper
        if let Ok(Some(Value::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", Value::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(&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(Value::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", Value::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(&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(),
            })?;

        // 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)
    }
}

#[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()),
            description: None,
            contents: Some(vec![]),
            part_of: None,
            audience: None,
            attachments: None,
            exclude: 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()),
            description: None,
            contents: Some(vec![]),
            part_of: Some("../parent.md".to_string()),
            audience: None,
            attachments: None,
            exclude: 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"),
            children: vec![
                TreeNode {
                    name: "Child 1".to_string(),
                    description: None,
                    path: PathBuf::from("child1.md"),
                    children: vec![],
                    properties: std::collections::HashMap::new(),
                },
                TreeNode {
                    name: "Child 2".to_string(),
                    description: Some("Child desc".to_string()),
                    path: PathBuf::from("child2.md"),
                    children: vec![],
                    properties: std::collections::HashMap::new(),
                },
            ],
            properties: std::collections::HashMap::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_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_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(Value::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_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
        );
    }
}