treeboot-core 0.4.1

Reusable worktree bootstrap engine for the treeboot CLI.
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
use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};

use crate::config::{
    Config, FileOperationSettings, FileOperationSettingsInput, RuntimeOptionOverrides,
    normalize_file_operation_settings,
};
use crate::context;
use crate::{
    ActionPlan, ActionPlanOptions, Error, ExecuteOptions, Executor, FileOperation,
    FileOperationKind, OutputEvent, PlanOrigin, Reporter, Result, SourceSpan, SymlinkMode,
    SyncCompare, Worktree, WorktreeOptions,
};

/// Options for building manual file operation specs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManualFileOperationOptions {
    /// File operation kind to build.
    pub operation: FileOperationKind,
    /// Source paths resolved from the root checkout.
    pub sources: Vec<PathBuf>,
    /// Optional target path resolved from the current worktree.
    pub target: Option<PathBuf>,
    /// Fails when a source is missing.
    pub required: bool,
    /// How copy and sync should treat source symlinks.
    pub symlinks: Option<SymlinkMode>,
    /// Sync comparison mode.
    pub compare: Option<SyncCompare>,
    /// Whether sync should delete target-only files.
    pub delete: Option<bool>,
}

impl Default for ManualFileOperationOptions {
    fn default() -> Self {
        Self {
            operation: FileOperationKind::Copy,
            sources: Vec::new(),
            target: None,
            required: false,
            symlinks: None,
            compare: None,
            delete: None,
        }
    }
}

impl FileOperation {
    /// Builds normalized manual file operation specs for an action plan.
    ///
    /// This applies the same target derivation and option validation used by
    /// `treeboot copy`, `treeboot symlink`, and `treeboot sync`.
    ///
    /// # Errors
    ///
    /// Returns an error when the manual operation has no sources, when an
    /// option is not valid for the selected operation kind, or when a target
    /// cannot be derived for an absolute source.
    pub fn from_manual_options(
        context: &Worktree,
        options: ManualFileOperationOptions,
    ) -> Result<Vec<Self>> {
        let settings = validate_manual_options(
            options.operation,
            &options.sources,
            options.symlinks,
            options.compare,
            options.delete,
        )?;
        manual_operations(options, context, settings)
    }
}

/// Options for running one manual file operation command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileOperationOptions {
    /// Directory from which the operation starts. Defaults to the process cwd.
    pub cwd: Option<PathBuf>,
    /// Overrides the root checkout used as the source base.
    pub root: Option<PathBuf>,
    /// File operation kind to run.
    pub operation: FileOperationKind,
    /// Source paths resolved from the root checkout.
    pub sources: Vec<PathBuf>,
    /// Optional target path resolved from the current worktree.
    pub target: Option<PathBuf>,
    /// Fails when a source is missing.
    pub required: bool,
    /// How copy and sync should treat source symlinks.
    pub symlinks: Option<SymlinkMode>,
    /// Sync comparison mode.
    pub compare: Option<SyncCompare>,
    /// Whether sync should delete target-only files.
    pub delete: Option<bool>,
    /// Fails on stricter file-operation conflicts.
    pub strict: bool,
    /// Replaces existing file-operation targets where supported.
    pub force: bool,
    /// Prints planned work without changing files.
    pub dry_run: bool,
}

impl Default for FileOperationOptions {
    fn default() -> Self {
        Self {
            cwd: None,
            root: None,
            operation: FileOperationKind::Copy,
            sources: Vec::new(),
            target: None,
            required: false,
            symlinks: None,
            compare: None,
            delete: None,
            strict: false,
            force: false,
            dry_run: false,
        }
    }
}

/// Completed action for a manual file operation invocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileOperationAction {
    /// The command started from the root checkout and had no work to do.
    RootWorktreeSkipped,
    /// File operations were planned and applied.
    Applied,
}

