diaryx_core 0.11.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
//! Backup system for persisting workspace data to various targets.
//!
//! This module provides abstractions for backing up workspace data to
//! configurable targets (local drive, cloud storage, etc.).
//!
//! This module is async-first to support WASM environments (e.g. IndexedDB-backed
//! filesystems) while remaining usable on native targets.
//!
//! Notes:
//! - Many higher-level Diaryx clients may not use this module yet.
//! - Native-only targets (like local drive) are gated behind `cfg(not(wasm32))`.

use crate::fs::{AsyncFileSystem, BoxFuture};
use std::path::{Path, PathBuf};
use std::time::Duration;

// ============================================================================
// Configuration Types
// ============================================================================

/// Configuration for error handling behavior during backup operations.
#[derive(Clone, Debug, Default)]
pub enum FailurePolicy {
    /// Log error and continue with other targets
    #[default]
    Continue,
    /// Retry N times with exponential backoff before continuing
    Retry(u32),
    /// Abort all backup operations on failure
    Abort,
}

// ============================================================================
// Cloud Backup Configuration (Serializable)
// ============================================================================

use serde::{Deserialize, Serialize};

/// Cloud storage provider configuration.
///
/// This is a serializable configuration type. Actual implementations
/// of cloud backup targets live in platform-specific apps (Tauri, WASM).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum CloudProvider {
    /// Amazon S3 or S3-compatible storage
    S3 {
        /// name of bucket
        bucket: String,
        /// region of bucket
        region: String,
        #[serde(default)]
        /// optional prefix for bucket files
        prefix: Option<String>,
        #[serde(default)]
        /// site where bucket is
        endpoint: Option<String>, // For S3-compatible (MinIO, etc.)
    },
    /// Google Drive
    GoogleDrive {
        #[serde(default)]
        /// optional name of folder
        folder_id: Option<String>,
    },
    /// WebDAV (Nextcloud, ownCloud, etc.)
    WebDAV {
        /// url of webdav
        url: String,
    },
}

/// Configuration for a cloud backup target.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CloudBackupConfig {
    /// Unique identifier for this backup target
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Cloud provider configuration
    pub provider: CloudProvider,
    /// Whether this target is enabled for automatic backups
    #[serde(default = "default_enabled")]
    pub enabled: bool,
}

fn default_enabled() -> bool {
    true
}

/// Result of a backup or restore operation.
#[derive(Debug)]
pub struct BackupResult {
    /// Whether the operation completed successfully
    pub success: bool,
    /// Number of files processed
    pub files_processed: usize,
    /// Error message if the operation failed
    pub error: Option<String>,
}

impl BackupResult {
    /// Create a successful result
    pub fn success(files_processed: usize) -> Self {
        Self {
            success: true,
            files_processed,
            error: None,
        }
    }

    /// Create a failed result
    pub fn failure(error: impl Into<String>) -> Self {
        Self {
            success: false,
            files_processed: 0,
            error: Some(error.into()),
        }
    }
}

// ============================================================================
// BackupTarget Trait
// ============================================================================

/// Trait for backup targets (one-way persistence).
///
/// A `BackupTarget` represents a destination where workspace data can be
/// persisted for backup purposes. This is a one-way operation: data flows
/// from the working filesystem to the target.
///
/// For bidirectional sync, see `SyncTarget`.
pub trait BackupTarget: Send + Sync {
    /// Human-readable name for this target (e.g., "Local Backup", "Google Drive")
    fn name(&self) -> &str;

    /// How often this target should be backed up.
    ///
    /// The backup manager will use this to schedule automatic backups.
    fn frequency(&self) -> Duration;

    /// What to do when backup fails.
    fn failure_policy(&self) -> FailurePolicy;

    /// Persist all files from filesystem to this target.
    ///
    /// This should copy all relevant files from the source filesystem
    /// to the backup target.
    fn backup<'a>(
        &'a self,
        fs: &'a dyn AsyncFileSystem,
        workspace_path: &'a Path,
    ) -> BoxFuture<'a, BackupResult>;

    /// Restore all files from this target into filesystem.
    ///
    /// This should copy all files from the backup target into the
    /// destination filesystem.
    fn restore<'a>(
        &'a self,
        fs: &'a dyn AsyncFileSystem,
        workspace_path: &'a Path,
    ) -> BoxFuture<'a, BackupResult>;

    /// Check if this target is available/accessible.
    ///
    /// For example, a local drive target might check if the path exists,
    /// while a cloud target might ping the service.
    fn is_available(&self) -> bool;

    /// Get timestamp of last successful backup.
    ///
    /// Returns `None` if no backup has been performed yet.
    fn get_last_sync(&self) -> Option<std::time::SystemTime> {
        None // Default implementation
    }
}

