ctb_io_csc/
move_engine.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Move engine providing atomic zero-copy rename on the same filesystem and
21//! verified checksummed copy fallback across filesystem boundaries.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::args::{CscArgs, MvArgs, SourceChangePolicy};
31use crate::copy_engine::{
32    compute_journal_relative_path, execute_copy_pipeline,
33};
34use crate::journal::{
35    MoveSourceDisposition, MoveSourceRecord, StateJournal,
36    read_journal_snapshot, resolve_journal_path,
37};
38use crate::path_resolution::{ResolvedCopyTask, resolve_tasks};
39use ctb_io::file::{
40    FileEntity, FileEntityKind, FileOrigin, TraversalOptions,
41    is_cross_device_error, traverse_dir, verify_materialized_entity,
42};
43use ctb_utilities::cli::ToolResult;
44use std::fmt::Write as _;
45use std::path::{Path, PathBuf};
46use std::time::Instant;
47
48fn rename_with_policy(
49    source: &Path,
50    destination: &Path,
51    policy: ctb_io::file::ExistingEntryPolicy,
52) -> Result<()> {
53    let source_parent =
54        match source.parent().filter(|path| !path.as_os_str().is_empty()) {
55            Some(parent) => parent,
56            None => Path::new("."),
57        };
58    let destination_parent = match destination
59        .parent()
60        .filter(|path| !path.as_os_str().is_empty())
61    {
62        Some(parent) => parent,
63        None => Path::new("."),
64    };
65    let source_name =
66        source.file_name().context("Missing source entry name")?;
67    let destination_name = destination
68        .file_name()
69        .context("Missing destination entry name")?;
70    let source_dir = ctb_io::file::SandboxableDir::open(source_parent)?;
71    let destination_dir =
72        ctb_io::file::SandboxableDir::open(destination_parent)?;
73    destination_dir.rename_from_parent(
74        &source_dir.root_fd(),
75        source_name,
76        &destination_dir.root_fd(),
77        destination_name,
78        policy,
79    )
80}
81
82fn normalize_move_source_path(path: &Path) -> PathBuf {
83    let mut normalized = PathBuf::new();
84    for component in path.components() {
85        normalized.push(component.as_os_str());
86    }
87    if normalized.as_os_str().is_empty() {
88        path.to_path_buf()
89    } else {
90        normalized
91    }
92}
93
94fn is_within_task_source(candidate: &Path, task_source_root: &Path) -> bool {
95    let norm_candidate = normalize_move_source_path(candidate);
96    let norm_root = normalize_move_source_path(task_source_root);
97    norm_candidate == norm_root || norm_candidate.starts_with(&norm_root)
98}
99
100fn open_or_create_move_journal(
101    args: &MvArgs,
102    temp_state_dir: &mut Option<tempfile::TempDir>,
103    sources: &[PathBuf],
104    dest_path: &Path,
105    initial_task_records: &[MoveSourceRecord],
106) -> Result<StateJournal> {
107    let mut journal = if let Some(ref custom_jp) = args.journal_path {
108        let journal_path = if custom_jp.extension().and_then(|e| e.to_str())
109            == Some("cscdesc")
110        {
111            custom_jp.with_extension("cscjournal")
112        } else if custom_jp.extension().and_then(|e| e.to_str())
113            == Some("cscjournal")
114        {
115            custom_jp.clone()
116        } else {
117            custom_jp.with_extension("cscjournal")
118        };
119        let desc_path = journal_path.with_extension("cscdesc");
120        anyhow::ensure!(
121            !journal_path.exists() && !desc_path.exists(),
122            "Journal file already exists at {}: will not overwrite existing file (pass --resume to resume an interrupted move)",
123            journal_path.display()
124        );
125        StateJournal::create_at_path(
126            &journal_path,
127            &desc_path,
128            sources,
129            dest_path,
130        )?
131    } else if let Some(ref custom_dir) = args.state_dir {
132        StateJournal::create_new(custom_dir, sources, dest_path)?
133    } else {
134        let mut dir = tempfile::tempdir().context(
135            "Failed to create temporary directory for move state journal",
136        )?;
137        let jw = StateJournal::create_new(dir.path(), sources, dest_path)?;
138        dir.disable_cleanup(true);
139        *temp_state_dir = Some(dir);
140        jw
141    };
142    journal.set_defer_completion(true);
143    if !initial_task_records.is_empty() {
144        journal.record_move_sources_durable(
145            initial_task_records.iter().cloned(),
146        )?;
147    }
148    Ok(journal)
149}
150
151fn discover_task_source_inventory(
152    task: &ResolvedCopyTask,
153    csc_args: &CscArgs,
154    journal: &mut StateJournal,
155) -> Result<()> {
156    let norm_root = normalize_move_source_path(&task.source_root);
157    let src_meta =
158        std::fs::symlink_metadata(&task.source_root).with_context(|| {
159            format!(
160                "Source path does not exist before cross-device move: {}",
161                task.source_root.display()
162            )
163        })?;
164    let mut discovered = Vec::new();
165    if src_meta.is_dir() {
166        let traversal_options = TraversalOptions::new()
167            .yield_root(true)
168            .one_file_system(csc_args.one_file_system)
169            .apple_read_options(csc_args.resolve_apple_read_options());
170        for entry in traverse_dir(&task.source_root, traversal_options)? {
171            let entry = entry?;
172            anyhow::ensure!(
173                entry.errors.is_empty(),
174                "Source traversal errors: {}",
175                entry.errors.join("; ")
176            );
177            let is_root = entry.relative_path.as_os_str().is_empty();
178            let norm_src = if is_root {
179                norm_root.clone()
180            } else {
181                normalize_move_source_path(&entry.path)
182            };
183            let dest_path = if is_root {
184                task.target_root.clone()
185            } else {
186                task.target_root.join(&entry.relative_path)
187            };
188            let source_identity =
189                ctb_io::file::identity::query_file_identity(&norm_src).ok();
190            let committed_relative_path = compute_journal_relative_path(
191                journal.destination(),
192                &dest_path,
193            )
194            .ok();
195            if let Some(existing) = journal.move_sources().get(&norm_src) {
196                if let (Some(expected_id), Some(actual_id)) =
197                    (&existing.source_identity, &source_identity)
198                {
199                    anyhow::ensure!(
200                        expected_id == actual_id,
201                        "Source entry was replaced before move completed: {}",
202                        norm_src.display()
203                    );
204                }
205                let mut updated = existing.clone();
206                if is_root {
207                    updated.is_task_root = true;
208                    updated.contents_only_root = task.copy_contents_only;
209                }
210                if updated.source_identity.is_none() {
211                    updated.source_identity = source_identity;
212                }
213                if updated.committed_relative_path.is_none() {
214                    updated.committed_relative_path = committed_relative_path;
215                }
216                discovered.push(updated);
217            } else {
218                discovered.push(MoveSourceRecord {
219                    source_path: norm_src,
220                    destination_path: dest_path,
221                    committed_relative_path,
222                    source_identity,
223                    is_dir: entry.is_dir,
224                    is_task_root: is_root,
225                    contents_only_root: is_root && task.copy_contents_only,
226                    disposition: MoveSourceDisposition::Pending,
227                });
228            }
229        }
230    } else {
231        let source_identity =
232            ctb_io::file::identity::query_file_identity(&norm_root).ok();
233        let committed_relative_path = compute_journal_relative_path(
234            journal.destination(),
235            &task.target_root,
236        )
237        .ok();
238        if let Some(existing) = journal.move_sources().get(&norm_root) {
239            if let (Some(expected_id), Some(actual_id)) =
240                (&existing.source_identity, &source_identity)
241            {
242                anyhow::ensure!(
243                    expected_id == actual_id,
244                    "Source entry was replaced before move completed: {}",
245                    norm_root.display()
246                );
247            }
248            let mut updated = existing.clone();
249            updated.is_task_root = true;
250            if updated.source_identity.is_none() {
251                updated.source_identity = source_identity;
252            }
253            if updated.committed_relative_path.is_none() {
254                updated.committed_relative_path = committed_relative_path;
255            }
256            discovered.push(updated);
257        } else {
258            discovered.push(MoveSourceRecord {
259                source_path: norm_root,
260                destination_path: task.target_root.clone(),
261                committed_relative_path,
262                source_identity,
263                is_dir: false,
264                is_task_root: true,
265                contents_only_root: false,
266                disposition: MoveSourceDisposition::Pending,
267            });
268        }
269    }
270    journal.record_move_sources_durable(discovered)
271}
272
273/// Executes the `mv` command.
274///
275/// Attempts an atomic O(1) filesystem rename. When encountering `EXDEV`
276/// (cross-filesystem link), falls back to executing the verified checksummed
277/// copy pipeline (`csc --delete-manifest-after`) and unlinks source entities
278/// only after verification completes successfully.
279pub fn run_mv(args: MvArgs) -> Result<ToolResult> {
280    let _env_scope = if args.full_provenance {
281        ctb_io_environment::GlobalEnvironmentScope::enter_full()
282    } else {
283        ctb_io_environment::GlobalEnvironmentScope::enter_fresh()
284    };
285    let start_time = Instant::now();
286    let progress = Progress::new(args.should_show_progress());
287    let strict_lossless = !args.best_effort_metadata && !args.allow_unknown_fs;
288
289    let mut temp_state_dir: Option<tempfile::TempDir> = None;
290    let (tasks, sources, dest_path, mut initial_task_records, mut journal) =
291        if let Some(ref resume_arg) = args.resume {
292            let journal_path = resolve_journal_path(resume_arg)?;
293            let desc_path = journal_path.with_extension("cscdesc");
294            let snap = read_journal_snapshot(&journal_path)?;
295            let mut root_records: Vec<MoveSourceRecord> = snap
296                .move_sources
297                .values()
298                .filter(|r| r.is_task_root)
299                .cloned()
300                .collect();
301            root_records.sort_by(|a, b| a.source_path.cmp(&b.source_path));
302            let resolved_tasks = if root_records.is_empty() {
303                let mut all_paths = snap.sources.clone();
304                all_paths.push(snap.destination.clone());
305                resolve_tasks(&all_paths)?.0
306            } else {
307                root_records
308                    .iter()
309                    .map(|r| ResolvedCopyTask {
310                        source_root: r.source_path.clone(),
311                        target_root: r.destination_path.clone(),
312                        copy_contents_only: r.contents_only_root,
313                    })
314                    .collect::<Vec<_>>()
315            };
316            let mut jw = StateJournal::open_for_resume(
317                &journal_path,
318                &desc_path,
319                &snap,
320            )?;
321            jw.set_defer_completion(true);
322            (
323                resolved_tasks,
324                snap.sources.clone(),
325                snap.destination.clone(),
326                root_records,
327                Some(jw),
328            )
329        } else {
330            anyhow::ensure!(
331                args.paths.len() >= 2,
332                "Must provide at least one source and one destination path"
333            );
334            let (resolved_tasks, resolved_dest) = resolve_tasks(&args.paths)?;
335            if !args.best_effort_metadata && !args.allow_unknown_fs {
336                for task in &resolved_tasks {
337                    if let Ok(src_meta) =
338                        std::fs::symlink_metadata(&task.source_root)
339                    {
340                        let src_fs = ctb_io::file::query_filesystem_info(
341                            &task.source_root,
342                            &src_meta,
343                        );
344                        if src_fs.fs_type == "unknown" {
345                            anyhow::bail!(
346                                "Cannot detect filesystem type for source '{}'. Pass --best-effort-metadata or --allow-unknown-fs to proceed.",
347                                task.source_root.display()
348                            );
349                        }
350                    }
351                    let tgt_existing = if task.target_root.exists() {
352                        task.target_root.clone()
353                    } else {
354                        match ctb_io::file::resolve_existing_ancestors(
355                            &task.target_root,
356                        ) {
357                            Ok(ancestor) => ancestor,
358                            Err(_) => PathBuf::from("."),
359                        }
360                    };
361                    if let Ok(tgt_meta) =
362                        std::fs::symlink_metadata(&tgt_existing)
363                    {
364                        let tgt_fs = ctb_io::file::query_filesystem_info(
365                            &tgt_existing,
366                            &tgt_meta,
367                        );
368                        if tgt_fs.fs_type == "unknown" {
369                            anyhow::bail!(
370                                "Cannot detect filesystem type for destination '{}'. Pass --best-effort-metadata or --allow-unknown-fs to proceed.",
371                                task.target_root.display()
372                            );
373                        }
374                    }
375                }
376            }
377            let task_sources: Vec<PathBuf> = resolved_tasks
378                .iter()
379                .map(|t| t.source_root.clone())
380                .collect();
381            let mut root_records = Vec::with_capacity(resolved_tasks.len());
382            for task in &resolved_tasks {
383                let norm_src = normalize_move_source_path(&task.source_root);
384                let meta = std::fs::symlink_metadata(&task.source_root)?;
385                let source_identity =
386                    ctb_io::file::identity::query_file_identity(&norm_src).ok();
387                let committed_rel = compute_journal_relative_path(
388                    &resolved_dest,
389                    &task.target_root,
390                )
391                .ok();
392                root_records.push(MoveSourceRecord {
393                    source_path: norm_src,
394                    destination_path: task.target_root.clone(),
395                    committed_relative_path: committed_rel,
396                    source_identity,
397                    is_dir: meta.is_dir(),
398                    is_task_root: true,
399                    contents_only_root: task.copy_contents_only,
400                    disposition: MoveSourceDisposition::Pending,
401                });
402            }
403            let jw = if !args.dry_run
404                && (args.journal_path.is_some() || args.state_dir.is_some())
405            {
406                Some(open_or_create_move_journal(
407                    &args,
408                    &mut temp_state_dir,
409                    &task_sources,
410                    &resolved_dest,
411                    &root_records,
412                )?)
413            } else {
414                None
415            };
416            (
417                resolved_tasks,
418                task_sources,
419                resolved_dest,
420                root_records,
421                jw,
422            )
423        };
424
425    let mut moved_renamed: u64 = 0;
426    let mut moved_copied: u64 = 0;
427    let mut bytes_copied: u64 = 0;
428    let mut retained_journals = Vec::new();
429    let mut warning_count = 0_usize;
430
431    for task in &tasks {
432        if args.dry_run {
433            progress.message(&format!(
434                "[Dry run] Move {} -> {}",
435                task.source_root.display(),
436                task.target_root.display()
437            ));
438            moved_renamed = moved_renamed.saturating_add(1);
439            continue;
440        }
441
442        let norm_task_src = normalize_move_source_path(&task.source_root);
443        // Reason for fallback: move execution without an active state journal has no recorded source move records
444        let existing_task_records: Vec<MoveSourceRecord> = journal
445            .as_ref()
446            .map(|jw| {
447                jw.move_sources()
448                    .values()
449                    .filter(|r| {
450                        is_within_task_source(&r.source_path, &norm_task_src)
451                    })
452                    .cloned()
453                    .collect()
454            })
455            .unwrap_or_default();
456
457        if existing_task_records.iter().any(|r| {
458            r.is_task_root && r.disposition == MoveSourceDisposition::Renamed
459        }) {
460            let root_rec = existing_task_records
461                .iter()
462                .find(|r| r.is_task_root)
463                .context("Missing renamed task root record")?;
464            std::fs::symlink_metadata(&root_rec.destination_path).with_context(|| {
465                format!(
466                    "Resumed move failed: previously renamed destination missing: {}",
467                    root_rec.destination_path.display()
468                )
469            })?;
470            if let Some(ref expected_id) = root_rec.source_identity {
471                if let Ok(actual_id) =
472                    ctb_io::file::identity::query_file_identity(
473                        &root_rec.destination_path,
474                    )
475                {
476                    anyhow::ensure!(
477                        actual_id == *expected_id,
478                        "Resumed move failed: previously renamed destination identity changed: {}",
479                        root_rec.destination_path.display()
480                    );
481                }
482            }
483            moved_renamed = moved_renamed.saturating_add(1);
484            continue;
485        }
486
487        let task_in_deletion_or_done = !existing_task_records.is_empty()
488            && existing_task_records.iter().all(|r| {
489                matches!(
490                    r.disposition,
491                    MoveSourceDisposition::CopiedVerified
492                        | MoveSourceDisposition::Deleted
493                        | MoveSourceDisposition::RetainedRoot
494                )
495            });
496
497        if task_in_deletion_or_done {
498            let jw = journal.as_mut().context(
499                "Journal must be open when resuming move source deletion",
500            )?;
501            let j_path = jw.journal_path().to_path_buf();
502            if let Err(error) = execute_journaled_source_deletion(
503                jw,
504                &norm_task_src,
505                strict_lossless,
506            ) {
507                if let Err(record_error) = jw.mark_failed(&format!("{error:#}"))
508                {
509                    return Err(error).context(format!(
510                        "Move journal retained at {}; recording failure also failed: {record_error:#}",
511                        j_path.display()
512                    ));
513                }
514                return Err(error).context(format!(
515                    "Move journal retained at {}",
516                    j_path.display()
517                ));
518            }
519            for rec in &existing_task_records {
520                if let Some(entity) = jw.committed_entity_for_move_source(rec) {
521                    if let FileEntityKind::Regular { size, .. } = entity.kind {
522                        moved_copied = moved_copied.saturating_add(1);
523                        bytes_copied = bytes_copied.saturating_add(size);
524                    }
525                }
526            }
527            continue;
528        }
529
530        let has_in_progress_copy = existing_task_records.len() > 1
531            || journal.as_ref().is_some_and(|jw| {
532                !jw.committed_entities().is_empty()
533                    && existing_task_records.iter().any(|r| {
534                        r.committed_relative_path.as_ref().is_some_and(|rel| {
535                            jw.committed_entities().contains_key(
536                                rel.as_os_str().as_encoded_bytes(),
537                            )
538                        })
539                    })
540            });
541
542        // Fast path: atomic rename on the same filesystem (unless cross-device copy already started)
543        let rename_res = if !task.copy_contents_only && !has_in_progress_copy {
544            if let Some(parent) = task.target_root.parent() {
545                if !parent.as_os_str().is_empty() && !parent.exists() {
546                    std::fs::create_dir_all(parent).with_context(|| {
547                        format!(
548                            "Failed to create destination directory: {}",
549                            parent.display()
550                        )
551                    })?;
552                }
553            }
554            rename_with_policy(
555                &task.source_root,
556                &task.target_root,
557                if args.force {
558                    ctb_io::file::ExistingEntryPolicy::Replace
559                } else {
560                    ctb_io::file::ExistingEntryPolicy::Refuse
561                },
562            )
563        } else {
564            Err(std::io::Error::from(std::io::ErrorKind::CrossesDevices).into())
565        };
566
567        match rename_res {
568            Ok(()) => {
569                moved_renamed = moved_renamed.saturating_add(1);
570                if let Some(rec) = initial_task_records
571                    .iter_mut()
572                    .find(|r| r.source_path == norm_task_src)
573                {
574                    rec.disposition = MoveSourceDisposition::Renamed;
575                }
576                if let Some(ref mut jw) = journal {
577                    jw.update_move_source_disposition_durable(
578                        &norm_task_src,
579                        MoveSourceDisposition::Renamed,
580                    )?;
581                }
582                if args.verbose {
583                    progress.message(&format!(
584                        "Renamed {} -> {}",
585                        task.source_root.display(),
586                        task.target_root.display()
587                    ));
588                }
589            }
590            Err(err)
591                if err
592                    .downcast_ref::<std::io::Error>()
593                    .is_some_and(is_cross_device_error) =>
594            {
595                progress.message(&format!(
596                    "Cross-device move detected for {}: copying with verification...",
597                    task.source_root.display()
598                ));
599
600                let csc_args = CscArgs {
601                    paths: vec![
602                        task.source_root.clone(),
603                        task.target_root.clone(),
604                    ],
605                    state_dir: None,
606                    resume: None,
607                    journal_path: None,
608                    verbose: args.verbose,
609                    progress: args.progress,
610                    no_progress: args.no_progress,
611                    verify_after: true,
612                    no_verify_after: false,
613                    overwrite: args.force,
614                    on_source_change: SourceChangePolicy::Error,
615                    copy_specials_as_specials: true,
616                    copy_block_devices_as_regular_files: false,
617                    copy_fifos_as_regular_files: false,
618                    one_file_system: false,
619                    best_effort_metadata: args.best_effort_metadata,
620                    allow_unknown_fs: args.allow_unknown_fs,
621                    check_atime: false,
622                    check_ctime: false,
623                    check_birthtime: false,
624                    strict: false,
625                    delete_manifest_after: true,
626                    recursive: true,
627                    archive: true,
628                    dry_run: false,
629                    read_apple_double: None,
630                    read_apple_double_alongside: false,
631                    no_read_apple_double_alongside: false,
632                    read_apple_double_zip: false,
633                    read_apple_double_netatalk: false,
634                    read_apple_single: false,
635                    read_apple_single_without_extension: false,
636                    no_read_apple_single: false,
637                    read_apple_single_with_extension: Vec::new(),
638                    maybe_write_apple_double: None,
639                    force_write_apple_double: None,
640                    maybe_write_apple_single: false,
641                    force_write_apple_single: false,
642                    write_apple_single_with_extension: None,
643                    write_apple_single_without_extension: false,
644                    read_windows_ads: false,
645                    no_read_windows_ads: false,
646                    maybe_write_windows_ads: false,
647                    force_write_windows_ads: false,
648                    full_provenance: args.full_provenance,
649                    continue_on_error: false,
650                    allow_journal_errors: false,
651                };
652
653                if journal.is_none() {
654                    journal = Some(open_or_create_move_journal(
655                        &args,
656                        &mut temp_state_dir,
657                        &sources,
658                        &dest_path,
659                        &initial_task_records,
660                    )?);
661                }
662                let jw = journal
663                    .as_mut()
664                    .context("Move journal must be initialized")?;
665                let j_path = jw.journal_path().to_path_buf();
666
667                let copy_result = (|| {
668                    discover_task_source_inventory(task, &csc_args, jw)?;
669                    let copy_stats = execute_copy_pipeline(
670                        std::slice::from_ref(task),
671                        &csc_args,
672                        jw,
673                        &progress,
674                    )?;
675
676                    anyhow::ensure!(
677                        copy_stats.special_files_skipped == 0,
678                        "Move refused: some source entries could not be copied; all sources retained"
679                    );
680                    anyhow::ensure!(
681                        copy_stats.files_failed == 0 && jw.errors().is_empty(),
682                        "Move refused: copy recorded failures; all sources retained"
683                    );
684                    remove_copied_sources_with_journal(
685                        &copy_stats.copied_entities,
686                        &task.source_root,
687                        task.copy_contents_only,
688                        strict_lossless,
689                        jw,
690                    )?;
691                    Ok(copy_stats)
692                })();
693                let copy_stats = match copy_result {
694                    Ok(stats) => stats,
695                    Err(error) => {
696                        if let Err(record_error) =
697                            jw.mark_failed(&format!("{error:#}"))
698                        {
699                            return Err(error).context(format!(
700                                "Move journal retained at {}; recording failure also failed: {record_error:#}",
701                                j_path.display()
702                            ));
703                        }
704                        return Err(error).context(format!(
705                            "Move journal retained at {}",
706                            j_path.display()
707                        ));
708                    }
709                };
710
711                moved_copied = moved_copied
712                    .saturating_add(copy_stats.files_copied)
713                    .saturating_add(copy_stats.files_skipped_identical);
714                bytes_copied =
715                    bytes_copied.saturating_add(copy_stats.bytes_copied);
716            }
717            Err(err) => {
718                if journal.is_none() && moved_renamed > 0 {
719                    if let Ok(mut jw) = open_or_create_move_journal(
720                        &args,
721                        &mut temp_state_dir,
722                        &sources,
723                        &dest_path,
724                        &initial_task_records,
725                    ) {
726                        let _ = jw.mark_failed(&format!("{err:#}"));
727                        journal = Some(jw);
728                    }
729                } else if let Some(ref mut jw) = journal {
730                    let _ = jw.mark_failed(&format!("{err:#}"));
731                }
732                return Err(err).with_context(|| {
733                    format!(
734                        "Failed to move '{}' to '{}'",
735                        task.source_root.display(),
736                        task.target_root.display()
737                    )
738                });
739            }
740        }
741    }
742
743    if let Some(mut jw) = journal {
744        jw.mark_completed()?;
745        let j_path = jw.journal_path().to_path_buf();
746        warning_count = warning_count.saturating_add(jw.warnings().len());
747        for warning in jw.warnings() {
748            progress
749                .message(&format!("[{}] {}", warning.code, warning.message));
750        }
751        let retain_metadata = !jw.warnings().is_empty()
752            || jw
753                .committed_entities()
754                .values()
755                .any(crate::journal::entity_requires_metadata_retention);
756        let explicit_journal_location = args.journal_path.is_some()
757            || args.state_dir.is_some()
758            || args.resume.is_some();
759        drop(jw);
760        if retain_metadata {
761            progress.message(&format!(
762                "Original metadata retained in {}",
763                j_path.display()
764            ));
765            retained_journals.push(j_path);
766        } else if !explicit_journal_location {
767            if let Some(dir) = temp_state_dir.take() {
768                dir.close().with_context(|| {
769                    format!(
770                        "Failed to remove completed move journal {}",
771                        j_path.display()
772                    )
773                })?;
774            }
775        }
776    }
777
778    let elapsed = start_time.elapsed().as_secs_f64();
779    let mut summary = String::new();
780    writeln!(summary, "--- MV Summary ---")?;
781    writeln!(summary, "Items renamed (same filesystem): {moved_renamed}")?;
782    if moved_copied > 0 {
783        writeln!(summary, "Files copied (cross-device):     {moved_copied}")?;
784        writeln!(summary, "Bytes transferred:               {bytes_copied}")?;
785    }
786    writeln!(summary, "Duration:                        {elapsed:.2}s")?;
787    for journal in retained_journals {
788        writeln!(
789            summary,
790            "Original metadata journal:       {}",
791            journal.display()
792        )?;
793    }
794    if warning_count > 0 {
795        writeln!(
796            summary,
797            "Status:                          Move completed with {warning_count} warning record(s); fidelity limitations are retained in the journal."
798        )?;
799    } else {
800        writeln!(
801            summary,
802            "Status:                          Move completed successfully."
803        )?;
804    }
805
806    Ok(ToolResult::immediate_ok(summary.into_bytes()))
807}
808
809pub(crate) fn remove_copied_sources(
810    entries: &[(PathBuf, PathBuf, FileEntity)],
811    source_root: &Path,
812    contents_only: bool,
813    strict_lossless: bool,
814) -> Result<()> {
815    let temp_dir = tempfile::tempdir().context(
816        "Failed to create temporary directory for move source deletion journal",
817    )?;
818    // Reason for fallback: when entries slice is empty, destination root for temporary move journal defaults to current directory
819    let dest_root = entries
820        .iter()
821        .find(|(src, _, _)| {
822            normalize_move_source_path(src)
823                == normalize_move_source_path(source_root)
824        })
825        .map(|(_, dst, _)| dst.clone())
826        .or_else(|| entries.first().map(|(_, dst, _)| dst.clone()))
827        .unwrap_or_else(|| PathBuf::from("."));
828    let mut journal = StateJournal::create_new(
829        temp_dir.path(),
830        &[source_root.to_path_buf()],
831        &dest_root,
832    )?;
833    journal.set_defer_completion(true);
834    remove_copied_sources_with_journal(
835        entries,
836        source_root,
837        contents_only,
838        strict_lossless,
839        &mut journal,
840    )
841}
842
843pub(crate) fn remove_copied_sources_with_journal(
844    entries: &[(PathBuf, PathBuf, FileEntity)],
845    source_root: &Path,
846    contents_only: bool,
847    strict_lossless: bool,
848    journal: &mut StateJournal,
849) -> Result<()> {
850    record_verified_copied_sources_in_journal(
851        entries,
852        source_root,
853        contents_only,
854        journal,
855    )?;
856    execute_journaled_source_deletion(journal, source_root, strict_lossless)
857}
858
859fn record_verified_copied_sources_in_journal(
860    entries: &[(PathBuf, PathBuf, FileEntity)],
861    source_root: &Path,
862    contents_only: bool,
863    journal: &mut StateJournal,
864) -> Result<()> {
865    let norm_root = normalize_move_source_path(source_root);
866    let mut records = Vec::with_capacity(entries.len());
867    for (source, destination, entity) in entries {
868        let norm_src = normalize_move_source_path(source);
869        let rel =
870            compute_journal_relative_path(journal.destination(), destination)?;
871        if !journal
872            .committed_entities()
873            .contains_key(rel.as_os_str().as_encoded_bytes())
874        {
875            let mut journal_entity = entity.clone();
876            journal_entity.identity.relative_path = Some(rel.clone());
877            journal.record_entity(&journal_entity);
878        }
879        let source_identity = match &entity.identity.origin {
880            FileOrigin::Filesystem { key, .. } => Some(key.clone()),
881            _ => None,
882        };
883        let is_root = norm_src == norm_root;
884        let existing_is_task_root = journal
885            .move_sources()
886            .get(&norm_src)
887            .is_some_and(|r| r.is_task_root);
888        records.push(MoveSourceRecord {
889            source_path: norm_src,
890            destination_path: destination.clone(),
891            committed_relative_path: Some(rel),
892            source_identity,
893            is_dir: entity.is_dir(),
894            is_task_root: is_root || existing_is_task_root,
895            contents_only_root: is_root && contents_only,
896            disposition: MoveSourceDisposition::CopiedVerified,
897        });
898    }
899    journal.commit_batch()?;
900    journal.record_move_sources_durable(records)?;
901
902    for record in journal.move_sources().values() {
903        if is_within_task_source(&record.source_path, &norm_root) {
904            anyhow::ensure!(
905                record.disposition != MoveSourceDisposition::Pending,
906                "Move refused: source inventory entry was not copied and verified: {}",
907                record.source_path.display()
908            );
909        }
910    }
911    Ok(())
912}
913
914fn has_deleted_descendant(
915    dir_path: &Path,
916    records: &[MoveSourceRecord],
917) -> bool {
918    records.iter().any(|r| {
919        r.source_path != dir_path
920            && r.source_path.starts_with(dir_path)
921            && r.disposition == MoveSourceDisposition::Deleted
922    })
923}
924
925pub(crate) fn execute_journaled_source_deletion(
926    journal: &mut StateJournal,
927    source_root: &Path,
928    strict_lossless: bool,
929) -> Result<()> {
930    let norm_root = normalize_move_source_path(source_root);
931    let mut task_records: Vec<MoveSourceRecord> = journal
932        .move_sources()
933        .values()
934        .filter(|r| is_within_task_source(&r.source_path, &norm_root))
935        .cloned()
936        .collect();
937    anyhow::ensure!(
938        !task_records.is_empty(),
939        "No durable move source inventory records found for {}",
940        source_root.display()
941    );
942
943    for record in &task_records {
944        anyhow::ensure!(
945            record.disposition != MoveSourceDisposition::Pending,
946            "Move refused: source entry was not copied and verified: {}",
947            record.source_path.display()
948        );
949        if record.disposition == MoveSourceDisposition::Renamed {
950            std::fs::symlink_metadata(&record.destination_path).with_context(
951                || {
952                    format!(
953                        "Renamed destination missing: {}",
954                        record.destination_path.display()
955                    )
956                },
957            )?;
958            continue;
959        }
960        let committed_entity = journal
961            .committed_entity_for_move_source(record)
962            .with_context(|| {
963                format!(
964                    "Missing committed journal entity for move source {}",
965                    record.source_path.display()
966                )
967            })?
968            .clone();
969        verify_materialized_entity(
970            &record.destination_path,
971            &committed_entity,
972            strict_lossless,
973        )?;
974        match record.disposition {
975            MoveSourceDisposition::CopiedVerified => {
976                verify_source_identity(&record.source_path, &committed_entity)?;
977                if !record.is_dir
978                    || !has_deleted_descendant(
979                        &record.source_path,
980                        &task_records,
981                    )
982                {
983                    verify_materialized_entity(
984                        &record.source_path,
985                        &committed_entity,
986                        strict_lossless,
987                    )?;
988                }
989            }
990            MoveSourceDisposition::Deleted => {
991                match std::fs::symlink_metadata(&record.source_path) {
992                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
993                    Ok(_) => {
994                        verify_source_identity(&record.source_path, &committed_entity).with_context(
995                        || {
996                            format!(
997                                "Source path was recreated with a different identity after deletion: {}",
998                                record.source_path.display()
999                            )
1000                        },
1001                    )?;
1002                    }
1003                    Err(err) => return Err(err.into()),
1004                }
1005            }
1006            MoveSourceDisposition::RetainedRoot => {
1007                verify_source_identity(&record.source_path, &committed_entity)?;
1008            }
1009            MoveSourceDisposition::Pending | MoveSourceDisposition::Renamed => {
1010            }
1011        }
1012    }
1013
1014    task_records.sort_by(|a, b| {
1015        std::cmp::Reverse(a.source_path.components().count())
1016            .cmp(&std::cmp::Reverse(b.source_path.components().count()))
1017            .then_with(|| a.source_path.cmp(&b.source_path))
1018    });
1019
1020    for record in task_records {
1021        if matches!(
1022            record.disposition,
1023            MoveSourceDisposition::Renamed
1024                | MoveSourceDisposition::RetainedRoot
1025        ) {
1026            continue;
1027        }
1028        if record.disposition == MoveSourceDisposition::Deleted
1029            && std::fs::symlink_metadata(&record.source_path)
1030                .is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)
1031        {
1032            continue;
1033        }
1034        let committed_entity = journal
1035            .committed_entity_for_move_source(&record)
1036            .with_context(|| {
1037                format!(
1038                    "Missing committed journal entity for move source {}",
1039                    record.source_path.display()
1040                )
1041            })?
1042            .clone();
1043        verify_source_identity(&record.source_path, &committed_entity)?;
1044        if record.is_dir {
1045            if record.contents_only_root {
1046                journal.update_move_source_disposition_durable(
1047                    &record.source_path,
1048                    MoveSourceDisposition::RetainedRoot,
1049                )?;
1050            } else {
1051                std::fs::remove_dir(&record.source_path).with_context(|| {
1052                    format!(
1053                        "Source directory changed or could not be removed: {}",
1054                        record.source_path.display()
1055                    )
1056                })?;
1057                journal.update_move_source_disposition_durable(
1058                    &record.source_path,
1059                    MoveSourceDisposition::Deleted,
1060                )?;
1061            }
1062        } else {
1063            verify_materialized_entity(
1064                &record.source_path,
1065                &committed_entity,
1066                strict_lossless,
1067            )?;
1068            verify_materialized_entity(
1069                &record.destination_path,
1070                &committed_entity,
1071                strict_lossless,
1072            )?;
1073            std::fs::remove_file(&record.source_path).with_context(|| {
1074                format!(
1075                    "Failed to remove verified source: {}",
1076                    record.source_path.display()
1077                )
1078            })?;
1079            journal.update_move_source_disposition_durable(
1080                &record.source_path,
1081                MoveSourceDisposition::Deleted,
1082            )?;
1083        }
1084    }
1085    Ok(())
1086}
1087
1088fn verify_source_identity(source: &Path, expected: &FileEntity) -> Result<()> {
1089    let actual = FileEntity::from_filesystem_metadata_only(source, None)?;
1090    match (&actual.identity.origin, &expected.identity.origin) {
1091        (
1092            FileOrigin::Filesystem {
1093                key: actual_key, ..
1094            },
1095            FileOrigin::Filesystem {
1096                key: expected_key, ..
1097            },
1098        ) => {
1099            anyhow::ensure!(
1100                actual_key == expected_key,
1101                "Source entry was replaced: {}",
1102                source.display()
1103            );
1104        }
1105        _ => anyhow::bail!(
1106            "Source identity is unavailable: {}",
1107            source.display()
1108        ),
1109    }
1110    Ok(())
1111}
1112#[cfg(test)]
1113#[allow(
1114    clippy::panic,
1115    clippy::expect_used,
1116    clippy::unwrap_used,
1117    clippy::unwrap_in_result,
1118    clippy::panic_in_result_fn,
1119    clippy::indexing_slicing,
1120    clippy::arithmetic_side_effects,
1121    reason = "Standard repository test boilerplate"
1122)]
1123mod tests {
1124    use super::*;
1125    use crate::args::MvArgs;
1126    use crate::move_engine::run_mv;
1127    use ctb_utilities::cli::ToolResult;
1128    use std::fs;
1129    use tempfile::tempdir;
1130
1131    #[crate::ctb_test]
1132    fn test_mv_collision_requires_force() -> Result<()> {
1133        use clap::Parser;
1134        let temporary = tempdir()?;
1135        fs::create_dir(temporary.path().join("source-parent"))?;
1136        fs::create_dir(temporary.path().join("destination-parent"))?;
1137        let source = temporary.path().join("source-parent/source");
1138        let destination =
1139            temporary.path().join("destination-parent/destination");
1140        fs::write(&source, b"source payload")?;
1141        fs::write(&destination, b"destination payload")?;
1142        let args = MvArgs::try_parse_from([
1143            std::ffi::OsStr::new("mv"),
1144            std::ffi::OsStr::new("--best-effort-metadata"),
1145            source.as_os_str(),
1146            destination.as_os_str(),
1147        ])?;
1148        assert!(run_mv(args.clone()).is_err());
1149        assert_eq!(fs::read(&source)?, b"source payload");
1150        assert_eq!(fs::read(&destination)?, b"destination payload");
1151        let mut forced = args;
1152        forced.force = true;
1153        run_mv(forced)?;
1154        assert!(!source.exists());
1155        assert_eq!(fs::read(destination)?, b"source payload");
1156        Ok(())
1157    }
1158
1159    #[crate::ctb_test]
1160    #[cfg(unix)]
1161    fn test_mv_dangling_collision_preserves_entries() -> Result<()> {
1162        let temporary = tempdir()?;
1163        let source = temporary.path().join("source");
1164        let destination = temporary.path().join("destination");
1165        fs::write(&source, b"source payload")?;
1166        std::os::unix::fs::symlink("missing", &destination)?;
1167        assert!(
1168            rename_with_policy(
1169                &source,
1170                &destination,
1171                ctb_io::file::ExistingEntryPolicy::Refuse
1172            )
1173            .is_err()
1174        );
1175        assert_eq!(fs::read(&source)?, b"source payload");
1176        assert_eq!(fs::read_link(&destination)?, Path::new("missing"));
1177        Ok(())
1178    }
1179
1180    #[crate::ctb_test]
1181    fn test_mv_same_filesystem() {
1182        let _fs_lock = ctb_io::file::FS_CACHE_TEST_MUTEX.lock().unwrap();
1183        let temp = tempdir().expect("create tempdir");
1184        let src = temp.path().join("mv_src");
1185        let dest = temp.path().join("mv_dest");
1186        fs::create_dir_all(&src).expect("create src dir");
1187
1188        let file_path = src.join("move_me.txt");
1189        fs::write(&file_path, b"Move this file atomically")
1190            .expect("write file");
1191
1192        let target_file = dest.join("move_me.txt");
1193        let args = MvArgs {
1194            paths: vec![file_path.clone(), target_file.clone()],
1195            resume: None,
1196            journal_path: None,
1197            state_dir: None,
1198            verbose: true,
1199            progress: false,
1200            no_progress: true,
1201            verify_after: true,
1202            no_verify_after: false,
1203            best_effort_metadata: false,
1204            allow_unknown_fs: false,
1205            force: false,
1206            dry_run: false,
1207            full_provenance: false,
1208        };
1209
1210        let res = run_mv(args).expect("run mv");
1211        match res {
1212            ToolResult::Immediate { stdout, .. } => {
1213                let out = String::from_utf8_lossy(&stdout);
1214                assert!(out.contains("Items renamed (same filesystem): 1"));
1215                assert!(out.contains("Move completed successfully"));
1216            }
1217            _ => panic!("Expected Immediate ToolResult"),
1218        }
1219
1220        assert!(!file_path.exists(), "Source file should no longer exist");
1221        assert!(target_file.exists(), "Destination file should exist");
1222        let content = fs::read(&target_file).expect("read dest");
1223        assert_eq!(content, b"Move this file atomically");
1224    }
1225
1226    #[crate::ctb_test]
1227    fn test_mv_directory_tree() {
1228        let _fs_lock = ctb_io::file::FS_CACHE_TEST_MUTEX.lock().unwrap();
1229        let temp = tempdir().expect("create tempdir");
1230        let src_dir = temp.path().join("mv_dir_src");
1231        let dest_dir = temp.path().join("mv_dir_dest");
1232        fs::create_dir_all(src_dir.join("subdir")).expect("create src tree");
1233
1234        fs::write(src_dir.join("file1.txt"), b"Content 1")
1235            .expect("write file1");
1236        fs::write(src_dir.join("subdir").join("file2.txt"), b"Content 2")
1237            .expect("write file2");
1238
1239        let args = MvArgs {
1240            paths: vec![src_dir.clone(), dest_dir.clone()],
1241            resume: None,
1242            journal_path: None,
1243            state_dir: None,
1244            verbose: true,
1245            progress: false,
1246            no_progress: true,
1247            verify_after: true,
1248            no_verify_after: false,
1249            best_effort_metadata: false,
1250            allow_unknown_fs: false,
1251            force: false,
1252            dry_run: false,
1253            full_provenance: false,
1254        };
1255
1256        let res = run_mv(args).expect("run mv on dir");
1257        match res {
1258            ToolResult::Immediate { stdout, .. } => {
1259                let out = String::from_utf8_lossy(&stdout);
1260                assert!(out.contains("Move completed successfully"));
1261            }
1262            _ => panic!("Expected Immediate ToolResult"),
1263        }
1264
1265        assert!(!src_dir.exists(), "Source directory should no longer exist");
1266        assert!(dest_dir.join("file1.txt").exists());
1267        assert!(dest_dir.join("subdir").join("file2.txt").exists());
1268    }
1269
1270    #[crate::ctb_test]
1271    fn test_mv_cleanup_retains_uncopied_entries() {
1272        let temp = tempdir().unwrap();
1273        let source = temp.path().join("source");
1274        let destination = temp.path().join("destination");
1275        fs::create_dir(&source).unwrap();
1276        fs::create_dir(&destination).unwrap();
1277        fs::write(source.join("new-data"), b"not copied").unwrap();
1278        let entity =
1279            ctb_io::file::FileEntity::from_filesystem(&source, None).unwrap();
1280        ctb_io::file::apply_entity_metadata(
1281            &destination,
1282            None,
1283            &entity.metadata,
1284            false,
1285            true,
1286            false,
1287            cfg!(windows),
1288        )
1289        .unwrap();
1290        let entries = vec![(source.clone(), destination, entity)];
1291        assert!(
1292            crate::move_engine::remove_copied_sources(
1293                &entries, &source, false, true
1294            )
1295            .is_err()
1296        );
1297        assert_eq!(fs::read(source.join("new-data")).unwrap(), b"not copied");
1298    }
1299
1300    #[crate::ctb_test]
1301    fn test_mv_cleanup_retains_changed_source() {
1302        let temp = tempdir().unwrap();
1303        let source = temp.path().join("source");
1304        let destination = temp.path().join("destination");
1305        fs::write(&source, b"original").unwrap();
1306        let entity =
1307            ctb_io::file::FileEntity::from_filesystem(&source, None).unwrap();
1308        fs::copy(&source, &destination).unwrap();
1309        fs::write(&source, b"new data").unwrap();
1310        let entries = vec![(source.clone(), destination, entity)];
1311        assert!(
1312            crate::move_engine::remove_copied_sources(
1313                &entries, &source, false, true
1314            )
1315            .is_err()
1316        );
1317        assert_eq!(fs::read(source).unwrap(), b"new data");
1318    }
1319
1320    #[crate::ctb_test]
1321    fn test_mv_contents_fallback() {
1322        let _fs_lock = ctb_io::file::FS_CACHE_TEST_MUTEX.lock().unwrap();
1323        let temp = tempdir().unwrap();
1324        let source = temp.path().join("source");
1325        let destination = temp.path().join("destination");
1326        fs::create_dir_all(source.join("sub")).unwrap();
1327        fs::write(source.join("sub/data"), b"move payload").unwrap();
1328        let result = run_mv(MvArgs {
1329            paths: vec![source.join(""), destination.clone()],
1330            resume: None,
1331            journal_path: None,
1332            state_dir: None,
1333            verbose: false,
1334            progress: false,
1335            no_progress: true,
1336            verify_after: false,
1337            no_verify_after: true,
1338            best_effort_metadata: false,
1339            allow_unknown_fs: true,
1340            force: false,
1341            dry_run: false,
1342            full_provenance: false,
1343        });
1344        let journal_path = match result {
1345            Ok(ToolResult::Immediate { stdout, .. }) => {
1346                assert_eq!(
1347                    fs::read(destination.join("sub/data")).unwrap(),
1348                    b"move payload"
1349                );
1350                assert_eq!(fs::read_dir(&source).unwrap().count(), 0);
1351                let summary = String::from_utf8(stdout).unwrap();
1352                let journal_path = summary
1353                    .lines()
1354                    .find_map(|line| {
1355                        line.strip_prefix("Original metadata journal:")
1356                            .map(str::trim)
1357                    })
1358                    .expect("Move must retain original native metadata");
1359                let journal_path = PathBuf::from(journal_path);
1360                let snapshot =
1361                    crate::journal::read_journal_snapshot(&journal_path)
1362                        .unwrap();
1363                assert!(snapshot.is_completed);
1364                assert!(snapshot.errors.is_empty());
1365                if !snapshot.warnings.is_empty() {
1366                    assert!(summary.contains(
1367                        "fidelity limitations are retained in the journal"
1368                    ));
1369                }
1370                journal_path
1371            }
1372            Ok(_) => panic!("Expected immediate move result"),
1373            Err(error) => {
1374                // FreeBSD cannot assign the source birth time. Strict cleanup
1375                // must refuse data deletion even after best-effort copying.
1376                let diagnostic = format!("{error:#}");
1377                assert!(
1378                    diagnostic.contains("Birthtime mismatch"),
1379                    "{diagnostic}"
1380                );
1381                assert_eq!(
1382                    fs::read(source.join("sub/data")).unwrap(),
1383                    b"move payload"
1384                );
1385                assert_eq!(
1386                    fs::read(destination.join("sub/data")).unwrap(),
1387                    b"move payload"
1388                );
1389                let message = error.to_string();
1390                let journal_path = PathBuf::from(
1391                    message
1392                        .strip_prefix("Move journal retained at ")
1393                        .expect("Retained move journal"),
1394                );
1395                let snapshot =
1396                    crate::journal::read_journal_snapshot(&journal_path)
1397                        .unwrap();
1398                assert!(!snapshot.warnings.is_empty());
1399                assert!(snapshot.committed_entities.values().any(|entity| {
1400                    entity
1401                        .metadata
1402                        .timestamps
1403                        .as_ref()
1404                        .and_then(|ts| ts.birthtime_sec)
1405                        .is_some()
1406                }));
1407                journal_path
1408            }
1409        };
1410        let snapshot =
1411            crate::journal::read_journal_snapshot(&journal_path).unwrap();
1412        assert!(!snapshot.committed_entities.is_empty());
1413        let journal_path = journal_path.as_path();
1414        fs::remove_file(journal_path).unwrap();
1415        fs::remove_file(journal_path.with_extension("cscdesc")).unwrap();
1416        fs::remove_dir(journal_path.parent().unwrap()).unwrap();
1417    }
1418
1419    #[crate::ctb_test]
1420    fn test_mv_failure_retains_journal_and_source() {
1421        let _fs_lock = ctb_io::file::FS_CACHE_TEST_MUTEX.lock().unwrap();
1422        let temp = tempdir().unwrap();
1423        let source = temp.path().join("source");
1424        let destination = temp.path().join("destination");
1425        fs::create_dir_all(source.join("sub")).unwrap();
1426        fs::write(source.join("sub/data"), b"must survive failed move")
1427            .unwrap();
1428        fs::create_dir_all(destination.join("sub/data")).unwrap();
1429        let error = run_mv(MvArgs {
1430            paths: vec![source.join(""), destination.clone()],
1431            resume: None,
1432            journal_path: None,
1433            state_dir: None,
1434            verbose: false,
1435            progress: false,
1436            no_progress: true,
1437            verify_after: false,
1438            no_verify_after: true,
1439            best_effort_metadata: false,
1440            allow_unknown_fs: true,
1441            force: true,
1442            dry_run: false,
1443            full_provenance: false,
1444        })
1445        .err()
1446        .expect("Conflicting destination must refuse the move");
1447        let message = error.to_string();
1448        let journal_path = Path::new(
1449            message
1450                .strip_prefix("Move journal retained at ")
1451                .expect("Retained journal diagnostic"),
1452        );
1453        let snapshot =
1454            crate::journal::read_journal_snapshot(journal_path).unwrap();
1455        assert!(!snapshot.is_completed);
1456        assert!(!snapshot.errors.is_empty() || !snapshot.warnings.is_empty());
1457        assert_eq!(
1458            fs::read(source.join("sub/data")).unwrap(),
1459            b"must survive failed move"
1460        );
1461        fs::remove_file(journal_path).unwrap();
1462        fs::remove_file(journal_path.with_extension("cscdesc")).unwrap();
1463        fs::remove_dir(journal_path.parent().unwrap()).unwrap();
1464    }
1465
1466    #[crate::ctb_test]
1467    fn test_journal_retention_includes_semantic_diagnostics() {
1468        let temp = tempdir().unwrap();
1469        let path = temp.path().join("file");
1470        fs::write(&path, b"payload").unwrap();
1471        let mut entity = FileEntity::from_filesystem(&path, None).unwrap();
1472        entity.metadata = ctb_io::file::FileMetadata::default();
1473        assert!(!crate::journal::entity_requires_metadata_retention(&entity));
1474        entity
1475            .metadata
1476            .push_warning("Captured fidelity limitation".to_string());
1477        assert!(crate::journal::entity_requires_metadata_retention(&entity));
1478        entity.metadata.warnings.clear();
1479        entity
1480            .metadata
1481            .push_error("Captured metadata error".to_string());
1482        assert!(crate::journal::entity_requires_metadata_retention(&entity));
1483    }
1484
1485    #[crate::ctb_test]
1486    fn test_mv_durable_source_inventory_and_interrupted_deletion_recovery()
1487    -> Result<()> {
1488        let _fs_lock = ctb_io::file::FS_CACHE_TEST_MUTEX.lock().unwrap();
1489        let temp = tempdir()?;
1490        let src_rename = temp.path().join("src_rename.txt");
1491        let src_dir = temp.path().join("src_cross");
1492        let src_later = temp.path().join("src_later.txt");
1493        let dest_root = temp.path().join("dest");
1494        let journal_path = temp.path().join("state/move_recovery.cscjournal");
1495        fs::create_dir_all(journal_path.parent().unwrap())?;
1496        fs::create_dir_all(src_dir.join("nested"))?;
1497        fs::create_dir_all(&dest_root)?;
1498
1499        fs::write(&src_rename, b"renamed task payload")?;
1500        let file1 = src_dir.join("nested/alpha.txt");
1501        let file2 = src_dir.join("nested/beta.txt");
1502        fs::write(&file1, b"alpha payload")?;
1503        fs::write(&file2, b"beta payload")?;
1504        fs::write(&src_later, b"later task payload")?;
1505
1506        // 1. Run a cross-device move of src_dir contents into dest_root/cross_out to populate
1507        //    a real journal, then simulate an interruption partway through source deletion.
1508        let cross_dest = dest_root.join("cross_out");
1509        let rename_dest = dest_root.join("src_rename.txt");
1510        let later_dest = dest_root.join("src_later.txt");
1511
1512        // Perform the rename of task 1 (`src_rename -> rename_dest`)
1513        let rename_id =
1514            ctb_io::file::identity::query_file_identity(&src_rename).ok();
1515        fs::rename(&src_rename, &rename_dest)?;
1516
1517        // Copy `src_dir` to `cross_dest` using execute_copy_pipeline and record verified sources
1518        // into the journal WITHOUT deleting all sources yet (simulating crash after deleting `alpha.txt`).
1519        let desc_path = journal_path.with_extension("cscdesc");
1520        let mut journal = StateJournal::create_at_path(
1521            &journal_path,
1522            &desc_path,
1523            &[src_rename.clone(), src_dir.clone(), src_later.clone()],
1524            &dest_root,
1525        )?;
1526        journal.set_defer_completion(true);
1527
1528        let later_id =
1529            ctb_io::file::identity::query_file_identity(&src_later).ok();
1530        journal.record_move_sources_durable([
1531            MoveSourceRecord {
1532                source_path: normalize_move_source_path(&src_rename),
1533                destination_path: rename_dest.clone(),
1534                committed_relative_path: Some(PathBuf::from("src_rename.txt")),
1535                source_identity: rename_id,
1536                is_dir: false,
1537                is_task_root: true,
1538                contents_only_root: false,
1539                disposition: MoveSourceDisposition::Renamed,
1540            },
1541            MoveSourceRecord {
1542                source_path: normalize_move_source_path(&src_dir),
1543                destination_path: cross_dest.clone(),
1544                committed_relative_path: Some(PathBuf::from("cross_out")),
1545                source_identity: ctb_io::file::identity::query_file_identity(
1546                    &src_dir,
1547                )
1548                .ok(),
1549                is_dir: true,
1550                is_task_root: true,
1551                contents_only_root: false,
1552                disposition: MoveSourceDisposition::Pending,
1553            },
1554            MoveSourceRecord {
1555                source_path: normalize_move_source_path(&src_later),
1556                destination_path: later_dest.clone(),
1557                committed_relative_path: Some(PathBuf::from("src_later.txt")),
1558                source_identity: later_id,
1559                is_dir: false,
1560                is_task_root: true,
1561                contents_only_root: false,
1562                disposition: MoveSourceDisposition::Pending,
1563            },
1564        ])?;
1565
1566        let cross_task = ResolvedCopyTask {
1567            source_root: src_dir.clone(),
1568            target_root: cross_dest.clone(),
1569            copy_contents_only: false,
1570        };
1571        let csc_args = crate::args::default_test_args(
1572            vec![src_dir.clone(), cross_dest.clone()],
1573            journal_path.parent().unwrap().to_path_buf(),
1574        );
1575        discover_task_source_inventory(&cross_task, &csc_args, &mut journal)?;
1576        let progress = Progress::new(false);
1577        let copy_stats = execute_copy_pipeline(
1578            std::slice::from_ref(&cross_task),
1579            &csc_args,
1580            &mut journal,
1581            &progress,
1582        )?;
1583        record_verified_copied_sources_in_journal(
1584            &copy_stats.copied_entities,
1585            &src_dir,
1586            false,
1587            &mut journal,
1588        )?;
1589
1590        // Simulate partial deletion before crash: `alpha.txt` is unlinked and marked `Deleted`,
1591        // while `beta.txt`, `nested`, and `src_dir` remain `CopiedVerified` on disk, and
1592        // `src_later.txt` is still `Pending`.
1593        fs::remove_file(&file1)?;
1594        journal.update_move_source_disposition_durable(
1595            &normalize_move_source_path(&file1),
1596            MoveSourceDisposition::Deleted,
1597        )?;
1598        drop(journal);
1599
1600        // Sub-test A: If a new unrelated file is created at the already-deleted `alpha.txt` path
1601        // before resume, recovery must detect the identity mismatch and refuse to delete it!
1602        fs::write(&file1, b"unrelated replacement file")?;
1603        let bad_snap = read_journal_snapshot(&journal_path)?;
1604        let mut bad_journal = StateJournal::open_for_resume(
1605            &journal_path,
1606            &desc_path,
1607            &bad_snap,
1608        )?;
1609        let err = execute_journaled_source_deletion(
1610            &mut bad_journal,
1611            &src_dir,
1612            false,
1613        )
1614        .expect_err("Recreated source with different identity must be refused");
1615        assert!(
1616            format!("{err:#}").contains(
1617                "Source path was recreated with a different identity"
1618            ),
1619            "Unexpected error: {err:#}"
1620        );
1621        assert_eq!(fs::read(&file1)?, b"unrelated replacement file");
1622        fs::remove_file(&file1)?;
1623        drop(bad_journal);
1624
1625        // Sub-test B: Resume the interrupted multi-file move via `run_mv` with `--resume`.
1626        // No in-memory `copied_entities` exists; recovery uses the durable `MoveSources:` log.
1627        run_mv(MvArgs {
1628            paths: Vec::new(),
1629            resume: Some(journal_path.clone()),
1630            journal_path: None,
1631            state_dir: None,
1632            verbose: false,
1633            progress: false,
1634            no_progress: true,
1635            verify_after: true,
1636            no_verify_after: false,
1637            best_effort_metadata: true,
1638            allow_unknown_fs: true,
1639            force: false,
1640            dry_run: false,
1641            full_provenance: false,
1642        })?;
1643
1644        // Verify all 3 tasks completed and all sources are gone while destinations are intact.
1645        assert!(!src_rename.exists());
1646        assert!(!src_dir.exists());
1647        assert!(!src_later.exists());
1648        assert_eq!(fs::read(&rename_dest)?, b"renamed task payload");
1649        assert_eq!(
1650            fs::read(cross_dest.join("nested/alpha.txt"))?,
1651            b"alpha payload"
1652        );
1653        assert_eq!(
1654            fs::read(cross_dest.join("nested/beta.txt"))?,
1655            b"beta payload"
1656        );
1657        assert_eq!(fs::read(&later_dest)?, b"later task payload");
1658
1659        let final_snap = read_journal_snapshot(&journal_path)?;
1660        assert!(final_snap.is_completed);
1661        assert_eq!(
1662            final_snap
1663                .move_sources
1664                .get(&normalize_move_source_path(&src_rename))
1665                .map(|r| r.disposition),
1666            Some(MoveSourceDisposition::Renamed)
1667        );
1668        assert_eq!(
1669            final_snap
1670                .move_sources
1671                .get(&normalize_move_source_path(&file1))
1672                .map(|r| r.disposition),
1673            Some(MoveSourceDisposition::Deleted)
1674        );
1675        assert_eq!(
1676            final_snap
1677                .move_sources
1678                .get(&normalize_move_source_path(&file2))
1679                .map(|r| r.disposition),
1680            Some(MoveSourceDisposition::Deleted)
1681        );
1682        assert_eq!(
1683            final_snap
1684                .move_sources
1685                .get(&normalize_move_source_path(&src_dir))
1686                .map(|r| r.disposition),
1687            Some(MoveSourceDisposition::Deleted)
1688        );
1689        assert_eq!(
1690            final_snap
1691                .move_sources
1692                .get(&normalize_move_source_path(&src_later))
1693                .map(|r| r.disposition),
1694            Some(MoveSourceDisposition::Renamed)
1695        );
1696        Ok(())
1697    }
1698}