diaryx_core 0.10.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
//! Command execution handler.
//!
//! This module contains the implementation of the `execute()` method for `Diaryx`.
//! It handles all command types and returns appropriate responses.

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

use indexmap::IndexMap;
use serde_yaml::Value;

use crate::command::{Command, EntryData, Response};
use crate::diaryx::{Diaryx, json_to_yaml, yaml_to_json};
use crate::error::{DiaryxError, Result};
use crate::frontmatter;
use crate::fs::AsyncFileSystem;

impl<FS: AsyncFileSystem + Clone> Diaryx<FS> {
    /// Execute a command and return the response.
    ///
    /// This is the unified command interface that replaces individual method calls.
    /// All commands are async and return a `Result<Response>`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use diaryx_core::{Command, Response, Diaryx};
    ///
    /// let cmd = Command::GetEntry { path: "notes/hello.md".to_string() };
    /// let response = diaryx.execute(cmd).await?;
    ///
    /// if let Response::Entry(entry) = response {
    ///     println!("Title: {:?}", entry.title);
    /// }
    /// ```
    pub async fn execute(&self, command: Command) -> Result<Response> {
        match command {
            // === Entry Operations ===
            Command::GetEntry { path } => {
                let content = self.entry().read_raw(&path).await?;
                let parsed = frontmatter::parse_or_empty(&content)?;
                let title = parsed
                    .frontmatter
                    .get("title")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                // Convert serde_yaml::Value to serde_json::Value
                let fm: IndexMap<String, serde_json::Value> = parsed
                    .frontmatter
                    .into_iter()
                    .map(|(k, v)| (k, yaml_to_json(v)))
                    .collect();

                Ok(Response::Entry(EntryData {
                    path: PathBuf::from(&path),
                    title,
                    frontmatter: fm,
                    content: parsed.body,
                }))
            }

            Command::SaveEntry { path, content } => {
                self.entry().save_content(&path, &content).await?;
                Ok(Response::Ok)
            }

            Command::GetFrontmatter { path } => {
                let fm = self.entry().get_frontmatter(&path).await?;
                let json_fm: IndexMap<String, serde_json::Value> =
                    fm.into_iter().map(|(k, v)| (k, yaml_to_json(v))).collect();
                Ok(Response::Frontmatter(json_fm))
            }

            Command::SetFrontmatterProperty { path, key, value } => {
                let yaml_value = json_to_yaml(value);
                self.entry()
                    .set_frontmatter_property(&path, &key, yaml_value)
                    .await?;
                Ok(Response::Ok)
            }

            Command::RemoveFrontmatterProperty { path, key } => {
                self.entry()
                    .remove_frontmatter_property(&path, &key)
                    .await?;
                Ok(Response::Ok)
            }

            // === Workspace Operations ===
            Command::FindRootIndex { directory } => {
                let ws = self.workspace().inner();
                match ws.find_root_index_in_dir(Path::new(&directory)).await? {
                    Some(path) => Ok(Response::String(path.to_string_lossy().to_string())),
                    None => Err(DiaryxError::WorkspaceNotFound(PathBuf::from(&directory))),
                }
            }

            Command::GetWorkspaceTree { path, depth } => {
                let root_path = path.unwrap_or_else(|| "workspace/index.md".to_string());
                let tree = self
                    .workspace()
                    .inner()
                    .build_tree_with_depth(
                        Path::new(&root_path),
                        depth.map(|d| d as usize),
                        &mut std::collections::HashSet::new(),
                    )
                    .await?;
                Ok(Response::Tree(tree))
            }

            Command::GetFilesystemTree {
                path,
                show_hidden,
                depth,
            } => {
                let root_path = path.unwrap_or_else(|| "workspace".to_string());
                let tree = self
                    .workspace()
                    .inner()
                    .build_filesystem_tree_with_depth(
                        Path::new(&root_path),
                        show_hidden,
                        depth.map(|d| d as usize),
                    )
                    .await?;
                Ok(Response::Tree(tree))
            }

            // === Validation Operations ===
            Command::ValidateWorkspace { path } => {
                let root_path = path.unwrap_or_else(|| "workspace/index.md".to_string());
                // Use depth limit of 2 to match tree view (TREE_INITIAL_DEPTH in App.svelte)
                // This significantly improves performance for large workspaces
                let result = self
                    .validate()
                    .validate_workspace(Path::new(&root_path), Some(2))
                    .await?;
                // Include computed metadata for frontend display
                Ok(Response::ValidationResult(result.with_metadata()))
            }

            Command::ValidateFile { path } => {
                let result = self.validate().validate_file(Path::new(&path)).await?;
                // Include computed metadata for frontend display
                Ok(Response::ValidationResult(result.with_metadata()))
            }

            Command::FixBrokenPartOf { path } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_broken_part_of(Path::new(&path))
                    .await;
                Ok(Response::FixResult(result))
            }

            Command::FixBrokenContentsRef { index_path, target } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_broken_contents_ref(Path::new(&index_path), &target)
                    .await;
                Ok(Response::FixResult(result))
            }