// ============================================================================
// SyncTarget Trait (for bidirectional sync)
// ============================================================================

/// Result of a sync operation.
#[derive(Debug)]
pub struct SyncResult {
    /// Whether the operation completed successfully
    pub success: bool,
    /// Number of files pulled from remote
    pub files_pulled: usize,
    /// Number of files pushed to remote
    pub files_pushed: usize,
    /// List of conflicts that need resolution
    pub conflicts: Vec<Conflict>,
    /// Error message if the operation failed
    pub error: Option<String>,
}

impl SyncResult {
    /// Create a successful sync result
    pub fn success(files_pulled: usize, files_pushed: usize) -> Self {
        Self {
            success: true,
            files_pulled,
            files_pushed,
            conflicts: Vec::new(),
            error: None,
        }
    }

    /// Create a failed sync result
    pub fn failure(error: impl Into<String>) -> Self {
        Self {
            success: false,
            files_pulled: 0,
            files_pushed: 0,
            conflicts: Vec::new(),
            error: Some(error.into()),
        }
    }

    /// Create a result with conflicts
    pub fn with_conflicts(conflicts: Vec<Conflict>) -> Self {
        Self {
            success: false,
            files_pulled: 0,
            files_pushed: 0,
            conflicts,
            error: Some("Conflicts detected".to_string()),
        }
    }
}

/// A file conflict between local and remote versions.
#[derive(Debug, Clone)]
pub struct Conflict {
    /// Path to the conflicting file
    pub path: PathBuf,
    /// Local modification timestamp
    pub local_modified: std::time::SystemTime,
    /// Remote modification timestamp
    pub remote_modified: std::time::SystemTime,
}

/// How to resolve a conflict.
#[derive(Debug, Clone)]
pub enum Resolution {
    /// Keep the local version
    KeepLocal,
    /// Keep the remote version
    KeepRemote,
    /// Use merged content (for future CRDT support)
    Merge(String),
}

/// Trait for sync targets (bidirectional persistence).
///
/// Extends `BackupTarget` with conflict detection and resolution.
/// Used for cloud sync and multi-device scenarios.
pub trait SyncTarget: BackupTarget {
    /// Pull changes from remote, returning any conflicts.
    fn pull<'a>(
        &'a self,
        fs: &'a dyn AsyncFileSystem,
        workspace_path: &'a Path,
    ) -> BoxFuture<'a, SyncResult>;

    /// Push local changes to remote.
    fn push<'a>(
        &'a self,
        fs: &'a dyn AsyncFileSystem,
        workspace_path: &'a Path,
    ) -> BoxFuture<'a, SyncResult>;

    /// Resolve a conflict using the specified resolution strategy.
    fn resolve_conflict<'a>(
        &'a self,
        fs: &'a dyn AsyncFileSystem,
        workspace_path: &'a Path,
        conflict: &'a Conflict,
        resolution: Resolution,
    ) -> BoxFuture<'a, BackupResult>;
}

// ============================================================================
// BackupManager
// ============================================================================

/// Manages multiple backup targets.
///
/// The `BackupManager` coordinates backups across multiple targets,
/// handling scheduling, error policies, and restore prioritization.
pub struct BackupManager {
    targets: Vec<Box<dyn BackupTarget>>,
    primary_index: Option<usize>,
}

impl Default for BackupManager {
    fn default() -> Self {
        Self::new()
    }
}

impl BackupManager {
    /// Create a new empty backup manager.
    pub fn new() -> Self {
        Self {
            targets: Vec::new(),
            primary_index: None,
        }
    }

    /// Add a backup target.
    ///
    /// The first target added becomes the primary by default.
    pub fn add_target(&mut self, target: Box<dyn BackupTarget>) {
        self.targets.push(target);
        if self.primary_index.is_none() {
            self.primary_index = Some(0);
        }
    }