/// Result summary for a manual file operation invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileOperationReport {
    /// Runtime context used by the operation.
    pub context: Worktree,
    /// File operation kind that ran.
    pub operation: FileOperationKind,
    /// Completed action.
    pub action: FileOperationAction,
    /// Number of file actions that were applied or reported.
    pub action_count: usize,
}

/// Options for root-relative source completion.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FileOperationCompletionOptions {
    /// Directory from which completion starts. Defaults to the process cwd.
    pub cwd: Option<PathBuf>,
    /// Overrides the root checkout used as the completion base.
    pub root: Option<PathBuf>,
    /// Current partial value being completed.
    pub current: PathBuf,
}

/// Runs a manual copy, symlink, or sync file operation.
///
/// # Errors
///
/// Returns an error if context discovery fails, options are invalid,
/// validation rejects the operation, output reporting fails, or applying the
/// file operation fails.
pub fn run_file_operation(
    options: FileOperationOptions,
    reporter: &mut dyn Reporter,
) -> Result<FileOperationReport> {
    let FileOperationOptions {
        cwd,
        root,
        operation,
        sources,
        target,
        required,
        symlinks,
        compare,
        delete,
        strict,
        force,
        dry_run,
    } = options;
    let manual_options = ManualFileOperationOptions {
        operation,
        sources,
        target,
        required,
        symlinks,
        compare,
        delete,
    };

    let env_options = RuntimeOptionOverrides::from_env()?;
    let pre_config_strict = env_options.pre_config_strict(strict);
    let context = context::resolve(&WorktreeOptions { cwd, root })?;

    if context.root_path == context.worktree_path {
        report(reporter, OutputEvent::RootWorktreeDetected)?;

        if pre_config_strict {
            return Err(Error::RootWorktreeStrict);
        }

        return Ok(FileOperationReport {
            context,
            operation,
            action: FileOperationAction::RootWorktreeSkipped,
            action_count: 0,
        });
    }

    let config_options = Config::load_discovered(&context, None)?
        .map(|loaded| loaded.config.options)
        .unwrap_or_default();
    let plan_options = env_options.resolve(&config_options, strict);
    let operations = FileOperation::from_manual_options(&context, manual_options)?;
    let plan = ActionPlan::from_file_operations(
        &context,
        PlanOrigin::Manual { operation },
        &operations,
        ActionPlanOptions::from(plan_options),
    )?;
    let report = Executor::new(ExecuteOptions {
        strict: plan_options.strict,
        force,
        dry_run,
        skip_commands: true,
    })
    .execute_files(&plan, reporter)?;
    let context = plan.context;

    Ok(FileOperationReport {
        context,
        operation,
        action: FileOperationAction::Applied,
        action_count: report.file_action_count,
    })
}

/// Returns source completion candidates relative to the resolved root checkout.
///
/// Errors during context resolution or directory scanning are intentionally
/// quiet, making this suitable for shell completion hooks.
#[must_use]
pub fn file_operation_source_candidates(options: FileOperationCompletionOptions) -> Vec<String> {
    let Ok(context) = context::resolve(&WorktreeOptions {
        cwd: options.cwd,
        root: options.root,
    }) else {
        return Vec::new();
    };

    source_candidates(&context.root_path, &options.current)
}

fn validate_manual_options(
    operation: FileOperationKind,
    sources: &[PathBuf],
    symlinks: Option<SymlinkMode>,
    compare: Option<SyncCompare>,
    delete: Option<bool>,
) -> Result<FileOperationSettings> {
    if sources.is_empty() {
        return invalid_manual(operation, "at least one source is required");
    }

    normalize_file_operation_settings(
        operation,
        FileOperationSettingsInput {
            compare,
            delete,
            symlinks,
        },
    )
    .map_err(|field| Error::FileOperationInvalid {
        operation: operation.as_str(),
        message: format!(
            "`{}` is only valid for {}",
            field.name(),
            field.allowed_operations()
        ),
    })
}