            // === Search Operations ===
            Command::SearchWorkspace { pattern, options } => {
                use crate::search::SearchQuery;

                let query = if options.search_frontmatter {
                    if let Some(prop) = options.property {
                        SearchQuery::property(&pattern, prop)
                    } else {
                        SearchQuery::frontmatter(&pattern)
                    }
                } else {
                    SearchQuery::content(&pattern)
                }
                .case_sensitive(options.case_sensitive);

                let workspace_path = options
                    .workspace_path
                    .unwrap_or_else(|| "workspace/index.md".to_string());
                let results = self
                    .search()
                    .search_workspace(Path::new(&workspace_path), &query)
                    .await?;
                Ok(Response::SearchResults(results))
            }

            // === Export Operations ===
            Command::PlanExport {
                root_path,
                audience,
            } => {
                let plan = self
                    .export()
                    .plan_export(Path::new(&root_path), &audience, Path::new("/tmp/export"))
                    .await?;
                Ok(Response::ExportPlan(plan))
            }

            // === File System Operations ===
            Command::FileExists { path } => {
                let exists = self.fs().exists(Path::new(&path)).await;
                Ok(Response::Bool(exists))
            }

            Command::ReadFile { path } => {
                let content = self.entry().read_raw(&path).await?;
                Ok(Response::String(content))
            }

            Command::WriteFile { path, content } => {
                self.fs()
                    .write_file(Path::new(&path), &content)
                    .await
                    .map_err(|e| DiaryxError::FileWrite {
                        path: PathBuf::from(&path),
                        source: e,
                    })?;
                Ok(Response::Ok)
            }

            Command::DeleteFile { path } => {
                self.fs().delete_file(Path::new(&path)).await.map_err(|e| {
                    DiaryxError::FileWrite {
                        path: PathBuf::from(&path),
                        source: e,
                    }
                })?;
                Ok(Response::Ok)
            }

            // === Attachment Operations ===
            Command::GetAttachments { path } => {
                let attachments = self.entry().get_attachments(&path).await?;
                Ok(Response::Strings(attachments))
            }

            Command::GetAncestorAttachments { path } => {
                use crate::command::{AncestorAttachmentEntry, AncestorAttachmentsResult};
                use std::collections::HashSet;

                let ws = self.workspace().inner();
                let mut entries = Vec::new();
                let mut visited = HashSet::new();
                let mut current_path = PathBuf::from(&path);

                // Maximum depth to prevent runaway traversal
                const MAX_DEPTH: usize = 100;

                // Traverse up the part_of chain
                for _ in 0..MAX_DEPTH {
                    let path_str = current_path.to_string_lossy().to_string();
                    if visited.contains(&path_str) {
                        break; // Circular reference protection
                    }
                    visited.insert(path_str.clone());

                    // Try to parse the file
                    if let Ok(index) = ws.parse_index(&current_path).await {
                        let attachments = index.frontmatter.attachments_list().to_vec();

                        // Only add if there are attachments
                        if !attachments.is_empty() {
                            entries.push(AncestorAttachmentEntry {
                                entry_path: path_str,
                                entry_title: index.frontmatter.title.clone(),
                                attachments,
                            });
                        }

                        // Move to parent via part_of
                        if let Some(part_of) = &index.frontmatter.part_of {
                            current_path = index.resolve_path(part_of);
                        } else {
                            break; // Reached root
                        }
                    } else {
                        break; // File doesn't exist or can't be parsed
                    }
                }

                Ok(Response::AncestorAttachments(AncestorAttachmentsResult {
                    entries,
                }))
            }

            // === Entry Creation/Deletion Operations ===
            Command::CreateEntry { path, options } => {
                // Derive title from filename if not provided
                let path_buf = PathBuf::from(&path);
                let title = options.title.unwrap_or_else(|| {
                    path_buf
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("Untitled")
                        .to_string()
                });

                // Create the file with basic frontmatter
                let content = format!("---\ntitle: {}\n---\n\n# {}\n\n", title, title);
                self.fs()
                    .create_new(Path::new(&path), &content)
                    .await
                    .map_err(|e| DiaryxError::FileWrite {
                        path: path_buf.clone(),
                        source: e,
                    })?;

                // Set part_of if provided
                if let Some(parent) = options.part_of {
                    self.entry()
                        .set_frontmatter_property(&path, "part_of", Value::String(parent))
                        .await?;
                }

                Ok(Response::String(path))
            }

            Command::DeleteEntry { path } => {
                // Use Workspace::delete_entry which handles contents cleanup
                let ws = self.workspace().inner();
                ws.delete_entry(Path::new(&path)).await?;
                Ok(Response::Ok)
            }

            Command::MoveEntry { from, to } => {
                if from == to {
                    return Ok(Response::String(to));
                }

                // Use Workspace::move_entry which handles contents/part_of updates
                let ws = self.workspace().inner();
                ws.move_entry(Path::new(&from), Path::new(&to)).await?;
                Ok(Response::String(to))
            }