    /// Set the primary target by name.
    ///
    /// The primary target is used for restore operations.
    /// Returns `true` if the target was found and set as primary.
    pub fn set_primary(&mut self, name: &str) -> bool {
        for (i, target) in self.targets.iter().enumerate() {
            if target.name() == name {
                self.primary_index = Some(i);
                return true;
            }
        }
        false
    }

    /// Get the primary target name.
    pub fn primary_name(&self) -> Option<&str> {
        self.primary_index
            .and_then(|i| self.targets.get(i))
            .map(|t| t.name())
    }

    /// Get all target names.
    pub fn target_names(&self) -> Vec<&str> {
        self.targets.iter().map(|t| t.name()).collect()
    }

    /// Backup to all available targets.
    ///
    /// Returns a result for each target, in the same order as added.
    pub async fn backup_all(
        &self,
        fs: &dyn AsyncFileSystem,
        workspace_path: &Path,
    ) -> Vec<BackupResult> {
        let mut results = Vec::with_capacity(self.targets.len());

        for target in &self.targets {
            if !target.is_available() {
                results.push(BackupResult::failure(format!(
                    "Target '{}' is not available",
                    target.name()
                )));
                continue;
            }

            let result = target.backup(fs, workspace_path).await;

            // Handle failure policy
            if !result.success {
                match target.failure_policy() {
                    FailurePolicy::Abort => {
                        results.push(result);
                        break; // Stop processing further targets
                    }
                    FailurePolicy::Retry(max_retries) => {
                        // Simple retry logic (no exponential backoff in this MVP)
                        let mut final_result = result;
                        for _ in 0..max_retries {
                            final_result = target.backup(fs, workspace_path).await;
                            if final_result.success {
                                break;
                            }
                        }
                        results.push(final_result);
                    }
                    FailurePolicy::Continue => {
                        results.push(result);
                    }
                }
            } else {
                results.push(result);
            }
        }

        results
    }

    /// Restore from the primary target.
    ///
    /// Returns `None` if no primary target is set.
    pub async fn restore_from_primary(
        &self,
        fs: &dyn AsyncFileSystem,
        workspace_path: &Path,
    ) -> Option<BackupResult> {
        let primary = self.primary_index.and_then(|i| self.targets.get(i))?;

        if !primary.is_available() {
            return Some(BackupResult::failure(format!(
                "Primary target '{}' is not available",
                primary.name()
            )));
        }

        Some(primary.restore(fs, workspace_path).await)
    }
}

// ============================================================================
// LocalDriveTarget - Native platforms only
// ============================================================================

/// Backup target that persists to a local directory.
///
/// This copies all workspace files to a specified backup directory.
#[cfg(not(target_arch = "wasm32"))]
pub struct LocalDriveTarget {
    /// Name of this target
    name: String,
    /// Path to the backup directory
    backup_path: PathBuf,
    /// How often to backup
    frequency: Duration,
    /// What to do on failure
    failure_policy: FailurePolicy,
}

#[cfg(not(target_arch = "wasm32"))]
impl LocalDriveTarget {
    /// Create a new local drive backup target.
    pub fn new(name: impl Into<String>, backup_path: PathBuf) -> Self {
        Self {
            name: name.into(),
            backup_path,
            frequency: Duration::from_secs(300), // 5 minutes default
            failure_policy: FailurePolicy::Continue,
        }
    }

    /// Set the backup frequency.
    pub fn with_frequency(mut self, frequency: Duration) -> Self {
        self.frequency = frequency;
        self
    }