fn manual_operations(
    options: ManualFileOperationOptions,
    context: &Worktree,
    settings: FileOperationSettings,
) -> Result<Vec<FileOperation>> {
    let ManualFileOperationOptions {
        operation,
        sources,
        target,
        required,
        ..
    } = options;
    let multiple_sources = sources.len() > 1;
    sources
        .into_iter()
        .map(|source| {
            let target = manual_target(operation, &source, target.as_deref(), multiple_sources)?;
            Ok(FileOperation {
                operation,
                source_path: resolve_path(&context.root_path, &source),
                target_path: resolve_path(&context.worktree_path, &target),
                source,
                target,
                required,
                compare: settings.compare,
                delete: settings.delete,
                symlinks: settings.symlinks,
                declaration: manual_span(),
            })
        })
        .collect()
}

fn manual_target(
    operation: FileOperationKind,
    source: &Path,
    target: Option<&Path>,
    multiple_sources: bool,
) -> Result<PathBuf> {
    match (target, multiple_sources) {
        (None, _) => Ok(source.to_path_buf()),
        (Some(target), false) => Ok(target.to_path_buf()),
        (Some(target), true) => {
            if source.is_absolute() {
                let Some(name) = source.file_name() else {
                    return invalid_manual(
                        operation,
                        format!("cannot derive target for source {}", source.display()),
                    );
                };
                return Ok(target.join(name));
            }

            Ok(target.join(source))
        }
    }
}

fn source_candidates(root: &Path, current: &Path) -> Vec<String> {
    if current.is_absolute()
        || current.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        })
    {
        return Vec::new();
    }

    let (search_prefix, needle) = split_candidate(current);
    let search_root = root.join(search_prefix);
    let Ok(entries) = std::fs::read_dir(search_root) else {
        return Vec::new();
    };
    let needle = needle.to_string_lossy();
    let mut candidates = entries
        .filter_map(|entry| {
            let entry = entry.ok()?;
            let name = entry.file_name();
            let name_lossy = name.to_string_lossy();
            if !name_lossy.starts_with(needle.as_ref()) {
                return None;
            }

            let mut candidate = search_prefix.to_path_buf();
            candidate.push(&name);
            let mut value = candidate.to_string_lossy().into_owned();
            if entry.file_type().ok()?.is_dir() {
                value.push(std::path::MAIN_SEPARATOR);
            }
            Some(value)
        })
        .collect::<Vec<_>>();

    candidates.sort();
    candidates
}

fn split_candidate(path: &Path) -> (&Path, &OsStr) {
    if path.as_os_str().is_empty() {
        return (Path::new(""), OsStr::new(""));
    }

    if has_trailing_separator(path) {
        return (path, OsStr::new(""));
    }

    (
        path.parent().unwrap_or_else(|| Path::new("")),
        path.file_name().unwrap_or_else(|| OsStr::new("")),
    )
}

fn has_trailing_separator(path: &Path) -> bool {
    path.as_os_str().to_string_lossy().ends_with(['/', '\\'])
}

fn resolve_path(base: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        base.join(path)
    }
}

const fn manual_span() -> SourceSpan {
    SourceSpan {
        start: 0,
        end: 0,
        line: 0,
        column: 0,
    }
}

fn invalid_manual<T>(operation: FileOperationKind, message: impl Into<String>) -> Result<T> {
    Err(Error::FileOperationInvalid {
        operation: operation.as_str(),
        message: message.into(),
    })
}