            Command::RenameEntry { path, new_filename } => {
                let from_path = PathBuf::from(&path);
                let parent_dir = from_path.parent().unwrap_or_else(|| Path::new("."));
                let to_path = parent_dir.join(&new_filename);

                if from_path == to_path {
                    return Ok(Response::String(to_path.to_string_lossy().to_string()));
                }

                // Use move_entry logic for consistency
                let ws = self.workspace().inner();
                ws.move_entry(&from_path, &to_path).await?;
                Ok(Response::String(to_path.to_string_lossy().to_string()))
            }

            Command::DuplicateEntry { path } => {
                let ws = self.workspace().inner();
                let new_path = ws.duplicate_entry(Path::new(&path)).await?;
                Ok(Response::String(new_path.to_string_lossy().to_string()))
            }

            // === Hierarchy Operations ===
            Command::ConvertToIndex { path } => {
                let fm = self.entry().get_frontmatter(&path).await?;

                // Check if already has contents
                if fm.contains_key("contents") {
                    return Ok(Response::String(path));
                }

                // Add empty contents array
                self.entry()
                    .set_frontmatter_property(&path, "contents", Value::Sequence(vec![]))
                    .await?;
                Ok(Response::String(path))
            }

            Command::ConvertToLeaf { path } => {
                // Remove contents property if it exists
                self.entry()
                    .remove_frontmatter_property(&path, "contents")
                    .await?;
                Ok(Response::String(path))
            }

            Command::CreateChildEntry { parent_path } => {
                let ws = self.workspace().inner();
                let new_path = ws.create_child_entry(Path::new(&parent_path), None).await?;
                Ok(Response::String(new_path.to_string_lossy().to_string()))
            }

            Command::AttachEntryToParent {
                entry_path,
                parent_path,
            } => {
                let ws = self.workspace().inner();
                let new_path = ws
                    .attach_and_move_entry_to_parent(
                        Path::new(&entry_path),
                        Path::new(&parent_path),
                    )
                    .await?;
                Ok(Response::String(new_path.to_string_lossy().to_string()))
            }

            Command::EnsureDailyEntry => {
                // This requires config which we don't have access to in the core
                // Return an error suggesting this should be handled at the Tauri level
                Err(DiaryxError::Unsupported(
                    "EnsureDailyEntry requires config which is platform-specific. Use Tauri command.".to_string()
                ))
            }

            // === Workspace Operations ===
            Command::CreateWorkspace { path, name } => {
                let ws_path = path.unwrap_or_else(|| "workspace".to_string());
                let ws_name = name.as_deref();
                let ws = self.workspace().inner();
                let readme_path = ws
                    .init_workspace(Path::new(&ws_path), ws_name, None)
                    .await?;
                Ok(Response::String(readme_path.to_string_lossy().to_string()))
            }