    /// Set the failure policy.
    pub fn with_failure_policy(mut self, policy: FailurePolicy) -> Self {
        self.failure_policy = policy;
        self
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl BackupTarget for LocalDriveTarget {
    fn name(&self) -> &str {
        &self.name
    }

    fn frequency(&self) -> Duration {
        self.frequency
    }

    fn failure_policy(&self) -> FailurePolicy {
        self.failure_policy.clone()
    }

    fn backup<'a>(
        &'a self,
        fs: &'a dyn AsyncFileSystem,
        workspace_path: &'a Path,
    ) -> BoxFuture<'a, BackupResult> {
        Box::pin(async move {
            use std::fs as std_fs;

            // Ensure backup directory exists
            if let Err(e) = std_fs::create_dir_all(&self.backup_path) {
                return BackupResult::failure(format!("Failed to create backup directory: {}", e));
            }

            // Get all files in workspace
            let files = match fs.list_all_files_recursive(workspace_path).await {
                Ok(files) => files,
                Err(e) => return BackupResult::failure(format!("Failed to list files: {}", e)),
            };

            let mut files_processed = 0;

            for file_path in files {
                // Skip directories
                if fs.is_dir(&file_path).await {
                    continue;
                }

                // Calculate relative path from workspace
                let relative = match file_path.strip_prefix(workspace_path) {
                    Ok(rel) => rel,
                    Err(_) => continue,
                };

                let dest_path = self.backup_path.join(relative);

                // Ensure parent directory exists
                if let Some(parent) = dest_path.parent()
                    && let Err(e) = std_fs::create_dir_all(parent)
                {
                    return BackupResult::failure(format!(
                        "Failed to create directory {:?}: {}",
                        parent, e
                    ));
                }

                // Prefer binary copy to avoid encoding surprises; fall back to string.
                let bytes = match fs.read_binary(&file_path).await {
                    Ok(bytes) => bytes,
                    Err(_) => match fs.read_to_string(&file_path).await {
                        Ok(s) => s.into_bytes(),
                        Err(e) => {
                            return BackupResult::failure(format!(
                                "Failed to read file {:?}: {}",
                                file_path, e
                            ));
                        }
                    },
                };

                if let Err(e) = std_fs::write(&dest_path, &bytes) {
                    return BackupResult::failure(format!(
                        "Failed to write file {:?}: {}",
                        dest_path, e
                    ));
                }

                files_processed += 1;
            }

            BackupResult::success(files_processed)
        })
    }