fn report(reporter: &mut dyn Reporter, event: OutputEvent) -> Result<()> {
    reporter
        .report(event)
        .map_err(|source| Error::Output { source })
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::ffi::OsString;
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::*;

    fn temp_workspace(name: &str) -> (PathBuf, PathBuf) {
        let id = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock should be after Unix epoch")
            .as_nanos();
        let base = std::env::temp_dir().join(format!("treeboot-manual-{name}-{id}"));
        let root = base.join("root");
        let worktree = base.join("worktree");

        std::fs::create_dir_all(&root).expect("root should be created");
        std::fs::create_dir_all(&worktree).expect("worktree should be created");

        (root, worktree)
    }

    fn context(root_path: &Path, worktree_path: &Path) -> Worktree {
        Worktree {
            root_path: root_path.to_path_buf(),
            worktree_path: worktree_path.to_path_buf(),
            default_branch: "main".to_owned(),
            environment: BTreeMap::from([(
                "TREEBOOT_ROOT_PATH".to_owned(),
                OsString::from(root_path),
            )]),
        }
    }

    fn options(operation: FileOperationKind, sources: &[&str]) -> ManualFileOperationOptions {
        ManualFileOperationOptions {
            operation,
            sources: sources.iter().map(PathBuf::from).collect(),
            target: None,
            required: false,
            symlinks: None,
            compare: None,
            delete: None,
        }
    }

    #[test]
    fn manual_operations_should_map_single_source_to_same_target() {
        let (root, worktree) = temp_workspace("single-default-target");
        let context = context(&root, &worktree);
        let options = options(FileOperationKind::Copy, &[".env"]);
        let operations = FileOperation::from_manual_options(&context, options)
            .expect("operation should normalize");

        assert_eq!(operations[0].source, PathBuf::from(".env"));
        assert_eq!(operations[0].target, PathBuf::from(".env"));
        assert_eq!(operations[0].source_path, root.join(".env"));
        assert_eq!(operations[0].target_path, worktree.join(".env"));
    }

    #[test]
    fn manual_operations_should_map_single_source_to_exact_target() {
        let (root, worktree) = temp_workspace("single-exact-target");
        let context = context(&root, &worktree);
        let mut options = options(FileOperationKind::Copy, &[".env"]);
        options.target = Some(PathBuf::from("local/.env"));

        let operations = FileOperation::from_manual_options(&context, options)
            .expect("operation should normalize");

        assert_eq!(operations[0].target, PathBuf::from("local/.env"));
        assert_eq!(operations[0].target_path, worktree.join("local/.env"));
    }

    #[test]
    fn manual_operations_should_map_multiple_sources_to_default_targets() {
        let (root, worktree) = temp_workspace("multi-default-target");
        let context = context(&root, &worktree);
        let options = options(FileOperationKind::Copy, &[".env", ".npmrc"]);
        let operations = FileOperation::from_manual_options(&context, options)
            .expect("operation should normalize");

        assert_eq!(operations[0].target_path, worktree.join(".env"));
        assert_eq!(operations[1].target_path, worktree.join(".npmrc"));
    }

    #[test]
    fn manual_operations_should_map_multiple_sources_under_target_prefix() {
        let (root, worktree) = temp_workspace("multi-target-prefix");
        let context = context(&root, &worktree);
        let mut options = options(FileOperationKind::Copy, &["a", "nested/c"]);
        options.target = Some(PathBuf::from("local"));

        let operations = FileOperation::from_manual_options(&context, options)
            .expect("operation should normalize");

        assert_eq!(operations[0].source_path, root.join("a"));
        assert_eq!(operations[0].target_path, worktree.join("local/a"));
        assert_eq!(operations[1].source_path, root.join("nested/c"));
        assert_eq!(operations[1].target_path, worktree.join("local/nested/c"));
    }

    #[test]
    fn manual_operations_should_map_multiple_absolute_sources_by_name() {
        let (root, worktree) = temp_workspace("multi-absolute-target-prefix");
        let context = context(&root, &worktree);
        let source = root.join("a");
        let mut options = ManualFileOperationOptions {
            operation: FileOperationKind::Copy,
            sources: vec![source.clone()],
            target: None,
            required: false,
            symlinks: None,
            compare: None,
            delete: None,
        };
        options.sources.push(root.join("b"));
        options.target = Some(PathBuf::from("local"));

        let operations = FileOperation::from_manual_options(&context, options)
            .expect("operation should normalize");

        assert_eq!(operations[0].source_path, source);
        assert_eq!(operations[0].target_path, worktree.join("local/a"));
        assert_eq!(operations[1].target_path, worktree.join("local/b"));
    }

    #[test]
    fn manual_target_should_reject_absolute_source_without_file_name() {
        let temp_dir = std::env::temp_dir();
        let root_source = temp_dir
            .ancestors()
            .last()
            .expect("temp dir should have a filesystem root");
        assert!(root_source.is_absolute());
        assert!(root_source.file_name().is_none());

        let error = manual_target(
            FileOperationKind::Copy,
            root_source,
            Some(Path::new("local")),
            true,
        )
        .expect_err("root path should not have a file name");

        assert!(error.to_string().contains("cannot derive target"));
    }

    #[test]
    fn validate_manual_options_should_reject_symlink_mode_for_symlink() {
        let mut options = options(FileOperationKind::Symlink, &["link"]);
        options.symlinks = Some(SymlinkMode::Preserve);

        let error = validate_manual_options(
            options.operation,
            &options.sources,
            options.symlinks,
            options.compare,
            options.delete,
        )
        .expect_err("symlinks should fail");

        assert!(error.to_string().contains("invalid symlink file operation"));
        assert!(error.to_string().contains("only valid for copy and sync"));
    }

    #[test]
    fn validate_manual_options_should_reject_compare_for_copy() {
        let mut options = options(FileOperationKind::Copy, &["file"]);
        options.compare = Some(SyncCompare::Checksum);

        let error = validate_manual_options(
            options.operation,
            &options.sources,
            options.symlinks,
            options.compare,
            options.delete,
        )
        .expect_err("compare should fail");

        assert!(
            error
                .to_string()
                .contains("`compare` is only valid for sync")
        );
    }

    #[test]
    fn validate_manual_options_should_reject_delete_for_copy() {
        let mut options = options(FileOperationKind::Copy, &["file"]);
        options.delete = Some(true);

        let error = validate_manual_options(
            options.operation,
            &options.sources,
            options.symlinks,
            options.compare,
            options.delete,
        )
        .expect_err("delete should fail");

        assert!(
            error
                .to_string()
                .contains("`delete` is only valid for sync")
        );
    }

    #[test]
    fn validate_manual_options_should_reject_compare_for_symlink() {
        let mut options = options(FileOperationKind::Symlink, &["file"]);
        options.compare = Some(SyncCompare::Metadata);

        let error = validate_manual_options(
            options.operation,
            &options.sources,
            options.symlinks,
            options.compare,
            options.delete,
        )
        .expect_err("compare should fail");

        assert!(
            error
                .to_string()
                .contains("`compare` is only valid for sync")
        );
    }

    #[test]
    fn validate_manual_options_should_reject_delete_for_symlink() {
        let mut options = options(FileOperationKind::Symlink, &["file"]);
        options.delete = Some(false);

        let error = validate_manual_options(
            options.operation,
            &options.sources,
            options.symlinks,
            options.compare,
            options.delete,
        )
        .expect_err("delete should fail");

        assert!(
            error
                .to_string()
                .contains("`delete` is only valid for sync")
        );
    }

    #[test]
    fn validate_manual_options_should_reject_empty_sources() {
        let options = options(FileOperationKind::Copy, &[]);
        let error = validate_manual_options(
            options.operation,
            &options.sources,
            options.symlinks,
            options.compare,
            options.delete,
        )
        .expect_err("empty sources should fail");

        assert!(
            error
                .to_string()
                .contains("at least one source is required")
        );
    }

    #[test]
    fn manual_operations_should_preserve_explicit_sync_options() {
        let (root, worktree) = temp_workspace("sync-options");
        let context = context(&root, &worktree);
        let mut options = options(FileOperationKind::Sync, &["shared"]);
        options.compare = Some(SyncCompare::Checksum);
        options.delete = Some(true);
        options.symlinks = Some(SymlinkMode::Preserve);

        let operations = FileOperation::from_manual_options(&context, options)
            .expect("operation should normalize");

        assert_eq!(operations[0].compare, Some(SyncCompare::Checksum));
        assert_eq!(operations[0].delete, Some(true));
        assert_eq!(operations[0].symlinks, Some(SymlinkMode::Preserve));
    }

    #[test]
    fn source_candidates_should_list_root_relative_files_and_dirs() {
        let (root, _worktree) = temp_workspace("source-candidates");
        std::fs::write(root.join(".env"), "TOKEN=1\n").expect("file should be written");
        std::fs::create_dir_all(root.join("shared/nested")).expect("dir should be created");

        assert_eq!(
            source_candidates(&root, Path::new("")),
            vec![
                ".env".to_owned(),
                format!("shared{}", std::path::MAIN_SEPARATOR)
            ]
        );
        assert_eq!(
            source_candidates(&root, Path::new("shared/")),
            vec![format!("shared/nested{}", std::path::MAIN_SEPARATOR)]
        );
    }

    #[test]
    fn source_candidates_should_fail_quietly_for_missing_prefix() {
        let (root, _worktree) = temp_workspace("source-candidates-missing");

        assert!(source_candidates(&root, Path::new("missing/")).is_empty());
    }

    #[test]
    fn source_candidates_should_fail_quietly_for_absolute_current_value() {
        let (root, _worktree) = temp_workspace("source-candidates-absolute");

        assert!(source_candidates(&root, Path::new("/tmp")).is_empty());
    }

    #[test]
    fn source_candidates_should_not_escape_root_with_parent_segments() {
        let (root, _worktree) = temp_workspace("source-candidates-parent");
        std::fs::write(root.join("inside"), "ok\n").expect("file should be written");

        assert!(source_candidates(&root, Path::new("../")).is_empty());
        assert!(source_candidates(&root, Path::new("nested/../../")).is_empty());
    }

    #[test]
    fn file_operation_source_candidates_should_fail_quietly_outside_git() {
        let (root, _worktree) = temp_workspace("completion-outside-git");

        assert!(
            file_operation_source_candidates(FileOperationCompletionOptions {
                cwd: Some(root),
                root: None,
                current: PathBuf::new(),
            })
            .is_empty()
        );
    }

    #[test]
    fn manual_validation_error_should_not_look_like_config_error() {
        let (root, worktree) = temp_workspace("manual-error-origin");
        let error = ActionPlan::from_file_operations(
            &context(&root, &worktree),
            PlanOrigin::Manual {
                operation: FileOperationKind::Copy,
            },
            &[FileOperation {
                operation: FileOperationKind::Copy,
                source: PathBuf::from("../outside"),
                target: PathBuf::from("outside"),
                source_path: root.join("../outside"),
                target_path: worktree.join("outside"),
                required: false,
                compare: None,
                delete: None,
                symlinks: Some(SymlinkMode::Preserve),
                declaration: manual_span(),
            }],
            ActionPlanOptions::default(),
        )
        .expect_err("outside source should fail");

        assert!(error.to_string().contains("invalid copy file operation"));
        assert!(!error.to_string().contains("invalid config"));
        assert!(!error.to_string().contains("line"));
        assert!(!error.to_string().contains(".treeboot.toml"));
    }

    #[test]
    fn strict_manual_sync_should_fail_before_side_effects() {
        let (root, worktree) = temp_workspace("strict-sync");
        std::fs::create_dir_all(root.join("shared")).expect("source should be created");
        let error = ActionPlan::from_file_operations(
            &context(&root, &worktree),
            PlanOrigin::Manual {
                operation: FileOperationKind::Sync,
            },
            &[FileOperation {
                operation: FileOperationKind::Sync,
                source: PathBuf::from("shared"),
                target: PathBuf::from("shared"),
                source_path: root.join("shared"),
                target_path: worktree.join("shared"),
                required: false,
                compare: Some(SyncCompare::Metadata),
                delete: Some(false),
                symlinks: Some(SymlinkMode::Preserve),
                declaration: manual_span(),
            }],
            ActionPlanOptions {
                strict: true,
                ..ActionPlanOptions::default()
            },
        )
        .expect_err("strict sync should fail");

        assert!(error.to_string().contains("cannot be used with sync"));
        assert!(!worktree.join("shared").exists());
    }
}