            // === Validation Fix Operations ===
            Command::FixBrokenAttachment { path, attachment } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_broken_attachment(Path::new(&path), &attachment)
                    .await;
                Ok(Response::FixResult(result))
            }

            Command::FixNonPortablePath {
                path,
                property,
                old_value,
                new_value,
            } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_non_portable_path(Path::new(&path), &property, &old_value, &new_value)
                    .await;
                Ok(Response::FixResult(result))
            }

            Command::FixUnlistedFile {
                index_path,
                file_path,
            } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_unlisted_file(Path::new(&index_path), Path::new(&file_path))
                    .await;
                Ok(Response::FixResult(result))
            }

            Command::FixOrphanBinaryFile {
                index_path,
                file_path,
            } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_orphan_binary_file(Path::new(&index_path), Path::new(&file_path))
                    .await;
                Ok(Response::FixResult(result))
            }

            Command::FixMissingPartOf {
                file_path,
                index_path,
            } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_missing_part_of(Path::new(&file_path), Path::new(&index_path))
                    .await;
                Ok(Response::FixResult(result))
            }

            Command::FixAll { validation_result } => {
                let fixer = self.validate().fixer();
                let (error_fixes, warning_fixes) = fixer.fix_all(&validation_result).await;

                let total_fixed = error_fixes.iter().filter(|r| r.success).count()
                    + warning_fixes.iter().filter(|r| r.success).count();
                let total_failed = error_fixes.iter().filter(|r| !r.success).count()
                    + warning_fixes.iter().filter(|r| !r.success).count();

                Ok(Response::FixSummary(crate::command::FixSummary {
                    error_fixes,
                    warning_fixes,
                    total_fixed,
                    total_failed,
                }))
            }

            Command::FixCircularReference {
                file_path,
                part_of_value,
            } => {
                let result = self
                    .validate()
                    .fixer()
                    .fix_circular_reference(Path::new(&file_path), &part_of_value)
                    .await;
                Ok(Response::FixResult(result))
            }

            Command::GetAvailableParentIndexes {
                file_path,
                workspace_root,
            } => {
                // Find all index files between the file and the workspace root
                let ws = self.workspace().inner();
                let file = Path::new(&file_path);
                let root_index = Path::new(&workspace_root);
                let root_dir = root_index.parent().unwrap_or(root_index);

                let mut parents = Vec::new();

                // Start from the file's directory and walk up to the workspace root
                let file_dir = file.parent().unwrap_or(Path::new("."));
                let mut current = file_dir.to_path_buf();

                loop {
                    // Look for index files in this directory
                    if let Ok(files) = ws.fs_ref().list_files(&current).await {
                        for file_path in files {
                            // Check if it's a markdown file
                            if file_path.extension().is_some_and(|ext| ext == "md")
                                && !ws.fs_ref().is_dir(&file_path).await
                            {
                                // Try to parse and check if it has contents (is an index)
                                if let Ok(index) = ws.parse_index(&file_path).await
                                    && index.frontmatter.is_index()
                                {
                                    parents.push(file_path.to_string_lossy().to_string());
                                }
                            }
                        }
                    }

                    // Stop if we've reached or passed the workspace root
                    if current == root_dir || !current.starts_with(root_dir) {
                        break;
                    }

                    // Go up one level
                    match current.parent() {
                        Some(parent) if parent != current => {
                            current = parent.to_path_buf();
                        }
                        _ => break,
                    }
                }

                // Always include the workspace root if not already present
                let root_str = root_index.to_string_lossy().to_string();
                if !parents.contains(&root_str) && ws.fs_ref().exists(root_index).await {
                    parents.push(root_str);
                }

                // Sort for consistent ordering
                parents.sort();
                Ok(Response::Strings(parents))
            }

            // === Export Operations ===
            Command::GetAvailableAudiences { root_path } => {
                // Collect unique audience tags from workspace
                let ws = self.workspace().inner();
                let mut audiences = std::collections::HashSet::new();
                let mut visited = std::collections::HashSet::new();

                async fn collect_audiences<FS: AsyncFileSystem>(
                    ws: &crate::workspace::Workspace<FS>,
                    path: &Path,
                    audiences: &mut std::collections::HashSet<String>,
                    visited: &mut std::collections::HashSet<PathBuf>,
                ) {
                    if visited.contains(path) {
                        return;
                    }
                    visited.insert(path.to_path_buf());

                    if let Ok(index) = ws.parse_index(path).await {
                        if let Some(file_audiences) = &index.frontmatter.audience {
                            for a in file_audiences {
                                if a.to_lowercase() != "private" {
                                    audiences.insert(a.clone());
                                }
                            }
                        }

                        if index.frontmatter.is_index() {
                            for child_rel in index.frontmatter.contents_list() {
                                let child_path = index.resolve_path(child_rel);
                                if ws.fs_ref().exists(&child_path).await {
                                    Box::pin(collect_audiences(
                                        ws,
                                        &child_path,
                                        audiences,
                                        visited,
                                    ))
                                    .await;
                                }
                            }
                        }
                    }
                }

                collect_audiences(&ws, Path::new(&root_path), &mut audiences, &mut visited).await;
                let mut result: Vec<String> = audiences.into_iter().collect();
                result.sort();
                Ok(Response::Strings(result))
            }

            Command::ExportToMemory {
                root_path,
                audience,
            } => {
                // Plan the export first
                log::info!(
                    "[Export] ExportToMemory starting - root_path: {:?}, audience: {:?}",
                    root_path,
                    audience
                );
                let plan = self
                    .export()
                    .plan_export(Path::new(&root_path), &audience, Path::new("/tmp/export"))
                    .await?;

                log::info!(
                    "[Export] plan_export returned {} included files",
                    plan.included.len()
                );
                for included in &plan.included {
                    log::info!(
                        "[Export] planned file: {:?} -> {:?}",
                        included.source_path,
                        included.relative_path
                    );
                }

                // Read each included file
                let mut files = Vec::new();
                for included in &plan.included {
                    match self.fs().read_to_string(&included.source_path).await {
                        Ok(content) => {
                            log::info!(
                                "[Export] read success: {:?} ({} bytes)",
                                included.source_path,
                                content.len()
                            );
                            files.push(crate::command::ExportedFile {
                                path: included.relative_path.to_string_lossy().to_string(),
                                content,
                            });
                        }
                        Err(e) => {
                            log::warn!("[Export] read failed: {:?} - {}", included.source_path, e);
                        }
                    }
                }
                log::info!("[Export] ExportToMemory returning {} files", files.len());
                Ok(Response::ExportedFiles(files))
            }

            Command::ExportToHtml {
                root_path,
                audience,
            } => {
                // Plan the export first
                let plan = self
                    .export()
                    .plan_export(Path::new(&root_path), &audience, Path::new("/tmp/export"))
                    .await?;

                // Read each included file and convert path extension
                let mut files = Vec::new();
                for included in &plan.included {
                    if let Ok(content) = self.fs().read_to_string(&included.source_path).await {
                        let html_path = included
                            .relative_path
                            .to_string_lossy()
                            .replace(".md", ".html");
                        files.push(crate::command::ExportedFile {
                            path: html_path,
                            content, // TODO: Add markdown-to-HTML conversion
                        });
                    }
                }
                Ok(Response::ExportedFiles(files))
            }

            Command::ExportBinaryAttachments {
                root_path,
                audience: _,
            } => {
                // Collect all non-hidden binary files from workspace
                let root_index = Path::new(&root_path);
                let root_dir = root_index.parent().unwrap_or(root_index);

                log::info!(
                    "[Export] ExportBinaryAttachments starting - root_path: {:?}, root_dir: {:?}",
                    root_path,
                    root_dir
                );

                let mut attachments: Vec<crate::command::BinaryFileInfo> = Vec::new();
                let mut visited_dirs = std::collections::HashSet::new();

                // Helper to check if a file is a binary attachment (not markdown)
                fn is_binary_file(path: &Path) -> bool {
                    let ext = path
                        .extension()
                        .and_then(|e| e.to_str())
                        .map(|e| e.to_lowercase());

                    match ext.as_deref() {
                        // Text/markdown files - not binary
                        Some("md" | "txt" | "json" | "yaml" | "yml" | "toml") => false,
                        // Common binary formats
                        Some(
                            "png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "ico" | "bmp" | "pdf"
                            | "heic" | "heif" | "doc" | "docx" | "xls" | "xlsx" | "ppt" | "pptx"
                            | "mp3" | "mp4" | "wav" | "ogg" | "flac" | "m4a" | "aac" | "mov"
                            | "avi" | "mkv" | "webm" | "zip" | "tar" | "gz" | "rar" | "7z" | "ttf"
                            | "otf" | "woff" | "woff2" | "sqlite" | "db",
                        ) => true,
                        // Unknown extension - check if it looks like a text file
                        _ => false,
                    }
                }

                // Helper to check if a path component is hidden
                fn is_hidden_component(name: &str) -> bool {
                    name.starts_with('.')
                }

                // Recursively collect binary file paths from a directory (no data, for efficiency)
                async fn collect_binaries_recursive<FS: AsyncFileSystem>(
                    fs: &FS,
                    dir: &Path,
                    root_dir: &Path,
                    attachments: &mut Vec<crate::command::BinaryFileInfo>,
                    visited_dirs: &mut std::collections::HashSet<PathBuf>,
                ) {
                    if visited_dirs.contains(dir) {
                        log::debug!("[Export] skipping already visited dir: {:?}", dir);
                        return;
                    }
                    visited_dirs.insert(dir.to_path_buf());

                    // Skip hidden directories
                    if let Some(name) = dir.file_name().and_then(|n| n.to_str())
                        && is_hidden_component(name)
                    {
                        log::debug!("[Export] skipping hidden dir: {:?}", dir);
                        return;
                    }

                    log::info!("[Export] listing files in dir: {:?}", dir);
                    let entries = match fs.list_files(dir).await {
                        Ok(e) => {
                            log::info!(
                                "[Export] list_files returned {} entries for {:?}",
                                e.len(),
                                dir
                            );
                            e
                        }
                        Err(e) => {
                            log::warn!("[Export] list_files failed for {:?}: {}", dir, e);
                            return;
                        }
                    };

                    for entry_path in entries {
                        // Skip hidden files/dirs
                        if let Some(name) = entry_path.file_name().and_then(|n| n.to_str())
                            && is_hidden_component(name)
                        {
                            continue;
                        }

                        if fs.is_dir(&entry_path).await {
                            // Recurse into subdirectory
                            Box::pin(collect_binaries_recursive(
                                fs,
                                &entry_path,
                                root_dir,
                                attachments,
                                visited_dirs,
                            ))
                            .await;
                        } else if is_binary_file(&entry_path) {
                            // Just record the path, don't read data (for efficiency)
                            let relative_path = pathdiff::diff_paths(&entry_path, root_dir)
                                .unwrap_or_else(|| entry_path.clone());
                            log::debug!("[Export] found binary file: {:?}", entry_path);
                            attachments.push(crate::command::BinaryFileInfo {
                                source_path: entry_path.to_string_lossy().to_string(),
                                relative_path: relative_path.to_string_lossy().to_string(),
                            });
                        } else {
                            log::debug!("[Export] skipping non-binary file: {:?}", entry_path);
                        }
                    }
                }

                collect_binaries_recursive(
                    self.fs(),
                    root_dir,
                    root_dir,
                    &mut attachments,
                    &mut visited_dirs,
                )
                .await;

                log::info!(
                    "[Export] ExportBinaryAttachments returning {} attachment paths",
                    attachments.len()
                );
                Ok(Response::BinaryFilePaths(attachments))
            }

            // === Template Operations ===
            Command::ListTemplates { workspace_path } => {
                let templates_dir = PathBuf::from(workspace_path.as_deref().unwrap_or("workspace"))
                    .join("_templates");

                let mut templates = Vec::new();

                // Add built-in templates
                templates.push(crate::command::TemplateInfo {
                    name: "note".to_string(),
                    path: None,
                    source: "builtin".to_string(),
                });
                templates.push(crate::command::TemplateInfo {
                    name: "daily".to_string(),
                    path: None,
                    source: "builtin".to_string(),
                });

                // Add workspace templates
                if self.fs().is_dir(&templates_dir).await
                    && let Ok(files) = self.fs().list_files(&templates_dir).await
                {
                    for file_path in files {
                        if file_path.extension().is_some_and(|ext| ext == "md")
                            && let Some(name) = file_path.file_stem().and_then(|s| s.to_str())
                        {
                            templates.push(crate::command::TemplateInfo {
                                name: name.to_string(),
                                path: Some(file_path),
                                source: "workspace".to_string(),
                            });
                        }
                    }
                }

                Ok(Response::Templates(templates))
            }

            Command::GetTemplate {
                name,
                workspace_path,
            } => {
                let templates_dir = PathBuf::from(workspace_path.as_deref().unwrap_or("workspace"))
                    .join("_templates");
                let template_path = templates_dir.join(format!("{}.md", name));

                // Check workspace templates first
                if self.fs().exists(&template_path).await {
                    let content = self
                        .fs()
                        .read_to_string(&template_path)
                        .await
                        .map_err(|e| DiaryxError::FileRead {
                            path: template_path,
                            source: e,
                        })?;
                    return Ok(Response::String(content));
                }

                // Return built-in template
                let content = match name.as_str() {
                    "note" => "---\ntitle: \"{{title}}\"\ncreated: \"{{date}}\"\n---\n\n",
                    "daily" => {
                        "---\ntitle: \"{{title}}\"\ncreated: \"{{date}}\"\n---\n\n## Today\n\n"
                    }
                    _ => return Err(DiaryxError::TemplateNotFound(name)),
                };
                Ok(Response::String(content.to_string()))
            }

            Command::SaveTemplate {
                name,
                content,
                workspace_path,
            } => {
                let templates_dir = PathBuf::from(&workspace_path).join("_templates");
                self.fs().create_dir_all(&templates_dir).await?;

                let template_path = templates_dir.join(format!("{}.md", name));
                self.fs()
                    .write_file(&template_path, &content)
                    .await
                    .map_err(|e| DiaryxError::FileWrite {
                        path: template_path,
                        source: e,
                    })?;

                Ok(Response::Ok)
            }

            Command::DeleteTemplate {
                name,
                workspace_path,
            } => {
                let template_path = PathBuf::from(&workspace_path)
                    .join("_templates")
                    .join(format!("{}.md", name));

                self.fs().delete_file(&template_path).await.map_err(|e| {
                    DiaryxError::FileWrite {
                        path: template_path,
                        source: e,
                    }
                })?;

                Ok(Response::Ok)
            }

            // === Attachment Operations ===
            Command::UploadAttachment {
                entry_path,
                filename,
                data_base64,
            } => {
                use base64::{Engine as _, engine::general_purpose::STANDARD};

                let entry = PathBuf::from(&entry_path);
                let entry_dir = entry.parent().unwrap_or_else(|| Path::new("."));
                let attachments_dir = entry_dir.join("_attachments");

                // Create _attachments directory if needed
                self.fs().create_dir_all(&attachments_dir).await?;

                // Decode base64 data
                let data = STANDARD.decode(&data_base64).map_err(|e| {
                    DiaryxError::Unsupported(format!("Failed to decode base64: {}", e))
                })?;

                // Write file
                let dest_path = attachments_dir.join(&filename);
                self.fs()
                    .write_binary(&dest_path, &data)
                    .await
                    .map_err(|e| DiaryxError::FileWrite {
                        path: dest_path.clone(),
                        source: e,
                    })?;

                // Add to frontmatter attachments
                let attachment_rel_path = format!("_attachments/{}", filename);
                self.entry()
                    .add_attachment(&entry_path, &attachment_rel_path)
                    .await?;

                Ok(Response::String(attachment_rel_path))
            }

            Command::DeleteAttachment {
                entry_path,
                attachment_path,
            } => {
                let entry = PathBuf::from(&entry_path);
                let entry_dir = entry.parent().unwrap_or_else(|| Path::new("."));
                let full_path = entry_dir.join(&attachment_path);

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

                // Remove from frontmatter
                self.entry()
                    .remove_attachment(&entry_path, &attachment_path)
                    .await?;

                Ok(Response::Ok)
            }

            Command::GetAttachmentData {
                entry_path,
                attachment_path,
            } => {
                use crate::utils::path::normalize_path;

                let entry = PathBuf::from(&entry_path);
                let entry_dir = entry.parent().unwrap_or_else(|| Path::new("."));
                // Normalize the path to handle .. components (important for inherited attachments)
                let full_path = normalize_path(&entry_dir.join(&attachment_path));

                let data =
                    self.fs()
                        .read_binary(&full_path)
                        .await
                        .map_err(|e| DiaryxError::FileRead {
                            path: full_path,
                            source: e,
                        })?;

                Ok(Response::Bytes(data))
            }

            Command::MoveAttachment {
                source_entry_path,
                target_entry_path,
                attachment_path,
                new_filename,
            } => {
                // Resolve source paths
                let source_entry = PathBuf::from(&source_entry_path);
                let source_dir = source_entry.parent().unwrap_or_else(|| Path::new("."));
                let source_attachment_path = source_dir.join(&attachment_path);

                // Get the original filename
                let original_filename = source_attachment_path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .ok_or_else(|| DiaryxError::InvalidPath {
                        path: source_attachment_path.clone(),
                        message: "Could not extract filename".to_string(),
                    })?;

                // Determine final filename (use new_filename if provided, otherwise original)
                let final_filename = new_filename.as_deref().unwrap_or(original_filename);

                // Resolve target paths
                let target_entry = PathBuf::from(&target_entry_path);
                let target_dir = target_entry.parent().unwrap_or_else(|| Path::new("."));
                let target_attachments_dir = target_dir.join("_attachments");
                let target_attachment_path = target_attachments_dir.join(final_filename);

                // Check for collision at destination
                if self.fs().exists(&target_attachment_path).await {
                    return Err(DiaryxError::InvalidPath {
                        path: target_attachment_path,
                        message: "File already exists at destination".to_string(),
                    });
                }

                // Read the source file data
                let data = self
                    .fs()
                    .read_binary(&source_attachment_path)
                    .await
                    .map_err(|e| DiaryxError::FileRead {
                        path: source_attachment_path.clone(),
                        source: e,
                    })?;

                // Create target _attachments directory if needed
                self.fs().create_dir_all(&target_attachments_dir).await?;

                // Write to target location
                self.fs()
                    .write_binary(&target_attachment_path, &data)
                    .await
                    .map_err(|e| DiaryxError::FileWrite {
                        path: target_attachment_path.clone(),
                        source: e,
                    })?;

                // Update frontmatter: remove from source, add to target
                self.entry()
                    .remove_attachment(&source_entry_path, &attachment_path)
                    .await?;
                let target_rel_path = format!("_attachments/{}", final_filename);
                self.entry()
                    .add_attachment(&target_entry_path, &target_rel_path)
                    .await?;

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

                Ok(Response::String(target_rel_path))
            }

            // === Storage Operations ===
            Command::GetStorageUsage => {
                // This requires knowledge of the workspace path which we don't have
                // Return basic info - clients can calculate usage themselves
                Ok(Response::StorageInfo(crate::command::StorageInfo {
                    used: 0,
                    limit: None,
                    attachment_limit: None,
                }))
            }

            // === CRDT Operations ===
            #[cfg(feature = "crdt")]
            Command::GetSyncState { doc_name: _ } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                Ok(Response::Binary(crdt.get_state_vector()))
            }

            #[cfg(feature = "crdt")]
            Command::ApplyRemoteUpdate {
                doc_name: _,
                update,
            } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let update_id = crdt.apply_update(&update, crate::crdt::UpdateOrigin::Remote)?;
                Ok(Response::UpdateId(update_id))
            }

            #[cfg(feature = "crdt")]
            Command::GetMissingUpdates {
                doc_name: _,
                remote_state_vector,
            } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let update = crdt.get_missing_updates(&remote_state_vector)?;
                Ok(Response::Binary(update))
            }

            #[cfg(feature = "crdt")]
            Command::GetFullState { doc_name: _ } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                Ok(Response::Binary(crdt.get_full_state()))
            }

            #[cfg(feature = "crdt")]
            Command::GetHistory { doc_name, limit } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let history_manager = crate::crdt::HistoryManager::new(crdt.storage().clone());
                let history = history_manager.get_history(&doc_name, limit)?;
                let entries: Vec<crate::command::CrdtHistoryEntry> = history
                    .into_iter()
                    .map(|u| crate::command::CrdtHistoryEntry {
                        update_id: u.update_id,
                        timestamp: u.timestamp,
                        origin: u.origin,
                        files_changed: u.files_changed,
                        device_id: u.device_id,
                        device_name: u.device_name,
                    })
                    .collect();
                Ok(Response::CrdtHistory(entries))
            }

            #[cfg(feature = "crdt")]
            Command::GetFileHistory { file_path, limit } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let history_manager = crate::crdt::HistoryManager::new(crdt.storage().clone());
                let history = history_manager.get_file_history(&file_path, limit)?;
                let entries: Vec<crate::command::CrdtHistoryEntry> = history
                    .into_iter()
                    .map(|u| crate::command::CrdtHistoryEntry {
                        update_id: u.update_id,
                        timestamp: u.timestamp,
                        origin: u.origin,
                        files_changed: u.files_changed,
                        device_id: u.device_id,
                        device_name: u.device_name,
                    })
                    .collect();
                Ok(Response::CrdtHistory(entries))
            }

            #[cfg(feature = "crdt")]
            Command::RestoreVersion {
                doc_name,
                update_id,
            } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let history_manager = crate::crdt::HistoryManager::new(crdt.storage().clone());
                let restore_update = history_manager.create_restore_update(&doc_name, update_id)?;
                crdt.apply_update(&restore_update, crate::crdt::UpdateOrigin::Local)?;
                crdt.save()?;
                Ok(Response::Ok)
            }

            #[cfg(feature = "crdt")]
            Command::GetVersionDiff {
                doc_name,
                from_id,
                to_id,
            } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let history_manager = crate::crdt::HistoryManager::new(crdt.storage().clone());
                let diffs = history_manager.diff(&doc_name, from_id, to_id)?;
                Ok(Response::VersionDiff(diffs))
            }

            #[cfg(feature = "crdt")]
            Command::GetStateAt {
                doc_name,
                update_id,
            } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let history_manager = crate::crdt::HistoryManager::new(crdt.storage().clone());
                let state = history_manager.get_state_at(&doc_name, update_id)?;
                match state {
                    Some(data) => Ok(Response::Binary(data)),
                    None => Ok(Response::Ok),
                }
            }

            #[cfg(feature = "crdt")]
            Command::GetCrdtFile { path } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                Ok(Response::CrdtFile(crdt.get_file(&path)))
            }

            #[cfg(feature = "crdt")]
            Command::SetCrdtFile { path, metadata } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let file_metadata: crate::crdt::FileMetadata = serde_json::from_value(metadata)
                    .map_err(|e| DiaryxError::Unsupported(format!("Invalid metadata: {}", e)))?;
                crdt.set_file(&path, file_metadata)?;
                Ok(Response::Ok)
            }

            #[cfg(feature = "crdt")]
            Command::ListCrdtFiles { include_deleted } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let files = if include_deleted {
                    crdt.list_files()
                } else {
                    crdt.list_active_files()
                };
                Ok(Response::CrdtFiles(files))
            }

            #[cfg(feature = "crdt")]
            Command::SaveCrdtState { doc_name: _ } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                crdt.save()?;
                Ok(Response::Ok)
            }

            // ==================== Body Document Commands ====================
            #[cfg(feature = "crdt")]
            Command::GetBodyContent { doc_name } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                match crdt.get_body_content(&doc_name) {
                    Some(content) => Ok(Response::String(content)),
                    None => Ok(Response::String(String::new())),
                }
            }

            #[cfg(feature = "crdt")]
            Command::SetBodyContent { doc_name, content } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                crdt.set_body_content(&doc_name, &content)?;
                Ok(Response::Ok)
            }

            #[cfg(feature = "crdt")]
            Command::GetBodySyncState { doc_name } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                match crdt.get_body_sync_state(&doc_name) {
                    Some(state) => Ok(Response::Binary(state)),
                    None => Ok(Response::Binary(Vec::new())),
                }
            }

            #[cfg(feature = "crdt")]
            Command::GetBodyFullState { doc_name } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                match crdt.get_body_full_state(&doc_name) {
                    Some(state) => Ok(Response::Binary(state)),
                    None => Ok(Response::Binary(Vec::new())),
                }
            }

            #[cfg(feature = "crdt")]
            Command::ApplyBodyUpdate { doc_name, update } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let update_id =
                    crdt.apply_body_update(&doc_name, &update, crate::crdt::UpdateOrigin::Remote)?;
                Ok(Response::UpdateId(update_id))
            }

            #[cfg(feature = "crdt")]
            Command::GetBodyMissingUpdates {
                doc_name,
                remote_state_vector,
            } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let diff = crdt.get_body_missing_updates(&doc_name, &remote_state_vector)?;
                Ok(Response::Binary(diff))
            }

            #[cfg(feature = "crdt")]
            Command::SaveBodyDoc { doc_name } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                crdt.save_body_doc(&doc_name)?;
                Ok(Response::Ok)
            }

            #[cfg(feature = "crdt")]
            Command::SaveAllBodyDocs => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                crdt.save_all_body_docs()?;
                Ok(Response::Ok)
            }

            #[cfg(feature = "crdt")]
            Command::ListLoadedBodyDocs => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                Ok(Response::Strings(crdt.loaded_body_docs()))
            }

            #[cfg(feature = "crdt")]
            Command::UnloadBodyDoc { doc_name } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                crdt.unload_body_doc(&doc_name);
                Ok(Response::Ok)
            }

            // ==================== Sync Protocol Commands ====================
            #[cfg(feature = "crdt")]
            Command::CreateSyncStep1 { doc_name } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let message = crdt.create_sync_step1(&doc_name);
                Ok(Response::Binary(message))
            }

            #[cfg(feature = "crdt")]
            Command::HandleSyncMessage { doc_name, message } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let response = crdt.handle_sync_message(&doc_name, &message)?;
                match response {
                    Some(data) => Ok(Response::Binary(data)),
                    None => Ok(Response::Ok),
                }
            }

            #[cfg(feature = "crdt")]
            Command::CreateUpdateMessage { doc_name, update } => {
                let crdt = self.crdt().ok_or_else(|| {
                    DiaryxError::Unsupported("CRDT not enabled for this instance".to_string())
                })?;
                let message = crdt.create_update_message(&doc_name, &update);
                Ok(Response::Binary(message))
            }
        }
    }
}