    fn restore<'a>(
        &'a self,
        fs: &'a dyn AsyncFileSystem,
        workspace_path: &'a Path,
    ) -> BoxFuture<'a, BackupResult> {
        Box::pin(async move {
            use std::fs as std_fs;

            if !self.backup_path.exists() {
                return BackupResult::failure("Backup directory does not exist");
            }

            let mut files_processed = 0;

            // Walk the backup directory
            fn visit_dir<'a>(
                dir: PathBuf,
                backup_root: PathBuf,
                workspace_path: PathBuf,
                fs: &'a dyn AsyncFileSystem,
                files_processed: &'a mut usize,
            ) -> BoxFuture<'a, Result<(), String>> {
                Box::pin(async move {
                    let entries = std_fs::read_dir(&dir)
                        .map_err(|e| format!("Failed to read directory {:?}: {}", dir, e))?;

                    for entry in entries {
                        let entry =
                            entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
                        let path = entry.path();

                        if path.is_dir() {
                            visit_dir(
                                path,
                                backup_root.clone(),
                                workspace_path.clone(),
                                fs,
                                files_processed,
                            )
                            .await?;
                        } else {
                            let relative = path
                                .strip_prefix(&backup_root)
                                .map_err(|_| "Failed to calculate relative path")?;
                            let dest_path = workspace_path.join(relative);

                            // Ensure parent directory exists in target filesystem
                            if let Some(parent) = dest_path.parent() {
                                fs.create_dir_all(parent).await.map_err(|e| {
                                    format!("Failed to create directory {:?}: {}", parent, e)
                                })?;
                            }

                            // Read bytes and write bytes.
                            //
                            // NOTE: For maximum compatibility across Diaryx filesystem implementations (including WASM/in-memory),
                            // we write restored files as UTF-8-ish text. This is a compromise: true binary attachments should be
                            // handled by an attachment-specific restore path in the future.
                            let bytes = std_fs::read(&path)
                                .map_err(|e| format!("Failed to read file {:?}: {}", path, e))?;

                            let s = String::from_utf8_lossy(&bytes).into_owned();
                            fs.write_file(&dest_path, &s).await.map_err(|e| {
                                format!("Failed to write file {:?}: {}", dest_path, e)
                            })?;

                            *files_processed += 1;
                        }
                    }

                    Ok(())
                })
            }

            match visit_dir(
                self.backup_path.clone(),
                self.backup_path.clone(),
                workspace_path.to_path_buf(),
                fs,
                &mut files_processed,
            )
            .await
            {
                Ok(()) => BackupResult::success(files_processed),
                Err(e) => BackupResult::failure(e),
            }
        })
    }

    fn is_available(&self) -> bool {
        // Check if we can access the parent directory
        self.backup_path
            .parent()
            .map(|p| p.exists() || p.as_os_str().is_empty())
            .unwrap_or(true)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_backup_result_success() {
        let result = BackupResult::success(10);
        assert!(result.success);
        assert_eq!(result.files_processed, 10);
        assert!(result.error.is_none());
    }

    #[test]
    fn test_backup_result_failure() {
        let result = BackupResult::failure("Something went wrong");
        assert!(!result.success);
        assert_eq!(result.files_processed, 0);
        assert_eq!(result.error, Some("Something went wrong".to_string()));
    }

    #[test]
    fn test_backup_manager_empty() {
        let manager = BackupManager::new();
        assert!(manager.target_names().is_empty());
        assert!(manager.primary_name().is_none());
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_local_drive_target_creation() {
        let target = LocalDriveTarget::new("Test Backup", PathBuf::from("/tmp/backup"))
            .with_frequency(Duration::from_secs(60))
            .with_failure_policy(FailurePolicy::Retry(3));

        assert_eq!(target.name(), "Test Backup");
        assert_eq!(target.frequency(), Duration::from_secs(60));
        matches!(target.failure_policy(), FailurePolicy::Retry(3));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_backup_manager_add_target() {
        let mut manager = BackupManager::new();
        let target = LocalDriveTarget::new("Test", PathBuf::from("/tmp/backup"));
        manager.add_target(Box::new(target));

        assert_eq!(manager.target_names(), vec!["Test"]);
        assert_eq!(manager.primary_name(), Some("Test"));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_backup_manager_set_primary() {
        let mut manager = BackupManager::new();
        manager.add_target(Box::new(LocalDriveTarget::new(
            "First",
            PathBuf::from("/tmp/first"),
        )));
        manager.add_target(Box::new(LocalDriveTarget::new(
            "Second",
            PathBuf::from("/tmp/second"),
        )));

        assert_eq!(manager.primary_name(), Some("First"));
        assert!(manager.set_primary("Second"));
        assert_eq!(manager.primary_name(), Some("Second"));
        assert!(!manager.set_primary("NonExistent"));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_backup_and_restore_integration() {
        use crate::fs::InMemoryFileSystem;
        use tempfile::tempdir;

        // Create a workspace with some files (sync fs)
        let fs = InMemoryFileSystem::new();
        let workspace = PathBuf::from("/workspace");
        fs.create_dir_all(&workspace).unwrap();
        fs.write_file(&workspace.join("test.md"), "# Hello World")
            .unwrap();
        fs.write_file(&workspace.join("subdir/nested.md"), "Nested content")
            .unwrap();

        // Wrap in async adapter for the async-first backup APIs
        let async_fs = SyncToAsyncFs::new(fs);

        // Create backup target pointing to temp directory
        let backup_dir = tempdir().unwrap();
        let target = LocalDriveTarget::new("Test Backup", backup_dir.path().to_path_buf());

        // Backup (async)
        let result = crate::fs::block_on_test(target.backup(&async_fs, &workspace));
        assert!(result.success, "Backup failed: {:?}", result.error);
        assert_eq!(result.files_processed, 2);

        // Verify files exist in backup
        assert!(backup_dir.path().join("test.md").exists());
        assert!(backup_dir.path().join("subdir/nested.md").exists());

        // Create a fresh filesystem and restore into it
        let fs2 = InMemoryFileSystem::new();
        fs2.create_dir_all(&workspace).unwrap();
        let async_fs2 = SyncToAsyncFs::new(fs2);

        // IMPORTANT: restore expects the workspace root to exist in the destination FS
        // (we already created it above via `create_dir_all`).
        let restore_result = crate::fs::block_on_test(target.restore(&async_fs2, &workspace));
        assert!(
            restore_result.success,
            "Restore failed: {:?}",
            restore_result.error
        );
        assert_eq!(restore_result.files_processed, 2);

        // Verify restored content (read back via the inner sync fs)
        let fs2_inner = async_fs2.into_inner();
        let content = fs2_inner
            .read_to_string(&workspace.join("test.md"))
            .unwrap();
        assert_eq!(content, "# Hello World");

        let nested = fs2_inner
            .read_to_string(&workspace.join("subdir/nested.md"))
            .unwrap();
        assert_eq!(nested, "Nested content");
    }
}