ctb_io_csc/
journal.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//! Transactional, crash-safe state journaling and manifest recording.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use ctb_formats_checksum::{Sha256Stream, xxhash};
30use ctb_formats_dcstring::{
31    DcMixedDecode, DcMixedEncode, DcMstring, SharedJson, SharedValueContext,
32};
33use ctb_io::file::Natural;
34use ctb_io::file::entity::{FileEntity, FileEntityKind};
35use ctb_io::file::identity::{
36    FileIdentity, FileOrigin, InodeKey, resolve_relative_path_for_os,
37};
38use ctb_io::file::link_path::LinkPath;
39use ctb_io::file::metadata::{FileFlag, FileMetadata, FileTimestamps};
40use ctb_io::file::streams::{AttachedStream, StreamKind, StreamName};
41use ctb_io_environment::EnvDescription;
42use serde::{Deserialize, Serialize};
43use std::collections::HashMap;
44use std::fs::{File, OpenOptions};
45use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
46#[cfg(unix)]
47use std::os::unix::fs::OpenOptionsExt;
48use std::path::{Path, PathBuf};
49use std::sync::Arc;
50use std::time::{SystemTime, UNIX_EPOCH};
51
52pub(crate) mod capture;
53pub mod legacy;
54mod reader;
55pub(crate) mod scanner;
56pub(crate) mod stream;
57
58pub use reader::{JournalPayload, JournalReader};
59pub use scanner::ReadMode;
60pub use stream::{
61    ARCHIVE_MAGIC, ARCHIVE_MAGIC_V1, ARCHIVE_MAGIC_V2, JournalMagic,
62    JournalWriter,
63};
64
65pub use legacy::{
66    convert_legacy_journal, convert_legacy_journal_bytes,
67    convert_legacy_journal_bytes_with_policy,
68    convert_legacy_journal_with_policy,
69};
70
71pub(crate) use legacy::{
72    JOURNAL_MAGIC_V1, PreservationRecord, PreservedStream, TAG_BATCH_COMMIT,
73    TAG_ENTITY, TAG_ERROR_RECORD, TAG_JOB_COMPLETED, TAG_SESSION_ENV,
74    TAG_SESSION_HEADER, TAG_WARNING_RECORD, read_entity_payload,
75    write_entity_payload,
76};
77
78pub const JOURNAL_MAGIC_V4: &[u8; 8] = b"CTBCSCJ\x04";
79pub const JOURNAL_MAGIC_V5: &[u8; 8] = b"CTBCSCJ\x05";
80pub const JOURNAL_MAGIC: &[u8; 8] = JOURNAL_MAGIC_V5;
81pub const SESSION_ENVIRONMENT_BINDING: &str = "csc.session.environment";
82
83pub(crate) fn session_context(
84    session: &JournalSessionRecord,
85) -> Result<SharedValueContext> {
86    let mut context = SharedValueContext::default();
87    if let Some(environment) = &session.environment {
88        context.insert(SESSION_ENVIRONMENT_BINDING, Arc::clone(environment))?;
89        context.insert("environment", Arc::clone(environment))?;
90    }
91    Ok(context)
92}
93
94pub const PLATFORM_LINUX: u8 = 1;
95pub const PLATFORM_MACOS: u8 = 2;
96pub const PLATFORM_WINDOWS: u8 = 3;
97pub const PLATFORM_OTHER: u8 = 4;
98
99/// Stage in the copy pipeline where an operation or file access error occurred.
100#[derive(
101    Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize,
102)]
103pub enum JournalErrorStage {
104    /// Directory listing or entry enumeration failed.
105    Traversal,
106    /// Inspection of file status, flags, xattrs, or streams failed.
107    MetadataRead,
108    /// Opening source file or device failed.
109    PayloadOpen,
110    /// Reading file payload or stream data failed.
111    PayloadRead,
112    /// Writing or flushing destination payload or metadata failed.
113    Materialize,
114    /// Post-copy verification or concurrent modification check failed.
115    PostCheck,
116}
117
118impl JournalErrorStage {
119    /// Encodes the stage as a compact numeric code.
120    #[must_use]
121    pub const fn to_code(self) -> u8 {
122        match self {
123            Self::Traversal => 0,
124            Self::MetadataRead => 1,
125            Self::PayloadOpen => 2,
126            Self::PayloadRead => 3,
127            Self::Materialize => 4,
128            Self::PostCheck => 5,
129        }
130    }
131
132    /// Decodes a numeric code into the corresponding stage.
133    #[must_use]
134    pub const fn from_code(code: u8) -> Self {
135        match code {
136            1 => Self::MetadataRead,
137            2 => Self::PayloadOpen,
138            3 => Self::PayloadRead,
139            4 => Self::Materialize,
140            5 => Self::PostCheck,
141            _ => Self::Traversal,
142        }
143    }
144}
145
146/// A persistent record of an item or operation failure stored in the journal.
147#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
148pub struct JournalErrorRecord {
149    pub path: PathBuf,
150    pub raw_path: Vec<u8>,
151    pub stage: JournalErrorStage,
152    pub error_message: String,
153    pub os_error: Option<i32>,
154    pub timestamp_sec: i64,
155}
156
157impl JournalErrorRecord {
158    /// Captures an operational failure without discarding its native cause.
159    #[must_use]
160    pub fn from_error(
161        path: &Path,
162        stage: JournalErrorStage,
163        error: &anyhow::Error,
164    ) -> Self {
165        Self {
166            path: path.to_path_buf(),
167            raw_path: path.as_os_str().as_encoded_bytes().to_vec(),
168            stage,
169            error_message: format!("{error:#}"),
170            os_error: error
171                .downcast_ref::<std::io::Error>()
172                .and_then(std::io::Error::raw_os_error),
173            timestamp_sec: sec_from_system_time(SystemTime::now()),
174        }
175    }
176}
177
178/// A persistent record of an operational warning or caveat stored in the journal.
179#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
180pub struct JournalWarningRecord {
181    pub code: String,
182    pub message: String,
183    pub timestamp_sec: i64,
184}
185
186/// Persistent operation session record bounded by Dc 547..548.
187#[derive(
188    Debug,
189    Clone,
190    PartialEq,
191    Eq,
192    serde::Serialize,
193    serde::Deserialize,
194    ctb_formats_dcstring::DcMixed,
195)]
196#[dc(begin = 547, end = 548)]
197pub struct JournalSessionRecord {
198    #[dc(549)]
199    pub sources: Vec<PathBuf>,
200    #[dc(550)]
201    pub destination: PathBuf,
202    #[dc(558)]
203    pub origin_platform: u32,
204    #[dc(nested = 340, shared = "environment")]
205    pub environment: Option<Arc<EnvDescription>>,
206}
207
208fn system_time_from_sec(timestamp_sec: i64) -> std::time::SystemTime {
209    let dur = std::time::Duration::from_secs(timestamp_sec.unsigned_abs());
210    if timestamp_sec < 0 {
211        match UNIX_EPOCH.checked_sub(dur) {
212            Some(t) => t,
213            // Reason for fallback: Pre-epoch timestamp underflowing SystemTime limits falls back to UNIX_EPOCH.
214            None => UNIX_EPOCH,
215        }
216    } else {
217        match UNIX_EPOCH.checked_add(dur) {
218            Some(t) => t,
219            // Reason for fallback: Post-epoch timestamp overflowing SystemTime limits falls back to UNIX_EPOCH.
220            None => UNIX_EPOCH,
221        }
222    }
223}
224
225fn sec_from_system_time(time: std::time::SystemTime) -> i64 {
226    match time.duration_since(UNIX_EPOCH) {
227        // Reason for fallback: Duration after epoch exceeding i64::MAX seconds clamps to i64::MAX.
228        Ok(dur) => i64::try_from(dur.as_secs()).unwrap_or(i64::MAX),
229        Err(err) => {
230            let dur = err.duration();
231            let secs = match i64::try_from(dur.as_secs()) {
232                Ok(s) => s,
233                // Reason for fallback: Duration before epoch exceeding i64::MAX seconds clamps to i64::MIN.
234                Err(_) => return i64::MIN,
235            };
236            let neg_secs = secs.saturating_neg();
237            if dur.subsec_nanos() == 0 {
238                neg_secs
239            } else {
240                neg_secs.saturating_sub(1)
241            }
242        }
243    }
244}
245
246/// Persistent error incident payload bounded by Dc 552..553.
247#[derive(
248    Debug,
249    Clone,
250    PartialEq,
251    Eq,
252    serde::Serialize,
253    serde::Deserialize,
254    ctb_formats_dcstring::DcMixed,
255)]
256#[dc(begin = 552, end = 553)]
257pub struct JournalErrorRecordPayload {
258    #[dc(549)]
259    pub path: PathBuf,
260    #[dc(558)]
261    pub packed_status: u64,
262    #[dc(556)]
263    pub error_message: String,
264    #[dc(nested = 390)]
265    pub timestamp: std::time::SystemTime,
266}
267
268impl JournalErrorRecordPayload {
269    /// Uses the record's typed path and whole-second timestamp for v4 encoding.
270    /// The separate `raw_path` field is not serialized by this format.
271    ///
272    /// # Errors
273    /// Rejects `Some(0)`, which is indistinguishable from no native OS error.
274    pub fn from_record(record: &JournalErrorRecord) -> Result<Self> {
275        let stage_code = u64::from(record.stage.to_code());
276        let os_code = match record.os_error {
277            Some(error_code) => {
278                anyhow::ensure!(
279                    error_code != 0,
280                    "Zero OS error code cannot be distinguished from an absent error in this journal format"
281                );
282                u64::from(u32::from_le_bytes(error_code.to_le_bytes()))
283            }
284            None => 0_u64,
285        };
286        Ok(Self::new(
287            record.path.clone(),
288            (stage_code << 32) | os_code,
289            record.error_message.clone(),
290            record.timestamp_sec,
291        ))
292    }
293
294    /// Reconstructs raw bytes from the decoded host path and floors the timestamp
295    /// to whole seconds. Unknown byte-sized stages retain the traversal fallback.
296    ///
297    /// # Errors
298    /// Rejects stages larger than one byte under the strict journal policy.
299    pub fn to_record(
300        &self,
301        policy: &ctb_formats_dcstring::DcProjectionPolicy,
302    ) -> Result<JournalErrorRecord> {
303        let stage_code =
304            if let Ok(code) = u8::try_from(self.packed_status >> 32) {
305                code
306            } else {
307                anyhow::ensure!(
308                    !policy.is_strict(),
309                    "Invalid stage code in error record"
310                );
311                0
312            };
313        let os_code = u32::try_from(self.packed_status & 0xFFFF_FFFF)?;
314        Ok(JournalErrorRecord {
315            path: self.path.clone(),
316            raw_path: self.path.as_os_str().as_encoded_bytes().to_vec(),
317            stage: JournalErrorStage::from_code(stage_code),
318            error_message: self.error_message.clone(),
319            os_error: if os_code == 0 {
320                None
321            } else {
322                Some(i32::from_le_bytes(os_code.to_le_bytes()))
323            },
324            timestamp_sec: self.timestamp_sec(),
325        })
326    }
327
328    #[must_use]
329    pub fn new(
330        path: PathBuf,
331        packed_status: u64,
332        error_message: String,
333        timestamp_sec: i64,
334    ) -> Self {
335        Self {
336            path,
337            packed_status,
338            error_message,
339            timestamp: system_time_from_sec(timestamp_sec),
340        }
341    }
342
343    #[must_use]
344    pub fn error_message(&self) -> &str {
345        &self.error_message
346    }
347
348    #[must_use]
349    pub fn timestamp_sec(&self) -> i64 {
350        sec_from_system_time(self.timestamp)
351    }
352}
353
354/// Persistent warning incident payload bounded by Dc 554..555.
355#[derive(
356    Debug,
357    Clone,
358    PartialEq,
359    Eq,
360    serde::Serialize,
361    serde::Deserialize,
362    ctb_formats_dcstring::DcMixed,
363)]
364#[dc(begin = 554, end = 555)]
365pub struct JournalWarningRecordPayload {
366    #[dc(556)]
367    pub message: String,
368    #[dc(nested = 390)]
369    pub timestamp: std::time::SystemTime,
370}
371
372impl JournalWarningRecordPayload {
373    /// Combines the warning code and message using the journal's `": "` delimiter.
374    #[must_use]
375    pub fn from_record(record: &JournalWarningRecord) -> Self {
376        Self::new(&record.code, &record.message, record.timestamp_sec)
377    }
378
379    /// Splits at the first `": "`, retaining later delimiters in the message.
380    /// Warnings without a delimiter have an empty code.
381    #[must_use]
382    pub fn to_record(&self) -> JournalWarningRecord {
383        let (code, message) = match self.message.split_once(": ") {
384            Some((code, message)) => (code.to_string(), message.to_string()),
385            None => (String::new(), self.message.clone()),
386        };
387        JournalWarningRecord {
388            code,
389            message,
390            timestamp_sec: self.timestamp_sec(),
391        }
392    }
393
394    #[must_use]
395    pub fn new(code: &str, message: &str, timestamp_sec: i64) -> Self {
396        Self {
397            message: format!("{code}: {message}"),
398            timestamp: system_time_from_sec(timestamp_sec),
399        }
400    }
401
402    #[must_use]
403    pub fn combined_message(&self) -> &str {
404        &self.message
405    }
406
407    #[must_use]
408    pub fn timestamp_sec(&self) -> i64 {
409        sec_from_system_time(self.timestamp)
410    }
411}
412
413/// Persistent warning incident payload with string-only log bounded by Dc 554..555.
414#[derive(
415    Debug,
416    Clone,
417    PartialEq,
418    Eq,
419    serde::Serialize,
420    serde::Deserialize,
421    ctb_formats_dcstring::DcMixed,
422)]
423#[dc(begin = 554, end = 555)]
424pub struct JournalWarningRecordStringPayload {
425    #[dc(556)]
426    pub message: String,
427}
428
429#[must_use]
430pub fn current_platform() -> u8 {
431    if cfg!(target_os = "linux") {
432        PLATFORM_LINUX
433    } else if cfg!(target_os = "macos") {
434        PLATFORM_MACOS
435    } else if cfg!(target_os = "windows") {
436        PLATFORM_WINDOWS
437    } else {
438        PLATFORM_OTHER
439    }
440}
441
442/// Durable identity receipt proving exclusive creation and authorization of a
443/// destination directory across crash and resume sessions.
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
445pub struct AppliedDirectoryReceipt {
446    pub relative: PathBuf,
447    pub identity: InodeKey,
448}
449
450/// Durable per-source lifecycle state for multi-file and cross-device move operations.
451#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
452pub enum MoveSourceDisposition {
453    /// Intended source entry discovered before copy/move execution.
454    Pending,
455    /// Source entry was atomically renamed on the same filesystem.
456    Renamed,
457    /// Source entry was copied and verified on the destination, awaiting source deletion.
458    CopiedVerified,
459    /// Source entry was verified and deleted from the source filesystem.
460    Deleted,
461    /// Source root directory was intentionally retained (`copy_contents_only`).
462    RetainedRoot,
463}
464
465/// Durable source inventory and deletion/recovery record persisted in `.cscdesc`.
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467pub struct MoveSourceRecord {
468    pub source_path: PathBuf,
469    pub destination_path: PathBuf,
470    #[serde(default, skip_serializing_if = "Option::is_none")]
471    pub committed_relative_path: Option<PathBuf>,
472    #[serde(default, skip_serializing_if = "Option::is_none")]
473    pub source_identity: Option<InodeKey>,
474    pub is_dir: bool,
475    #[serde(default)]
476    pub is_task_root: bool,
477    #[serde(default)]
478    pub contents_only_root: bool,
479    pub disposition: MoveSourceDisposition,
480}
481
482/// Summary of an active or completed journal recovered from disk.
483#[derive(Debug, Clone)]
484pub struct JournalSnapshot {
485    pub sources: Vec<PathBuf>,
486    pub destination: PathBuf,
487    pub origin_platform: u8,
488    pub committed_entities: HashMap<Vec<u8>, FileEntity>,
489    pub is_completed: bool,
490    pub last_batch_id: u64,
491    pub valid_length: u64,
492    pub noatime_used: bool,
493    pub environment: Option<Arc<EnvDescription>>,
494    pub errors: Vec<JournalErrorRecord>,
495    pub warnings: Vec<JournalWarningRecord>,
496    pub applied_directories: HashMap<PathBuf, InodeKey>,
497    pub move_sources: HashMap<PathBuf, MoveSourceRecord>,
498}
499
500impl JournalSnapshot {
501    /// Returns true if the relative path (in raw bytes) has been committed.
502    #[must_use]
503    pub fn is_committed(&self, rel_bytes: &[u8]) -> bool {
504        self.committed_entities.contains_key(rel_bytes)
505            || self.committed_entities.values().any(|entity| {
506                entity
507                    .metadata
508                    .source_relative_path()
509                    .is_some_and(|src| src.as_os_str().as_encoded_bytes() == rel_bytes)
510                    || entity
511                        .metadata
512                        .native
513                        .as_ref()
514                        .and_then(|native| native.values.get("source.relative_path"))
515                        .is_some_and(|val| {
516                            matches!(
517                                val,
518                                ctb_io::file::metadata::NativeMetadataValue::Bytes(bytes)
519                                    if bytes.as_slice() == rel_bytes
520                            )
521                        })
522            })
523    }
524
525    /// Returns the actual relative path where `source_rel` was materialized on disk,
526    /// even if best-effort mode or format conversion renamed or truncated it.
527    #[must_use]
528    pub fn materialized_path_for(&self, source_rel: &Path) -> Option<PathBuf> {
529        let raw_bytes = source_rel.as_os_str().as_encoded_bytes();
530        for entity in self.committed_entities.values() {
531            if entity.metadata.source_relative_path().as_deref()
532                == Some(source_rel)
533            {
534                return entity
535                    .metadata
536                    .materialized_relative_path()
537                    .or_else(|| entity.identity.relative_path.clone());
538            }
539        }
540        if let Some(entity) = self.committed_entities.get(raw_bytes) {
541            return entity
542                .metadata
543                .materialized_relative_path()
544                .or_else(|| entity.identity.relative_path.clone())
545                .or_else(|| Some(source_rel.to_path_buf()));
546        }
547        None
548    }
549}
550
551pub(crate) fn entity_requires_metadata_retention(entity: &FileEntity) -> bool {
552    entity.metadata.native.is_some()
553        || entity
554            .metadata
555            .timestamps
556            .as_ref()
557            .and_then(|ts| ts.birthtime_sec)
558            .is_some()
559        || entity.metadata.platform_raw_flags.is_some()
560        || !entity.streams.is_empty()
561        || !entity.metadata.warnings.is_empty()
562        || !entity.metadata.errors.is_empty()
563}
564
565/// Writer managing the persistent state journal and its companion `.cscdesc` file.
566pub struct StateJournal {
567    journal_path: PathBuf,
568    desc_path: PathBuf,
569    writer: stream::JournalWriter<BufWriter<File>>,
570    sources: Vec<PathBuf>,
571    destination: PathBuf,
572    current_batch_id: u64,
573    uncommitted_entities: Vec<FileEntity>,
574    committed_entities: HashMap<Vec<u8>, FileEntity>,
575    total_committed_files: u64,
576    total_committed_bytes: u64,
577    noatime_used: bool,
578    pub environment: Option<Arc<EnvDescription>>,
579    snapshot: Option<JournalSnapshot>,
580    errors: Vec<JournalErrorRecord>,
581    warnings: Vec<JournalWarningRecord>,
582    pending_descriptor_status: Option<String>,
583    applied_directories: HashMap<PathBuf, InodeKey>,
584    move_sources: HashMap<PathBuf, MoveSourceRecord>,
585    defer_completion: bool,
586}
587
588impl StateJournal {
589    /// Creates a new state journal at the specified path.
590    /// Fails with an error if either file already exists.
591    pub fn create_at_path(
592        journal_path: &Path,
593        desc_path: &Path,
594        sources: &[PathBuf],
595        destination: &Path,
596    ) -> Result<Self> {
597        let mut opts = OpenOptions::new();
598        opts.write(true).create_new(true);
599        #[cfg(unix)]
600        opts.mode(0o600);
601        let file = opts
602            .open(journal_path)
603            .with_context(|| {
604                format!(
605                    "Failed to create state journal (file already exists or inaccessible): {}",
606                    journal_path.display()
607                )
608            })?;
609
610        let env = ctb_io_environment::capture_quick_arc();
611        let session = JournalSessionRecord {
612            sources: sources.to_vec(),
613            destination: destination.to_path_buf(),
614            origin_platform: u32::from(current_platform()),
615            environment: Some(Arc::clone(&env)),
616        };
617        let mut writer = stream::JournalWriter::new(
618            BufWriter::new(file),
619            &session,
620            stream::JournalMagic::JournalV5,
621        )?;
622        Self::sync_output(writer.output_mut())?;
623
624        let jw = Self {
625            journal_path: journal_path.to_path_buf(),
626            desc_path: desc_path.to_path_buf(),
627            writer,
628            sources: sources.to_vec(),
629            destination: destination.to_path_buf(),
630            current_batch_id: 0,
631            uncommitted_entities: Vec::new(),
632            committed_entities: HashMap::new(),
633            total_committed_files: 0,
634            total_committed_bytes: 0,
635            noatime_used: false,
636            environment: Some(env),
637            snapshot: None,
638            errors: Vec::new(),
639            warnings: Vec::new(),
640            pending_descriptor_status: None,
641            applied_directories: HashMap::new(),
642            move_sources: HashMap::new(),
643            defer_completion: false,
644        };
645
646        jw.update_desc_file("InProgress")?;
647        Ok(jw)
648    }
649
650    /// Creates a new timestamped state journal directly in the user's home directory.
651    /// Fails with an error if either file already exists.
652    pub fn create_new(
653        home_dir: &Path,
654        sources: &[PathBuf],
655        destination: &Path,
656    ) -> Result<Self> {
657        let now = SystemTime::now()
658            .duration_since(UNIX_EPOCH)
659            .context("System clock before Unix epoch")?;
660        let secs = now.as_secs();
661        let nanos = now.subsec_nanos();
662        let pid = std::process::id();
663        let base_name = format!("csc_state_{secs}_{nanos}_{pid}");
664
665        let journal_path = home_dir.join(format!("{base_name}.cscjournal"));
666        let desc_path = home_dir.join(format!("{base_name}.cscdesc"));
667        Self::create_at_path(&journal_path, &desc_path, sources, destination)
668    }
669
670    /// Reopens a journal, preserving all committed bytes and completion markers.
671    /// Previously completed journals explicitly begin a new writable session.
672    /// Legacy journals (prior to `CSCJRNL5` / `DcMixed2`) are rejected with an error.
673    pub fn open_for_resume(
674        journal_path: &Path,
675        desc_path: &Path,
676        snapshot: &JournalSnapshot,
677    ) -> Result<Self> {
678        let mut header = [0_u8; 8 + ctb_formats_dcstring::DCMM_HEADER_LEN];
679        {
680            let mut f = File::open(journal_path).with_context(|| {
681                format!(
682                    "Failed to open state journal: {}",
683                    journal_path.display()
684                )
685            })?;
686            f.read_exact(&mut header).with_context(|| {
687                format!(
688                    "State journal header is too short to resume: {}",
689                    journal_path.display()
690                )
691            })?;
692        }
693        ensure!(
694            header.get(..8) == Some(JOURNAL_MAGIC_V5.as_slice())
695                && header.get(8..13)
696                    == Some(ctb_formats_dcstring::DCMM_MAGIC.as_slice())
697                && header.get(13..29)
698                    == Some(ctb_formats_dcstring::DCMM_UUID.as_slice()),
699            "Cannot resume a legacy CSC journal (expected CSCJRNL5 / DcMixed2): {}",
700            journal_path.display()
701        );
702
703        let mut file = OpenOptions::new()
704            .write(true)
705            .open(journal_path)
706            .with_context(|| {
707                format!(
708                    "Failed to reopen state journal: {}",
709                    journal_path.display()
710                )
711            })?;
712        let mut total_bytes = 0_u64;
713        let mut total_files = 0_u64;
714        for e in snapshot.committed_entities.values() {
715            if let FileEntityKind::Regular { size, .. } = e.kind {
716                total_bytes = total_bytes.saturating_add(size);
717                total_files = total_files.saturating_add(1);
718            }
719        }
720
721        file.set_len(snapshot.valid_length)
722            .context("Failed to discard uncommitted journal tail")?;
723        file.sync_all()?;
724        std::io::Seek::seek(&mut file, std::io::SeekFrom::End(0))?;
725        let session = JournalSessionRecord {
726            sources: snapshot.sources.clone(),
727            destination: snapshot.destination.clone(),
728            origin_platform: u32::from(snapshot.origin_platform),
729            environment: snapshot.environment.clone(),
730        };
731        let writer = stream::JournalWriter::resume_output(
732            BufWriter::new(file),
733            &session,
734            snapshot.last_batch_id,
735            false,
736        )?;
737        Ok(Self {
738            journal_path: journal_path.to_path_buf(),
739            desc_path: desc_path.to_path_buf(),
740            writer,
741            sources: snapshot.sources.clone(),
742            destination: snapshot.destination.clone(),
743            current_batch_id: snapshot.last_batch_id,
744            uncommitted_entities: Vec::new(),
745            committed_entities: snapshot.committed_entities.clone(),
746            total_committed_files: total_files,
747            total_committed_bytes: total_bytes,
748            noatime_used: snapshot.noatime_used,
749            environment: snapshot.environment.clone(),
750            snapshot: Some(snapshot.clone()),
751            errors: snapshot.errors.clone(),
752            warnings: snapshot.warnings.clone(),
753            pending_descriptor_status: None,
754            applied_directories: snapshot.applied_directories.clone(),
755            move_sources: snapshot.move_sources.clone(),
756            defer_completion: false,
757        })
758    }
759
760    /// Configures whether `execute_copy_pipeline` should defer marking the journal
761    /// completed (e.g., until source deletion finishes in a move operation).
762    pub fn set_defer_completion(&mut self, defer: bool) {
763        self.defer_completion = defer;
764    }
765
766    /// Whether completion marking is deferred until post-copy move cleanup completes.
767    #[must_use]
768    pub const fn defer_completion(&self) -> bool {
769        self.defer_completion
770    }
771
772    /// Read-only map of all committed entities in this journal session.
773    #[must_use]
774    pub fn committed_entities(&self) -> &HashMap<Vec<u8>, FileEntity> {
775        &self.committed_entities
776    }
777
778    /// Read-only map of all durable move source inventory and disposition records.
779    #[must_use]
780    pub fn move_sources(&self) -> &HashMap<PathBuf, MoveSourceRecord> {
781        &self.move_sources
782    }
783
784    /// Inserts or updates a move source inventory record in memory.
785    pub fn record_move_source(&mut self, record: MoveSourceRecord) {
786        self.move_sources.insert(record.source_path.clone(), record);
787    }
788
789    /// Inserts or updates move source inventory records and flushes `.cscdesc` durably.
790    pub fn record_move_sources_durable(
791        &mut self,
792        records: impl IntoIterator<Item = MoveSourceRecord>,
793    ) -> Result<()> {
794        for record in records {
795            self.move_sources.insert(record.source_path.clone(), record);
796        }
797        self.persist_descriptor("InProgress".to_owned())
798    }
799
800    /// Updates the durable disposition of a move source entry and flushes `.cscdesc` durably.
801    pub fn update_move_source_disposition_durable(
802        &mut self,
803        source_path: &Path,
804        disposition: MoveSourceDisposition,
805    ) -> Result<()> {
806        let record =
807            self.move_sources.get_mut(source_path).with_context(|| {
808                format!(
809                    "Missing move source inventory record for {}",
810                    source_path.display()
811                )
812            })?;
813        record.disposition = disposition;
814        self.persist_descriptor("InProgress".to_owned())
815    }
816
817    /// Looks up the committed [`FileEntity`] corresponding to a [`MoveSourceRecord`].
818    #[must_use]
819    pub fn committed_entity_for_move_source<'a>(
820        &'a self,
821        record: &MoveSourceRecord,
822    ) -> Option<&'a FileEntity> {
823        if let Some(ref rel) = record.committed_relative_path {
824            let rel_bytes = rel.as_os_str().as_encoded_bytes();
825            if let Some(entity) = self.committed_entities.get(rel_bytes) {
826                return Some(entity);
827            }
828            if let Some(mat_rel) = self.materialized_path_for(rel) {
829                if let Some(entity) = self
830                    .committed_entities
831                    .get(mat_rel.as_os_str().as_encoded_bytes())
832                {
833                    return Some(entity);
834                }
835            }
836        }
837        if let Some(ref expected_key) = record.source_identity {
838            for entity in self.committed_entities.values() {
839                if let FileOrigin::Filesystem { key, .. } =
840                    &entity.identity.origin
841                {
842                    if key == expected_key && entity.is_dir() == record.is_dir {
843                        return Some(entity);
844                    }
845                }
846            }
847        }
848        None
849    }
850
851    /// Records an applied destination directory identity receipt for crash recovery.
852    pub fn record_applied_directory(
853        &mut self,
854        relative: PathBuf,
855        identity: InodeKey,
856    ) {
857        self.applied_directories.insert(relative, identity);
858    }
859
860    /// Read-only map of all applied destination directory identity receipts.
861    #[must_use]
862    pub fn applied_directories(&self) -> &HashMap<PathBuf, InodeKey> {
863        &self.applied_directories
864    }
865
866    /// Records whether `O_NOATIME` was successfully used for payload operations.
867    pub fn record_noatime_used(&mut self, used: bool) {
868        if used {
869            self.noatime_used = true;
870        }
871    }
872
873    /// Whether `O_NOATIME` was used during this journal session.
874    #[must_use]
875    pub const fn noatime_used(&self) -> bool {
876        self.noatime_used
877    }
878
879    fn sync_output(writer: &mut BufWriter<File>) -> Result<()> {
880        writer.flush()?;
881        writer.get_ref().sync_data()?;
882        Ok(())
883    }
884
885    /// Queues a `FileEntity` for transactional commit.
886    /// In copy mode, stream payloads are stripped so that `.cscjournal` records
887    /// only stream metadata and checksums rather than duplicating stream bodies.
888    /// A poisoned or completed writer retains the item; the next commit fails.
889    pub fn record_entity(&mut self, entity: &FileEntity) {
890        let mut entity = entity.clone();
891        entity.strip_stream_bodies();
892        self.uncommitted_entities.push(entity);
893    }
894
895    /// Commits all pending items to disk with an explicit fsync, advancing the transaction.
896    pub fn commit_batch(&mut self) -> Result<()> {
897        self.ensure_ready()?;
898        if self.uncommitted_entities.is_empty() {
899            return Ok(());
900        }
901
902        self.writer
903            .write_batch(&self.uncommitted_entities, Self::sync_output)?;
904        self.current_batch_id = self.writer.sequence();
905        for entity in &self.uncommitted_entities {
906            if let FileEntityKind::Regular { size, .. } = entity.kind {
907                self.total_committed_files =
908                    self.total_committed_files.saturating_add(1);
909                self.total_committed_bytes =
910                    self.total_committed_bytes.saturating_add(size);
911            }
912            let path_key = match entity.identity.path_bytes() {
913                Some(bytes) => bytes.to_vec(),
914                None => Vec::new(),
915            };
916            if let Some(source_rel) = entity.metadata.source_relative_path() {
917                let source_bytes = source_rel.as_os_str().as_encoded_bytes();
918                if source_bytes != path_key.as_slice() {
919                    self.committed_entities.remove(source_bytes);
920                }
921            }
922            self.committed_entities.insert(path_key, entity.clone());
923        }
924
925        self.uncommitted_entities.clear();
926        self.persist_descriptor("InProgress".to_owned())?;
927        Ok(())
928    }
929
930    /// Marks the job as completely finished and updates the `.cscdesc` companion file.
931    pub fn mark_completed(&mut self) -> Result<()> {
932        self.commit_batch()?;
933        self.writer.complete(Self::sync_output)?;
934        if self.errors.is_empty() && !self.warnings.is_empty() {
935            self.persist_descriptor(format!(
936                "Completed with {} warning(s)",
937                self.warnings.len()
938            ))?;
939        } else if self.errors.is_empty() {
940            self.persist_descriptor("Completed".to_owned())?;
941        } else {
942            self.persist_descriptor(format!(
943                "Completed with {} error(s)",
944                self.errors.len()
945            ))?;
946        }
947        Ok(())
948    }
949
950    /// Records an item or operational error directly into the state journal and descriptor.
951    pub fn record_error(&mut self, error: &JournalErrorRecord) -> Result<()> {
952        self.ensure_ready()?;
953        self.writer.record_error_durable(error, Self::sync_output)?;
954        self.errors.push(error.clone());
955        self.persist_descriptor("InProgress".to_owned())?;
956        Ok(())
957    }
958
959    /// Records a caveat or operational warning directly into the state journal and descriptor.
960    pub fn record_warning(&mut self, code: &str, message: &str) -> Result<()> {
961        self.ensure_ready()?;
962        // Reason for fallback: pre-epoch system clock failure defaults warning timestamp to 0
963        let now_sec = SystemTime::now()
964            .duration_since(UNIX_EPOCH)
965            .ok()
966            .and_then(|d| i64::try_from(d.as_secs()).ok())
967            .unwrap_or(0);
968        let record = JournalWarningRecord {
969            code: code.to_string(),
970            message: message.to_string(),
971            timestamp_sec: now_sec,
972        };
973        self.writer
974            .record_warning_durable(&record, Self::sync_output)?;
975        self.warnings.push(record);
976        self.persist_descriptor("InProgress".to_owned())?;
977        Ok(())
978    }
979
980    /// Marks the job as failed with a specified reason and updates `.cscdesc`.
981    pub fn mark_failed(&mut self, reason: &str) -> Result<()> {
982        self.commit_batch().with_context(|| format!("Failed to commit pending journal records while marking failure: {reason}"))?;
983        self.writer.transaction(|_, _| Ok(()), Self::sync_output)?;
984        let status = format!("Failed: {reason}");
985        self.persist_descriptor(status)?;
986        Ok(())
987    }
988
989    fn ensure_ready(&self) -> Result<()> {
990        ensure!(
991            self.pending_descriptor_status.is_none(),
992            "Journal metadata repair pending; call retry_descriptor before writing"
993        );
994        self.writer.ensure_ready()
995    }
996
997    /// Returns the descriptor status awaiting metadata-only repair.
998    #[must_use]
999    pub fn pending_descriptor_status(&self) -> Option<&str> {
1000        self.pending_descriptor_status.as_deref()
1001    }
1002
1003    fn persist_descriptor(&mut self, status: String) -> Result<()> {
1004        self.pending_descriptor_status = Some(status);
1005        self.retry_descriptor()
1006    }
1007
1008    /// Retries only a pending descriptor update, without writing journal bytes.
1009    /// Failure retains the pending status and blocks further journal writes.
1010    /// Success does not reopen a completed writer or permit duplicate completion.
1011    pub fn retry_descriptor(&mut self) -> Result<()> {
1012        let status = self
1013            .pending_descriptor_status
1014            .as_deref()
1015            .context("No journal descriptor repair is pending")?;
1016        self.update_desc_file(status)
1017            .context("Journal operation is durable but descriptor update failed; retry_descriptor is required")?;
1018        self.pending_descriptor_status = None;
1019        Ok(())
1020    }
1021
1022    /// Slice of all errors recorded during this journal session.
1023    #[must_use]
1024    pub fn errors(&self) -> &[JournalErrorRecord] {
1025        &self.errors
1026    }
1027
1028    /// Slice of all warnings and caveats recorded during this journal session.
1029    #[must_use]
1030    pub fn warnings(&self) -> &[JournalWarningRecord] {
1031        &self.warnings
1032    }
1033
1034    fn update_desc_file(&self, status: &str) -> Result<()> {
1035        use std::fmt::Write;
1036        let mut desc_text = String::new();
1037        writeln!(desc_text, "CSC State File")?;
1038        writeln!(desc_text, "Status: {status}")?;
1039        writeln!(desc_text, "FilesCommitted: {}", self.total_committed_files)?;
1040        writeln!(desc_text, "BytesCommitted: {}", self.total_committed_bytes)?;
1041        writeln!(desc_text, "ErrorsCount: {}", self.errors.len())?;
1042        if !self.errors.is_empty() {
1043            writeln!(desc_text, "Errors:")?;
1044            for err in &self.errors {
1045                writeln!(
1046                    desc_text,
1047                    "  - [{:?}] {}: {}",
1048                    err.stage,
1049                    ctb_formats_string::escape_path_human_readable(&err.path),
1050                    err.error_message
1051                )?;
1052            }
1053        }
1054        writeln!(desc_text, "WarningsCount: {}", self.warnings.len())?;
1055        if !self.warnings.is_empty() {
1056            writeln!(desc_text, "Warnings:")?;
1057            for warn in &self.warnings {
1058                writeln!(desc_text, "  - [{}]: {}", warn.code, warn.message)?;
1059            }
1060        }
1061        writeln!(desc_text, "Sources:")?;
1062        for s in &self.sources {
1063            writeln!(
1064                desc_text,
1065                "  - {}",
1066                ctb_formats_string::escape_path_human_readable(s)
1067            )?;
1068        }
1069        writeln!(
1070            desc_text,
1071            "Destination: {}",
1072            ctb_formats_string::escape_path_human_readable(&self.destination)
1073        )?;
1074        writeln!(desc_text, "NoatimeUsed: {}", self.noatime_used)?;
1075        if !self.applied_directories.is_empty() {
1076            writeln!(desc_text, "AppliedDirectories:")?;
1077            let mut sorted: Vec<_> = self.applied_directories.iter().collect();
1078            sorted.sort_by(|a, b| a.0.cmp(b.0));
1079            for (rel, id) in sorted {
1080                let receipt = AppliedDirectoryReceipt {
1081                    relative: rel.clone(),
1082                    identity: id.clone(),
1083                };
1084                let line = serde_json::to_string(&receipt)?;
1085                writeln!(desc_text, "  - {line}")?;
1086            }
1087        }
1088        if !self.move_sources.is_empty() {
1089            writeln!(desc_text, "MoveSources:")?;
1090            let mut sorted: Vec<_> = self.move_sources.iter().collect();
1091            sorted.sort_by(|a, b| a.0.cmp(b.0));
1092            for (_, record) in sorted {
1093                let line = serde_json::to_string(record)?;
1094                writeln!(desc_text, "  - {line}")?;
1095            }
1096        }
1097
1098        ctb_io::file::write_file_durable(&self.desc_path, desc_text.as_bytes())
1099    }
1100
1101    #[must_use]
1102    pub fn journal_path(&self) -> &Path {
1103        &self.journal_path
1104    }
1105
1106    #[must_use]
1107    pub fn desc_path(&self) -> &Path {
1108        &self.desc_path
1109    }
1110
1111    #[must_use]
1112    pub fn destination(&self) -> &Path {
1113        &self.destination
1114    }
1115
1116    #[must_use]
1117    pub fn snapshot(&self) -> Option<&JournalSnapshot> {
1118        self.snapshot.as_ref()
1119    }
1120
1121    /// Returns the actual relative path where `source_rel` was materialized on disk,
1122    /// checking uncommitted records first and then any loaded journal snapshot.
1123    #[must_use]
1124    pub fn materialized_path_for(&self, source_rel: &Path) -> Option<PathBuf> {
1125        for entity in self.uncommitted_entities.iter().rev() {
1126            if entity.metadata.source_relative_path().as_deref()
1127                == Some(source_rel)
1128            {
1129                return entity
1130                    .metadata
1131                    .materialized_relative_path()
1132                    .or_else(|| entity.identity.relative_path.clone());
1133            }
1134            if entity.identity.relative_path.as_deref() == Some(source_rel) {
1135                return entity
1136                    .metadata
1137                    .materialized_relative_path()
1138                    .or_else(|| entity.identity.relative_path.clone());
1139            }
1140        }
1141        self.snapshot
1142            .as_ref()
1143            .and_then(|snap| snap.materialized_path_for(source_rel))
1144    }
1145}
1146
1147/// Resolves a manifest path or directory into a `.cscjournal` file path.
1148pub fn resolve_journal_path(path: &Path) -> Result<PathBuf> {
1149    if path.is_file() {
1150        if path.extension().and_then(|e| e.to_str()) == Some("cscdesc") {
1151            return Ok(path.with_extension("cscjournal"));
1152        }
1153        return Ok(path.to_path_buf());
1154    }
1155
1156    if path.is_dir() {
1157        let mut candidates = Vec::new();
1158        for entry in ctb_io::file::read_dir_raw(path)? {
1159            let entry = entry?;
1160            let p = entry.path();
1161            let ext = p.extension().and_then(|e| e.to_str());
1162            if ext == Some("cscjournal") || ext == Some("cscarchive") {
1163                if let Ok(meta) = p.metadata() {
1164                    // Reason for fallback: filesystems lacking mtime support default to UNIX_EPOCH so missing timestamps sort oldest
1165                    let mtime = meta.modified().unwrap_or(UNIX_EPOCH);
1166                    candidates.push((mtime, p));
1167                }
1168            }
1169        }
1170        candidates.sort_by(|a, b| b.0.cmp(&a.0));
1171        if let Some((_, newest)) = candidates.into_iter().next() {
1172            return Ok(newest);
1173        }
1174    }
1175
1176    anyhow::bail!(
1177        "Could not find valid .cscjournal or .cscarchive file from path: {}",
1178        path.display()
1179    )
1180}
1181
1182/// Reads a state journal in strict mode, rolling back to the last valid batch or record.
1183pub fn read_journal_snapshot(path: &Path) -> Result<JournalSnapshot> {
1184    read_journal_snapshot_with_policy(
1185        path,
1186        &ctb_formats_dcstring::DcProjectionPolicy::strict(),
1187    )
1188}
1189
1190/// Reads a state journal using the specified [`ctb_formats_dcstring::DcProjectionPolicy`],
1191/// rolling back to the last valid batch or record on crash truncation.
1192pub fn read_journal_snapshot_with_policy(
1193    path: &Path,
1194    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1195) -> Result<JournalSnapshot> {
1196    let journal_path = resolve_journal_path(path)?;
1197    let mut file = File::open(&journal_path).with_context(|| {
1198        format!("Failed to open journal file: {}", journal_path.display())
1199    })?;
1200
1201    let mut magic = [0_u8; 8];
1202    file.read_exact(&mut magic)
1203        .context("Incomplete journal magic")?;
1204
1205    let desc_path = journal_path.with_extension("cscdesc");
1206    let (noatime_used, applied_directories, move_sources) = if desc_path
1207        .exists()
1208    {
1209        if let Ok(desc_content) = std::fs::read_to_string(&desc_path) {
1210            let noatime = desc_content
1211                .lines()
1212                .any(|l| l.trim() == "NoatimeUsed: true");
1213            let mut dirs = HashMap::new();
1214            let mut move_srcs = HashMap::new();
1215            let mut in_applied = false;
1216            let mut in_move_sources = false;
1217            for line in desc_content.lines() {
1218                let trimmed = line.trim();
1219                if trimmed == "AppliedDirectories:" {
1220                    in_applied = true;
1221                    in_move_sources = false;
1222                    continue;
1223                }
1224                if trimmed == "MoveSources:" {
1225                    in_move_sources = true;
1226                    in_applied = false;
1227                    continue;
1228                }
1229                if in_applied {
1230                    if let Some(entry) = trimmed.strip_prefix("- ") {
1231                        if let Ok(receipt) = serde_json::from_str::<
1232                            AppliedDirectoryReceipt,
1233                        >(entry)
1234                        {
1235                            dirs.insert(receipt.relative, receipt.identity);
1236                        }
1237                    } else if !trimmed.is_empty() && !line.starts_with("  ") {
1238                        in_applied = false;
1239                    }
1240                } else if in_move_sources {
1241                    if let Some(entry) = trimmed.strip_prefix("- ") {
1242                        if let Ok(record) =
1243                            serde_json::from_str::<MoveSourceRecord>(entry)
1244                        {
1245                            move_srcs
1246                                .insert(record.source_path.clone(), record);
1247                        }
1248                    } else if !trimmed.is_empty() && !line.starts_with("  ") {
1249                        in_move_sources = false;
1250                    }
1251                }
1252            }
1253            (noatime, dirs, move_srcs)
1254        } else {
1255            (false, HashMap::new(), HashMap::new())
1256        }
1257    } else {
1258        (false, HashMap::new(), HashMap::new())
1259    };
1260
1261    let mut snapshot = match &magic {
1262        m if m == JOURNAL_MAGIC_V5
1263            || m == JOURNAL_MAGIC_V4
1264            || m == JOURNAL_MAGIC_V1
1265            || m == ARCHIVE_MAGIC_V2
1266            || m == ARCHIVE_MAGIC_V1 =>
1267        {
1268            read_v4_journal_snapshot(
1269                &mut file,
1270                &journal_path,
1271                noatime_used,
1272                policy,
1273            )?
1274        }
1275        _ => {
1276            anyhow::bail!(
1277                "Invalid or unrecognized journal magic in {}",
1278                journal_path.display()
1279            );
1280        }
1281    };
1282    snapshot.applied_directories = applied_directories;
1283    snapshot.move_sources = move_sources;
1284    Ok(snapshot)
1285}
1286
1287fn warn_unexpected_stream_bodies(
1288    entity: &FileEntity,
1289    warnings: &mut Vec<JournalWarningRecord>,
1290) {
1291    let mut pending = vec![entity];
1292    while let Some(current) = pending.pop() {
1293        for stream in &current.streams {
1294            if stream.data.is_some() || stream.payload.is_some() {
1295                let msg = format!(
1296                    "Journal snapshot for {:?} contains unexpected embedded stream body: {:?}",
1297                    entity.identity.relative_path,
1298                    stream.to_string_lossy()
1299                );
1300                warn_fmt!("{msg}");
1301                warnings.push(JournalWarningRecord {
1302                    code: "unexpected-journal-stream-body".into(),
1303                    message: msg,
1304                    timestamp_sec: 0,
1305                });
1306            }
1307            pending.push(&stream.entity);
1308        }
1309    }
1310}
1311
1312/// Converts any in-memory cscjournal bytes (legacy or v4+) to a `DcMstring` document.
1313///
1314/// Legacy journal versions (revisions 1..=3) are converted to the current Dc format,
1315/// and then the 8 leading magic bytes are removed from the beginning of the converted data,
1316/// yielding a native `DcMixed` document.
1317pub fn convert_cscjournal_to_dcmstring(
1318    bytes: &[u8],
1319) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1320    convert_cscjournal_to_dcmstring_with_policy(
1321        bytes,
1322        &ctb_formats_dcstring::DcProjectionPolicy::strict(),
1323    )
1324}
1325
1326/// Converts journal bytes, using `policy` when projecting legacy Dc identities.
1327pub fn convert_cscjournal_to_dcmstring_with_policy(
1328    bytes: &[u8],
1329    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1330) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1331    convert_cscjournal_to_dcmstring_with_options(
1332        bytes,
1333        policy,
1334        !policy.is_strict(),
1335    )
1336}
1337
1338/// Converts journal bytes using `policy` for legacy Dc identity projection and
1339/// `best_effort` for permissive header/payload recovery.
1340pub fn convert_cscjournal_to_dcmstring_with_options(
1341    bytes: &[u8],
1342    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1343    best_effort: bool,
1344) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1345    let opts = ctb_formats_dcstring::DcmmStreamOptions { best_effort };
1346    if bytes.len() < 8 {
1347        if !best_effort {
1348            anyhow::bail!("CscJournal data is too short (< 8 bytes)");
1349        }
1350        let (doc, mut log) =
1351            ctb_formats_dcstring::dc_mixed::dcmm_to_dcmstring_with_options(
1352                bytes, &opts,
1353            )?;
1354        log.warn("CscJournal data is too short (< 8 bytes); decoded in permissive mode");
1355        return Ok((doc, log));
1356    }
1357    let magic = bytes
1358        .get(..8)
1359        .context("Slice bounds invalid for journal magic")?;
1360
1361    let is_v4_or_newer = magic == JOURNAL_MAGIC_V5
1362        || magic == JOURNAL_MAGIC_V4
1363        || (magic.starts_with(b"CTBCSCJ")
1364            && magic.get(7).is_some_and(|&v| v >= 4))
1365        || magic == ARCHIVE_MAGIC_V2
1366        || magic == ARCHIVE_MAGIC_V1;
1367
1368    let dcmm_bytes = if is_v4_or_newer {
1369        bytes
1370            .get(8..)
1371            .context("Slice bounds invalid for journal payload")?
1372    } else {
1373        let is_legacy = magic == JOURNAL_MAGIC_V1
1374            || (magic.starts_with(b"CTBCSCJ")
1375                && magic.get(7).is_some_and(|&v| v < 4));
1376        if !is_legacy {
1377            if !best_effort {
1378                anyhow::bail!(
1379                    "Invalid or unrecognized cscjournal magic bytes: {magic:?}"
1380                );
1381            }
1382            let (doc, mut log) =
1383                ctb_formats_dcstring::dc_mixed::dcmm_to_dcmstring_with_options(
1384                    bytes, &opts,
1385                )?;
1386            log.warn(&format!(
1387                "Unrecognized cscjournal magic bytes {magic:?}; decoded in permissive mode"
1388            ));
1389            return Ok((doc, log));
1390        }
1391        let converted_bytes =
1392            legacy::convert_legacy_journal_bytes_with_policy(bytes, policy)?;
1393        return ctb_formats_dcstring::dc_mixed::dcmm_to_dcmstring_with_options(
1394            converted_bytes.get(8..).context(
1395                "Slice bounds invalid for converted journal payload",
1396            )?,
1397            &opts,
1398        );
1399    };
1400
1401    ctb_formats_dcstring::dc_mixed::dcmm_to_dcmstring_with_options(
1402        dcmm_bytes, &opts,
1403    )
1404}
1405
1406/// Converts in-memory cscarchive bytes (v1 or v2) to a `DcMstring` document.
1407pub fn convert_cscarchive_to_dcmstring_with_policy(
1408    bytes: &[u8],
1409    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1410) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1411    let best_effort = !policy.is_strict();
1412    let opts = ctb_formats_dcstring::DcmmStreamOptions { best_effort };
1413    if let Some(payload) = bytes.strip_prefix(ARCHIVE_MAGIC_V2) {
1414        return ctb_formats_dcstring::dc_mixed::dcmm2_to_dcmstring_with_options(
1415            payload, &opts,
1416        );
1417    }
1418    if let Some(payload) = bytes.strip_prefix(ARCHIVE_MAGIC_V1) {
1419        return ctb_formats_dcstring::dc_mixed::dcmm1_to_dcmstring_with_options(
1420            payload, &opts,
1421        );
1422    }
1423    if !best_effort {
1424        anyhow::bail!(
1425            "Input bytes do not start with valid CTBCSCA\\x01 or CTBCSCA\\x02 magic header"
1426        );
1427    }
1428    let (doc, mut log) =
1429        ctb_formats_dcstring::dc_mixed::dcmm_to_dcmstring_with_options(
1430            bytes, &opts,
1431        )?;
1432    log.warn("Missing or invalid CTBCSCA magic header; decoded payload in permissive mode");
1433    Ok((doc, log))
1434}
1435
1436/// Converts in-memory cscarchive v1 (`CTBCSCA\x01` + `DcMixed1`) bytes to a `DcMstring` document.
1437pub fn convert_cscarchive1_to_dcmstring_with_policy(
1438    bytes: &[u8],
1439    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1440) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1441    let best_effort = !policy.is_strict();
1442    let opts = ctb_formats_dcstring::DcmmStreamOptions { best_effort };
1443    if let Some(payload) = bytes.strip_prefix(ARCHIVE_MAGIC_V1) {
1444        return ctb_formats_dcstring::dc_mixed::dcmm1_to_dcmstring_with_options(
1445            payload, &opts,
1446        );
1447    }
1448    if !best_effort {
1449        anyhow::bail!(
1450            "Input bytes do not start with valid CTBCSCA\\x01 magic header"
1451        );
1452    }
1453    // Reason for fallback: in permissive mode, if the input has a v2 archive magic header instead of v1, strip it; otherwise decode the raw bytes as payload.
1454    let payload = bytes.strip_prefix(ARCHIVE_MAGIC_V2).unwrap_or(bytes);
1455    let (doc, mut log) =
1456        ctb_formats_dcstring::dc_mixed::dcmm1_to_dcmstring_with_options(
1457            payload, &opts,
1458        )?;
1459    log.warn("Missing or mismatched CTBCSCA\\x01 magic header; decoded payload in permissive mode");
1460    Ok((doc, log))
1461}
1462
1463/// Converts in-memory cscarchive v2 (`CTBCSCA\x02` + `DcMixed2`) bytes to a `DcMstring` document.
1464pub fn convert_cscarchive2_to_dcmstring_with_policy(
1465    bytes: &[u8],
1466    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1467) -> Result<(DcMstring, ctb_formats_utilities::FormatLog)> {
1468    let best_effort = !policy.is_strict();
1469    let opts = ctb_formats_dcstring::DcmmStreamOptions { best_effort };
1470    if let Some(payload) = bytes.strip_prefix(ARCHIVE_MAGIC_V2) {
1471        return ctb_formats_dcstring::dc_mixed::dcmm2_to_dcmstring_with_options(
1472            payload, &opts,
1473        );
1474    }
1475    if !best_effort {
1476        anyhow::bail!(
1477            "Input bytes do not start with valid CTBCSCA\\x02 magic header"
1478        );
1479    }
1480    // Reason for fallback: in permissive mode, if the input has a v1 archive magic header instead of v2, strip it; otherwise decode the raw bytes as payload.
1481    let payload = bytes.strip_prefix(ARCHIVE_MAGIC_V1).unwrap_or(bytes);
1482    let (doc, mut log) =
1483        ctb_formats_dcstring::dc_mixed::dcmm2_to_dcmstring_with_options(
1484            payload, &opts,
1485        )?;
1486    log.warn("Missing or mismatched CTBCSCA\\x02 magic header; decoded payload in permissive mode");
1487    Ok((doc, log))
1488}
1489
1490/// Encodes a `DcMstring` into `CscJournal5` (`CTBCSCJ\x05` + `DcMixed2`) bytes.
1491pub fn dcmstring_to_cscjournal(
1492    doc: &DcMstring,
1493) -> Result<(Vec<u8>, ctb_formats_utilities::FormatLog)> {
1494    let mut out =
1495        Vec::with_capacity(JOURNAL_MAGIC_V5.len().saturating_add(doc.len()));
1496    out.extend_from_slice(JOURNAL_MAGIC_V5);
1497    out.extend_from_slice(doc.as_bytes());
1498    Ok((out, ctb_formats_utilities::FormatLog::default()))
1499}
1500
1501/// Encodes a `DcMstring` into `CscArchive2` (`CTBCSCA\x02` + `DcMixed2`) bytes.
1502pub fn dcmstring_to_cscarchive(
1503    doc: &DcMstring,
1504) -> Result<(Vec<u8>, ctb_formats_utilities::FormatLog)> {
1505    dcmstring_to_cscarchive2(doc)
1506}
1507
1508/// Encodes a `DcMstring` into `CscArchive1` (`CTBCSCA\x01` + `DcMixed1`) bytes.
1509pub fn dcmstring_to_cscarchive1(
1510    doc: &DcMstring,
1511) -> Result<(Vec<u8>, ctb_formats_utilities::FormatLog)> {
1512    let (dcmm1, log) = ctb_formats_dcstring::dc_mixed::dcmstring_to_dcmm1(doc)?;
1513    let mut out =
1514        Vec::with_capacity(ARCHIVE_MAGIC_V1.len().saturating_add(dcmm1.len()));
1515    out.extend_from_slice(ARCHIVE_MAGIC_V1);
1516    out.extend_from_slice(&dcmm1);
1517    Ok((out, log))
1518}
1519
1520/// Encodes a `DcMstring` into `CscArchive2` (`CTBCSCA\x02` + `DcMixed2`) bytes.
1521pub fn dcmstring_to_cscarchive2(
1522    doc: &DcMstring,
1523) -> Result<(Vec<u8>, ctb_formats_utilities::FormatLog)> {
1524    let mut out =
1525        Vec::with_capacity(ARCHIVE_MAGIC_V2.len().saturating_add(doc.len()));
1526    out.extend_from_slice(ARCHIVE_MAGIC_V2);
1527    out.extend_from_slice(doc.as_bytes());
1528    Ok((out, ctb_formats_utilities::FormatLog::default()))
1529}
1530
1531/// Converts in-memory cscjournal bytes to current `DcMixed` journal bytes (`CSCJRNL5`),
1532/// or returns version 4+ journal bytes unmodified.
1533pub fn convert_cscjournal_to_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
1534    convert_cscjournal_to_bytes_with_policy(
1535        bytes,
1536        &ctb_formats_dcstring::DcProjectionPolicy::strict(),
1537    )
1538}
1539
1540/// Converts journal bytes, using `policy` when projecting legacy Dc identities.
1541pub fn convert_cscjournal_to_bytes_with_policy(
1542    bytes: &[u8],
1543    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1544) -> Result<Vec<u8>> {
1545    anyhow::ensure!(
1546        bytes.len() >= 8,
1547        "CscJournal data is too short (< 8 bytes)"
1548    );
1549    let magic = bytes
1550        .get(..8)
1551        .context("Slice bounds invalid for journal magic")?;
1552    if magic == JOURNAL_MAGIC_V5
1553        || magic == JOURNAL_MAGIC_V4
1554        || (magic.starts_with(b"CTBCSCJ")
1555            && magic.get(7).is_some_and(|&v| v >= 4))
1556        || magic == ARCHIVE_MAGIC_V2
1557        || magic == ARCHIVE_MAGIC_V1
1558    {
1559        Ok(bytes.to_vec())
1560    } else if magic == JOURNAL_MAGIC_V1
1561        || (magic.starts_with(b"CTBCSCJ")
1562            && magic.get(7).is_some_and(|&v| v < 4))
1563    {
1564        legacy::convert_legacy_journal_bytes_with_policy(bytes, policy)
1565    } else {
1566        anyhow::bail!(
1567            "Invalid or unrecognized cscjournal magic bytes: {magic:?}"
1568        );
1569    }
1570}
1571
1572/// Reads a v4 native `DcMixed` state journal using [`ctb_formats_dcstring::DcDocumentNavigator`]
1573/// without buffering file bodies. Member metadata is retained for projection.
1574pub fn read_v4_journal_snapshot(
1575    file: &mut File,
1576    journal_path: &Path,
1577    noatime_used: bool,
1578    policy: &ctb_formats_dcstring::DcProjectionPolicy,
1579) -> Result<JournalSnapshot> {
1580    let mut nav_file = file.try_clone().with_context(|| {
1581        format!("Failed to clone file handle for {}", journal_path.display())
1582    })?;
1583    nav_file.seek(SeekFrom::Start(0))?;
1584    let mut magic = [0_u8; 8];
1585    nav_file.read_exact(&mut magic)?;
1586    let is_archive = &magic == ARCHIVE_MAGIC_V2 || &magic == ARCHIVE_MAGIC_V1;
1587
1588    let scanned =
1589        JournalReader::read(nav_file, scanner::ReadMode::Recover, policy)
1590            .with_context(|| {
1591                format!("Invalid DcMixed journal in {}", journal_path.display())
1592            })?;
1593    let origin_platform =
1594        if let Ok(platform) = u8::try_from(scanned.session.origin_platform) {
1595            platform
1596        } else {
1597            anyhow::ensure!(
1598                !policy.is_strict(),
1599                "Invalid origin platform code in session header"
1600            );
1601            current_platform()
1602        };
1603    let mut committed_entities = HashMap::new();
1604    let mut warnings = scanned.warnings;
1605    for member in scanned.members {
1606        if !is_archive && member.payload.is_some() {
1607            let msg = format!(
1608                "Journal snapshot for {:?} contains unexpected embedded file body",
1609                member.entity.identity.relative_path
1610            );
1611            warn_fmt!("{msg}");
1612            warnings.push(JournalWarningRecord {
1613                code: "unexpected-journal-file-body".into(),
1614                message: msg,
1615                timestamp_sec: 0,
1616            });
1617        }
1618        let mut entity = member.entity;
1619        if is_archive {
1620            entity.strip_stream_bodies();
1621        } else {
1622            warn_unexpected_stream_bodies(&entity, &mut warnings);
1623        }
1624        let path_key = match entity.identity.path_bytes() {
1625            Some(bytes) => bytes.to_vec(),
1626            None => Vec::new(),
1627        };
1628        if let Some(source_rel) = entity.metadata.source_relative_path() {
1629            let source_bytes = source_rel.as_os_str().as_encoded_bytes();
1630            if source_bytes != path_key.as_slice() {
1631                committed_entities.remove(source_bytes);
1632            }
1633        }
1634        committed_entities.insert(path_key, entity);
1635    }
1636    Ok(JournalSnapshot {
1637        sources: scanned.session.sources,
1638        destination: scanned.session.destination,
1639        origin_platform,
1640        committed_entities,
1641        is_completed: scanned.completed,
1642        last_batch_id: scanned.sequence,
1643        valid_length: scanned.valid_length,
1644        noatime_used,
1645        environment: scanned.session.environment,
1646        errors: scanned.errors,
1647        warnings,
1648        applied_directories: HashMap::new(),
1649        move_sources: HashMap::new(),
1650    })
1651}
1652
1653fn attach_legacy_session_environment(
1654    entity: &mut FileEntity,
1655    env: &Arc<EnvDescription>,
1656) {
1657    if entity.metadata.environment.is_none()
1658        || entity
1659            .metadata
1660            .environment
1661            .as_ref()
1662            .is_some_and(|existing| existing == env)
1663    {
1664        entity.metadata.environment = Some(Arc::clone(env));
1665    }
1666    for stream in &mut entity.streams {
1667        attach_legacy_session_environment(&mut stream.entity, env);
1668    }
1669}
1670
1671#[cfg(test)]
1672pub(crate) fn find_cscjournal(state_dir: &Path) -> PathBuf {
1673    for entry in std::fs::read_dir(state_dir).expect("read state dir") {
1674        let entry = entry.expect("entry");
1675        if entry.path().extension().and_then(|e| e.to_str())
1676            == Some("cscjournal")
1677        {
1678            return entry.path();
1679        }
1680    }
1681    panic!("No .cscjournal found in {}", state_dir.display());
1682}
1683
1684#[cfg(test)]
1685#[allow(
1686    clippy::panic,
1687    clippy::expect_used,
1688    clippy::unwrap_used,
1689    clippy::unwrap_in_result,
1690    clippy::panic_in_result_fn,
1691    clippy::indexing_slicing,
1692    clippy::arithmetic_side_effects,
1693    reason = "Standard repository test boilerplate"
1694)]
1695mod tests {
1696    use super::*;
1697    use crate::args::default_test_args;
1698    use crate::cli::run_csc;
1699    use crate::journal::find_cscjournal;
1700    use crate::journal::legacy::{
1701        read_bytes, read_u32, write_bytes, write_u32,
1702    };
1703    use std::fs;
1704    use std::path::PathBuf;
1705    use tempfile::tempdir;
1706
1707    #[cfg(unix)]
1708    #[crate::ctb_test]
1709    fn journal_failed_commit_preserves_counters_queue_and_refuses_retry()
1710    -> Result<()> {
1711        for fault in ["encoding", "write", "flush", "sync"] {
1712            let temporary = tempdir()?;
1713            let journal = temporary.path().join("copy.cscjournal");
1714            let description = temporary.path().join("copy.cscdesc");
1715            let mut writer = StateJournal::create_at_path(
1716                &journal,
1717                &description,
1718                &[],
1719                temporary.path(),
1720            )?;
1721            let entity = FileEntity::from_vec(b"payload".to_vec());
1722            writer.record_entity(&entity);
1723            writer.commit_batch()?;
1724            writer.record_entity(&entity);
1725            let mut second = entity.clone();
1726            if fault == "encoding" {
1727                second.metadata.read_time = Some(
1728                    UNIX_EPOCH
1729                        .checked_sub(std::time::Duration::from_secs(1))
1730                        .context("Test time underflow")?,
1731                );
1732            }
1733            writer.record_entity(&second);
1734            let mut _sync_pipe_reader = None;
1735            match fault {
1736                "write" => {
1737                    let output = File::open(&journal)?;
1738                    writer.writer = writer
1739                        .writer
1740                        .map_output(|_| BufWriter::with_capacity(0, output));
1741                }
1742                "flush" => {
1743                    let output = File::open(&journal)?;
1744                    writer.writer =
1745                        writer.writer.map_output(|_| BufWriter::new(output));
1746                }
1747                "sync" => {
1748                    let (reader_pipe, writer_pipe) = std::io::pipe()?;
1749                    _sync_pipe_reader = Some(reader_pipe);
1750                    let output =
1751                        File::from(std::os::fd::OwnedFd::from(writer_pipe));
1752                    writer.writer =
1753                        writer.writer.map_output(|_| BufWriter::new(output));
1754                }
1755                _ => {}
1756            }
1757            let description_before = fs::read(&description)?;
1758            ensure!(writer.commit_batch().is_err(), "Accepted {fault} failure");
1759            ensure!(
1760                writer.current_batch_id == 1
1761                    && writer.total_committed_files == 1
1762                    && writer.total_committed_bytes == 7
1763            );
1764            ensure!(writer.uncommitted_entities == vec![entity, second]);
1765            ensure!(writer.writer.is_failed());
1766            let bytes_after_failure = fs::read(&journal)?;
1767            ensure!(writer.commit_batch().is_err());
1768            ensure!(writer.mark_completed().is_err());
1769            ensure!(writer.record_warning("late", "must fail").is_err());
1770            ensure!(writer.mark_failed("failed commit").is_err());
1771            ensure!(
1772                writer.current_batch_id == 1
1773                    && writer.total_committed_files == 1
1774                    && writer.total_committed_bytes == 7
1775            );
1776            ensure!(writer.uncommitted_entities.len() == 2);
1777            ensure!(
1778                fs::read(&journal)? == bytes_after_failure
1779                    && fs::read(&description)? == description_before
1780            );
1781        }
1782        Ok(())
1783    }
1784
1785    #[crate::ctb_test]
1786    fn journal_descriptor_failure_requires_metadata_only_repair() -> Result<()>
1787    {
1788        for operation in ["batch", "completion", "warning", "error", "failure"]
1789        {
1790            let temporary = tempdir()?;
1791            let journal = temporary.path().join("copy.cscjournal");
1792            let description = temporary.path().join("copy.cscdesc");
1793            let mut writer = StateJournal::create_at_path(
1794                &journal,
1795                &description,
1796                &[],
1797                Path::new(""),
1798            )?;
1799            let mut entity = FileEntity::from_vec(b"payload".to_vec());
1800            entity.identity.relative_path = Some("payload".into());
1801            writer.record_entity(&entity);
1802            writer.commit_batch()?;
1803            let error = JournalErrorRecord::from_error(
1804                temporary.path(),
1805                JournalErrorStage::PayloadRead,
1806                &anyhow::anyhow!("injected"),
1807            );
1808            if operation == "completion" {
1809                writer.record_error(&error)?;
1810            }
1811            fs::remove_file(&description)?;
1812            fs::create_dir(&description)?;
1813            let result = match operation {
1814                "batch" => {
1815                    entity.identity.relative_path = Some("second".into());
1816                    writer.record_entity(&entity);
1817                    writer.commit_batch()
1818                }
1819                "completion" => writer.mark_completed(),
1820                "warning" => writer.record_warning("injected", "warning"),
1821                "error" => writer.record_error(&error),
1822                _ => writer.mark_failed("injected"),
1823            };
1824            ensure!(
1825                format!(
1826                    "{:#}",
1827                    result.expect_err("Descriptor failure must propagate")
1828                )
1829                .contains("operation is durable")
1830            );
1831            let status = writer
1832                .pending_descriptor_status()
1833                .context("Missing pending descriptor")?
1834                .to_owned();
1835            ensure!(
1836                status
1837                    == match operation {
1838                        "completion" => "Completed with 1 error(s)",
1839                        "failure" => "Failed: injected",
1840                        _ => "InProgress",
1841                    }
1842            );
1843            let bytes = fs::read(&journal)?;
1844            let counters = (
1845                writer.current_batch_id,
1846                writer.total_committed_files,
1847                writer.total_committed_bytes,
1848            );
1849            ensure!(writer.uncommitted_entities.is_empty());
1850            ensure!(!writer.writer.is_failed());
1851            ensure!(writer.retry_descriptor().is_err());
1852            ensure!(writer.commit_batch().is_err());
1853            ensure!(writer.mark_completed().is_err());
1854            ensure!(writer.record_warning("blocked", "blocked").is_err());
1855            ensure!(writer.record_error(&error).is_err());
1856            ensure!(writer.mark_failed("blocked").is_err());
1857            ensure!(
1858                writer.pending_descriptor_status() == Some(status.as_str())
1859            );
1860            ensure!(fs::read(&journal)? == bytes);
1861            fs::remove_dir(&description)?;
1862            writer.retry_descriptor()?;
1863            ensure!(writer.pending_descriptor_status().is_none());
1864            ensure!(fs::read(&journal)? == bytes);
1865            ensure!(
1866                (
1867                    writer.current_batch_id,
1868                    writer.total_committed_files,
1869                    writer.total_committed_bytes
1870                ) == counters
1871            );
1872            let descriptor = fs::read_to_string(&description)?;
1873            ensure!(descriptor.contains(&format!("Status: {status}\n")));
1874            ensure!(descriptor.contains(&format!(
1875                "FilesCommitted: {}\nBytesCommitted: {}\n",
1876                counters.1, counters.2
1877            )));
1878            ensure!(descriptor.contains(&format!(
1879                "ErrorsCount: {}\n",
1880                writer.errors().len()
1881            )));
1882            ensure!(descriptor.contains(&format!(
1883                "WarningsCount: {}\n",
1884                writer.warnings().len()
1885            )));
1886            ensure!(writer.retry_descriptor().is_err());
1887            if operation == "completion" {
1888                ensure!(writer.mark_completed().is_err());
1889                ensure!(writer.record_warning("late", "late").is_err());
1890                ensure!(fs::read(&journal)? == bytes);
1891            } else {
1892                writer.mark_completed()?;
1893            }
1894            let snapshot = read_journal_snapshot(&journal)?;
1895            ensure!(
1896                snapshot.is_completed && snapshot.last_batch_id == counters.0
1897            );
1898        }
1899        Ok(())
1900    }
1901
1902    #[crate::ctb_test]
1903    fn journal_resume_preserves_completed_diagnostics_and_prefix() -> Result<()>
1904    {
1905        let temporary = tempdir()?;
1906        let journal = temporary.path().join("copy.cscjournal");
1907        let description = temporary.path().join("copy.cscdesc");
1908        let mut writer = StateJournal::create_at_path(
1909            &journal,
1910            &description,
1911            &[],
1912            Path::new(""),
1913        )?;
1914        let mut entity = FileEntity::from_vec(b"original".to_vec());
1915        entity.identity.relative_path = Some("original".into());
1916        writer.record_entity(&entity);
1917        writer.mark_completed()?;
1918        drop(writer);
1919        let warning = JournalWarningRecord {
1920            code: "historical".into(),
1921            message: "warning".into(),
1922            timestamp_sec: 1,
1923        };
1924        let error = JournalErrorRecord::from_error(
1925            temporary.path(),
1926            JournalErrorStage::PayloadRead,
1927            &anyhow::anyhow!("historical"),
1928        );
1929        let mut output = OpenOptions::new().append(true).open(&journal)?;
1930        let mut diagnostics = DcMstring::new();
1931        JournalWarningRecordPayload::from_record(&warning)
1932            .encode_dc_mixed(&mut diagnostics)?;
1933        JournalErrorRecordPayload::from_record(&error)?
1934            .encode_dc_mixed(&mut diagnostics)?;
1935        output.write_all(diagnostics.payload_bytes())?;
1936        output.sync_all()?;
1937        drop(output);
1938        let prefix = fs::read(&journal)?;
1939        let snapshot = read_journal_snapshot(&journal)?;
1940        ensure!(
1941            snapshot.is_completed
1942                && snapshot.valid_length == u64::try_from(prefix.len())?
1943        );
1944        let mut resumed =
1945            StateJournal::open_for_resume(&journal, &description, &snapshot)?;
1946        ensure!(fs::read(&journal)? == prefix);
1947        entity.identity.relative_path = Some("resumed".into());
1948        resumed.record_entity(&entity);
1949        resumed.commit_batch()?;
1950        let snapshot = read_journal_snapshot(&journal)?;
1951        ensure!(!snapshot.is_completed && snapshot.last_batch_id == 2);
1952        ensure!(
1953            snapshot.is_committed(b"original")
1954                && snapshot.is_committed(b"resumed")
1955        );
1956        ensure!(
1957            snapshot.warnings.len() == 1
1958                && snapshot.warnings.first() == Some(&warning)
1959        );
1960        ensure!(
1961            snapshot.errors.len() == 1
1962                && snapshot.errors.first() == Some(&error)
1963        );
1964        resumed.mark_completed()?;
1965        ensure!(fs::read(&journal)?.starts_with(&prefix));
1966        let snapshot = read_journal_snapshot(&journal)?;
1967        ensure!(
1968            snapshot.is_completed
1969                && snapshot.errors.len() == 1
1970                && snapshot.warnings.len() == 1
1971        );
1972        Ok(())
1973    }
1974
1975    #[crate::ctb_test]
1976    fn journal_completion_refuses_reuse_and_explicit_resume_reopens()
1977    -> Result<()> {
1978        let temporary = tempdir()?;
1979        let journal = temporary.path().join("copy.cscjournal");
1980        let description = temporary.path().join("copy.cscdesc");
1981        let mut writer = StateJournal::create_at_path(
1982            &journal,
1983            &description,
1984            &[],
1985            temporary.path(),
1986        )?;
1987        writer.mark_completed()?;
1988        let completed = fs::read(&journal)?;
1989        ensure!(writer.mark_completed().is_err());
1990        ensure!(writer.record_warning("late", "must fail").is_err());
1991        let error = JournalErrorRecord::from_error(
1992            temporary.path(),
1993            JournalErrorStage::PayloadRead,
1994            &anyhow::anyhow!("late"),
1995        );
1996        ensure!(writer.record_error(&error).is_err());
1997        let mut entity = FileEntity::from_vec(b"resumed".to_vec());
1998        entity.identity.relative_path = Some("resumed".into());
1999        writer.record_entity(&entity);
2000        ensure!(
2001            writer.commit_batch().is_err() && writer.mark_completed().is_err()
2002        );
2003        ensure!(
2004            writer.uncommitted_entities.len() == 1
2005                && writer.current_batch_id == 0
2006        );
2007        ensure!(fs::read(&journal)? == completed);
2008        drop(writer);
2009        let snapshot = read_journal_snapshot(&journal)?;
2010        ensure!(snapshot.is_completed);
2011        let mut resumed =
2012            StateJournal::open_for_resume(&journal, &description, &snapshot)?;
2013        ensure!(fs::read(&journal)? == completed);
2014        ensure!(read_journal_snapshot(&journal)?.is_completed);
2015        resumed.record_entity(&entity);
2016        resumed.commit_batch()?;
2017        ensure!(!read_journal_snapshot(&journal)?.is_completed);
2018        resumed.mark_completed()?;
2019        ensure!(fs::read(&journal)?.starts_with(&completed));
2020        let snapshot = read_journal_snapshot(&journal)?;
2021        ensure!(
2022            snapshot.is_completed
2023                && snapshot.last_batch_id == 1
2024                && snapshot.is_committed(b"resumed")
2025        );
2026        Ok(())
2027    }
2028
2029    #[crate::ctb_test]
2030    fn diagnostic_mark_failed_propagates_pending_encoding_failure() -> Result<()>
2031    {
2032        let temporary = tempdir()?;
2033        let source = temporary.path().join("source");
2034        let journal = temporary.path().join("copy.cscjournal");
2035        let description = temporary.path().join("copy.cscdesc");
2036        fs::write(&source, b"payload")?;
2037        let mut entity = FileEntity::from_filesystem(&source, None)?;
2038        entity
2039            .metadata
2040            .timestamps
2041            .as_mut()
2042            .context("Missing captured timestamps")?
2043            .mtime_nsec = 1_000_000_000;
2044        let mut writer = StateJournal::create_at_path(
2045            &journal,
2046            &description,
2047            std::slice::from_ref(&source),
2048            temporary.path(),
2049        )?;
2050        let before = fs::read(&description)?;
2051        writer.record_entity(&entity);
2052        let error = writer
2053            .mark_failed("Injected operation failure")
2054            .expect_err("Invalid pending record must fail");
2055        ensure!(
2056            format!("{error:#}").contains("Invalid file timestamp nanoseconds")
2057        );
2058        ensure!(writer.uncommitted_entities.len() == 1);
2059        ensure!(
2060            fs::read(&description)? == before,
2061            "Failed commit rewrote the descriptor as persisted status"
2062        );
2063        Ok(())
2064    }
2065
2066    #[crate::ctb_test]
2067    fn diagnostic_error_conversion() -> Result<()> {
2068        let policy = ctb_formats_dcstring::DcProjectionPolicy::strict();
2069        for stage in [
2070            JournalErrorStage::Traversal,
2071            JournalErrorStage::MetadataRead,
2072            JournalErrorStage::PayloadOpen,
2073            JournalErrorStage::PayloadRead,
2074            JournalErrorStage::Materialize,
2075            JournalErrorStage::PostCheck,
2076        ] {
2077            for os_error in
2078                [None, Some(13), Some(-1), Some(i32::MIN), Some(i32::MAX)]
2079            {
2080                for timestamp_sec in [-1, 0, 1] {
2081                    let record = JournalErrorRecord {
2082                        path: PathBuf::from("source"),
2083                        raw_path: b"source".to_vec(),
2084                        stage,
2085                        error_message: "OS error fidelity".to_owned(),
2086                        os_error,
2087                        timestamp_sec,
2088                    };
2089                    let payload =
2090                        JournalErrorRecordPayload::from_record(&record)?;
2091                    assert_eq!(payload.to_record(&policy)?, record);
2092                    let os_code = match os_error {
2093                        Some(code) => {
2094                            u64::from(u32::from_le_bytes(code.to_le_bytes()))
2095                        }
2096                        None => 0,
2097                    };
2098                    let expected = JournalErrorRecordPayload::new(
2099                        record.path.clone(),
2100                        (u64::from(stage.to_code()) << 32) | os_code,
2101                        record.error_message.clone(),
2102                        timestamp_sec,
2103                    );
2104                    let mut actual_bytes = DcMstring::new();
2105                    payload.encode_dc_mixed(&mut actual_bytes)?;
2106                    let mut expected_bytes = DcMstring::new();
2107                    expected.encode_dc_mixed(&mut expected_bytes)?;
2108                    assert_eq!(
2109                        actual_bytes.as_bytes(),
2110                        expected_bytes.as_bytes()
2111                    );
2112                }
2113            }
2114        }
2115        let zero = JournalErrorRecord {
2116            path: PathBuf::from("source"),
2117            raw_path: b"source".to_vec(),
2118            stage: JournalErrorStage::Traversal,
2119            error_message: String::new(),
2120            os_error: Some(0),
2121            timestamp_sec: 0,
2122        };
2123        assert!(JournalErrorRecordPayload::from_record(&zero).is_err());
2124        Ok(())
2125    }
2126
2127    #[crate::ctb_test]
2128    fn diagnostic_status_validation() -> Result<()> {
2129        let strict = ctb_formats_dcstring::DcProjectionPolicy::strict();
2130        let forgiving = ctb_formats_dcstring::DcProjectionPolicy::forgiving();
2131        for stage_code in [6_u64, 255, 256, u64::from(u32::MAX)] {
2132            let payload = JournalErrorRecordPayload::new(
2133                PathBuf::from("source"),
2134                stage_code << 32,
2135                String::new(),
2136                0,
2137            );
2138            assert_eq!(payload.to_record(&strict).is_err(), stage_code > 255);
2139            assert_eq!(
2140                payload.to_record(&forgiving)?.stage,
2141                JournalErrorStage::Traversal
2142            );
2143        }
2144        Ok(())
2145    }
2146
2147    #[crate::ctb_test]
2148    fn diagnostic_warning_conversion() {
2149        for timestamp_sec in [-1, 0, 1] {
2150            let record = JournalWarningRecord {
2151                code: "metadata".to_owned(),
2152                message: "first: second: third".to_owned(),
2153                timestamp_sec,
2154            };
2155            let payload = JournalWarningRecordPayload::from_record(&record);
2156            assert_eq!(payload.message, "metadata: first: second: third");
2157            assert_eq!(payload.to_record(), record);
2158        }
2159        let payload = JournalWarningRecordPayload {
2160            message: "unsplit warning".to_owned(),
2161            timestamp: UNIX_EPOCH,
2162        };
2163        assert_eq!(
2164            payload.to_record(),
2165            JournalWarningRecord {
2166                code: String::new(),
2167                message: payload.message.clone(),
2168                timestamp_sec: 0,
2169            }
2170        );
2171    }
2172
2173    #[crate::ctb_test]
2174    fn diagnostic_timestamp_conversion() -> Result<()> {
2175        for (timestamp, timestamp_sec) in [
2176            (
2177                UNIX_EPOCH.checked_sub(std::time::Duration::from_millis(1)),
2178                -1,
2179            ),
2180            (
2181                UNIX_EPOCH.checked_add(std::time::Duration::from_millis(999)),
2182                0,
2183            ),
2184        ] {
2185            let timestamp = timestamp.context("Test timestamp out of range")?;
2186            let error = JournalErrorRecordPayload {
2187                path: PathBuf::from("source"),
2188                packed_status: 0,
2189                error_message: String::new(),
2190                timestamp,
2191            };
2192            assert_eq!(
2193                error
2194                    .to_record(
2195                        &ctb_formats_dcstring::DcProjectionPolicy::strict()
2196                    )?
2197                    .timestamp_sec,
2198                timestamp_sec
2199            );
2200            let warning = JournalWarningRecordPayload {
2201                message: "code: message".to_owned(),
2202                timestamp,
2203            };
2204            assert_eq!(warning.to_record().timestamp_sec, timestamp_sec);
2205        }
2206        Ok(())
2207    }
2208
2209    #[cfg(unix)]
2210    #[crate::ctb_test]
2211    fn diagnostic_non_utf8_path_conversion() -> Result<()> {
2212        use std::os::unix::ffi::OsStrExt;
2213
2214        let raw_path = b"source/\xff".to_vec();
2215        let record = JournalErrorRecord {
2216            path: PathBuf::from(std::ffi::OsStr::from_bytes(&raw_path)),
2217            raw_path,
2218            stage: JournalErrorStage::PayloadOpen,
2219            error_message: "non-UTF-8 path".to_owned(),
2220            os_error: Some(-1),
2221            timestamp_sec: 0,
2222        };
2223        let payload = JournalErrorRecordPayload::from_record(&record)?;
2224        assert_eq!(
2225            payload.to_record(
2226                &ctb_formats_dcstring::DcProjectionPolicy::strict()
2227            )?,
2228            record
2229        );
2230        let temp = tempdir()?;
2231        let journal_path = temp.path().join("raw-path.cscjournal");
2232        let mut writer = StateJournal::create_at_path(
2233            &journal_path,
2234            &journal_path.with_extension("cscdesc"),
2235            &[temp.path().join("source")],
2236            &temp.path().join("destination"),
2237        )?;
2238        writer.record_error(&record)?;
2239        assert_eq!(read_journal_snapshot(&journal_path)?.errors, vec![record]);
2240        Ok(())
2241    }
2242
2243    #[cfg(unix)]
2244    #[crate::ctb_test]
2245    fn diagnostic_cross_platform_path_conversion() -> Result<()> {
2246        use std::os::unix::ffi::OsStrExt;
2247
2248        let raw_path = b"C:/source/\xed\xa0\x80".to_vec();
2249        let record = JournalErrorRecord {
2250            path: PathBuf::from(std::ffi::OsStr::from_bytes(&raw_path)),
2251            raw_path,
2252            stage: JournalErrorStage::PayloadRead,
2253            error_message: "Windows WTF-8 filename".to_owned(),
2254            os_error: Some(-1),
2255            timestamp_sec: -1,
2256        };
2257        let session = JournalSessionRecord {
2258            sources: vec![PathBuf::from("C:/source")],
2259            destination: PathBuf::from("D:/destination"),
2260            origin_platform: u32::from(PLATFORM_WINDOWS),
2261            environment: None,
2262        };
2263        let mut document = DcMstring::new();
2264        session.encode_dc_mixed(&mut document)?;
2265        JournalErrorRecordPayload::from_record(&record)?
2266            .encode_dc_mixed(&mut document)?;
2267        let (dcmm1_bytes, _) =
2268            ctb_formats_dcstring::dc_mixed::dcmstring_to_dcmm1(&document)?;
2269        for (magic, payload) in [
2270            (JOURNAL_MAGIC_V5, document.as_bytes()),
2271            (JOURNAL_MAGIC_V4, dcmm1_bytes.as_slice()),
2272        ] {
2273            let mut bytes = magic.to_vec();
2274            bytes.extend_from_slice(payload);
2275            let temp = tempdir()?;
2276            let journal_path = temp.path().join("windows-path.cscjournal");
2277            fs::write(&journal_path, bytes)?;
2278            let snapshot = read_journal_snapshot(&journal_path)?;
2279            assert_eq!(snapshot.origin_platform, PLATFORM_WINDOWS);
2280            assert_eq!(snapshot.errors, vec![record.clone()]);
2281        }
2282        Ok(())
2283    }
2284
2285    #[crate::ctb_test]
2286    fn test_journal_signed_os_errors_roundtrip() -> Result<()> {
2287        let temp = tempdir()?;
2288        let journal_path = temp.path().join("signed-errors.cscjournal");
2289        let mut writer = StateJournal::create_at_path(
2290            &journal_path,
2291            &journal_path.with_extension("cscdesc"),
2292            &[temp.path().join("source")],
2293            &temp.path().join("destination"),
2294        )?;
2295        for os_error in
2296            [None, Some(13), Some(-1), Some(i32::MIN), Some(i32::MAX)]
2297        {
2298            let record = JournalErrorRecord {
2299                path: PathBuf::from("source"),
2300                raw_path: b"source".to_vec(),
2301                stage: JournalErrorStage::MetadataRead,
2302                error_message: "OS error fidelity".to_owned(),
2303                os_error,
2304                timestamp_sec: 0,
2305            };
2306            writer.record_error(&record)?;
2307            let snapshot = read_journal_snapshot(&journal_path)?;
2308            assert_eq!(snapshot.errors.last(), Some(&record));
2309        }
2310        let mut zero_record = writer
2311            .errors()
2312            .last()
2313            .context("Missing recorded errors")?
2314            .clone();
2315        zero_record.os_error = Some(0);
2316        assert!(writer.record_error(&zero_record).is_err());
2317        assert_eq!(read_journal_snapshot(&journal_path)?.errors.len(), 5);
2318        Ok(())
2319    }
2320
2321    #[crate::ctb_test]
2322    fn test_journal_rejects_unknown_environment_json() -> Result<()> {
2323        let temp = tempdir()?;
2324        let journal_path = temp.path().join("unknown-environment.cscjournal");
2325        let mut bytes = JOURNAL_MAGIC_V1.to_vec();
2326        bytes.extend_from_slice(&[TAG_SESSION_HEADER, current_platform()]);
2327        write_u32(&mut bytes, 0)?;
2328        write_bytes(&mut bytes, b"")?;
2329        bytes.push(TAG_SESSION_ENV);
2330        write_bytes(&mut bytes, br#"{"os":"linux","future_flag":true}"#)?;
2331        fs::write(&journal_path, bytes)?;
2332        let error = read_journal_snapshot(&journal_path).expect_err(
2333            "unknown environment fields must not be silently discarded",
2334        );
2335        assert!(format!("{error:#}").contains("unknown field"));
2336        Ok(())
2337    }
2338
2339    #[crate::ctb_test]
2340    fn test_journal_legacy_embedded_identity_obeys_policy() -> Result<()> {
2341        use ctb_formats_dcstring::DcProjectionPolicy;
2342
2343        let context = SharedValueContext::default();
2344        let mut entity = FileEntity::from_vec(b"payload".to_vec());
2345        entity.identity.relative_path = Some(PathBuf::from("entry"));
2346        let mut encoded = Vec::new();
2347        write_entity_payload(&mut encoded, &entity, &context)?;
2348        let positive = read_entity_payload(
2349            &encoded,
2350            current_platform(),
2351            &context,
2352            &DcProjectionPolicy::strict(),
2353        )?;
2354        assert_eq!(positive.identity, entity.identity);
2355
2356        let marker = encoded
2357            .windows(8)
2358            .position(|window| window == b"CTBMETA3")
2359            .context("Missing preservation record marker")?;
2360        let record_start = marker
2361            .checked_add(8)
2362            .context("Preservation record offset overflow")?;
2363        let mut cursor = encoded
2364            .get(record_start..)
2365            .context("Invalid preservation record offset")?;
2366        let mut record: PreservationRecord =
2367            serde_json::from_slice(&read_bytes(&mut cursor)?)?;
2368        let mut missing_nlink = DcMstring::new();
2369        missing_nlink.push_char(ctb_formats_dcstring::DcChar::from_short(319));
2370        entity.identity.origin.encode_dc_mixed(&mut missing_nlink)?;
2371        missing_nlink.push_char(ctb_formats_dcstring::DcChar::from_short(337));
2372        entity
2373            .identity
2374            .relative_path
2375            .as_ref()
2376            .context("Missing test path")?
2377            .encode_dc_mixed(&mut missing_nlink)?;
2378        missing_nlink.push_char(ctb_formats_dcstring::DcChar::from_short(320));
2379        record.identity_dc = Some(missing_nlink.as_bytes().to_vec());
2380        let mut malformed = encoded
2381            .get(..record_start)
2382            .context("Invalid preservation prefix")?
2383            .to_vec();
2384        write_bytes(&mut malformed, &serde_json::to_vec(&record)?)?;
2385        assert!(
2386            read_entity_payload(
2387                &malformed,
2388                current_platform(),
2389                &context,
2390                &DcProjectionPolicy::strict()
2391            )
2392            .is_err()
2393        );
2394        let salvaged = read_entity_payload(
2395            &malformed,
2396            current_platform(),
2397            &context,
2398            &DcProjectionPolicy::forgiving(),
2399        )?;
2400        assert_eq!(
2401            salvaged.identity.relative_path,
2402            entity.identity.relative_path
2403        );
2404        assert_eq!(salvaged.identity.nlink, 0);
2405
2406        let mut journal = JOURNAL_MAGIC_V1.to_vec();
2407        journal.extend_from_slice(&[TAG_SESSION_HEADER, current_platform()]);
2408        write_u32(&mut journal, 0)?;
2409        write_bytes(&mut journal, b"destination")?;
2410        journal.push(TAG_ENTITY);
2411        write_u32(&mut journal, u32::try_from(malformed.len())?)?;
2412        journal.extend_from_slice(&xxhash::xxhash3_64(&malformed));
2413        journal.extend_from_slice(&malformed);
2414        journal.push(TAG_BATCH_COMMIT);
2415        legacy::write_u64(&mut journal, 1)?;
2416        journal.extend_from_slice(&ctb_formats_checksum::sha256(&malformed));
2417        journal.push(TAG_JOB_COMPLETED);
2418        assert!(convert_cscjournal_to_bytes(&journal).is_err());
2419        assert!(convert_cscjournal_to_dcmstring(&journal).is_err());
2420        assert!(
2421            convert_cscjournal_to_bytes_with_policy(
2422                &journal,
2423                &DcProjectionPolicy::strict()
2424            )
2425            .is_err()
2426        );
2427        assert!(
2428            convert_cscjournal_to_dcmstring_with_policy(
2429                &journal,
2430                &DcProjectionPolicy::strict()
2431            )
2432            .is_err()
2433        );
2434        let converted = convert_cscjournal_to_bytes_with_policy(
2435            &journal,
2436            &DcProjectionPolicy::forgiving(),
2437        )?;
2438        let temp = tempdir()?;
2439        let path = temp.path().join("salvaged.cscjournal");
2440        fs::write(&path, converted)?;
2441        let snapshot = read_journal_snapshot(&path)?;
2442        assert!(snapshot.is_completed);
2443        assert_eq!(snapshot.last_batch_id, 1);
2444        assert_eq!(
2445            snapshot
2446                .committed_entities
2447                .get(b"entry".as_slice())
2448                .context("Missing salvaged entity")?
2449                .identity,
2450            salvaged.identity
2451        );
2452        let (document, log) = convert_cscjournal_to_dcmstring_with_policy(
2453            &journal,
2454            &DcProjectionPolicy::forgiving(),
2455        )?;
2456        assert!(document.len() > ctb_formats_dcstring::DCMM_HEADER_LEN);
2457        assert!(!log.has_errors());
2458        Ok(())
2459    }
2460
2461    #[crate::ctb_test]
2462    fn test_journal_legacy_identity_fidelity_warning() -> Result<()> {
2463        let context = SharedValueContext::default();
2464        let mut entity = FileEntity::from_vec(b"payload".to_vec());
2465        entity.identity.relative_path = Some(PathBuf::from("entry"));
2466        let mut encoded = Vec::new();
2467        write_entity_payload(&mut encoded, &entity, &context)?;
2468        let marker = encoded
2469            .windows(8)
2470            .position(|window| window == b"CTBMETA3")
2471            .context("Missing preservation record marker")?;
2472        let record_start = marker
2473            .checked_add(8)
2474            .context("Preservation record offset overflow")?;
2475        let mut cursor = encoded
2476            .get(record_start..)
2477            .context("Invalid preservation record offset")?;
2478        let mut record: PreservationRecord =
2479            serde_json::from_slice(&read_bytes(&mut cursor)?)?;
2480        record.identity_dc = None;
2481        let prefix = encoded
2482            .get(..marker)
2483            .context("Invalid preservation record prefix")?;
2484        let oldest = read_entity_payload(
2485            prefix,
2486            current_platform(),
2487            &context,
2488            &ctb_formats_dcstring::DcProjectionPolicy::strict(),
2489        )?;
2490        assert!(oldest.metadata.warnings.iter().any(|warning| {
2491            warning.contains("Legacy journal lacks semantic identity")
2492        }));
2493        let mut legacy = prefix.to_vec();
2494        legacy.extend_from_slice(b"CTBMETA2");
2495        write_bytes(&mut legacy, &serde_json::to_vec(&record)?)?;
2496        let decoded = read_entity_payload(
2497            &legacy,
2498            current_platform(),
2499            &context,
2500            &ctb_formats_dcstring::DcProjectionPolicy::strict(),
2501        )?;
2502        assert!(decoded.metadata.warnings.iter().any(|warning| {
2503            warning.contains("Legacy journal lacks semantic identity")
2504        }));
2505        let mut invalid = prefix.to_vec();
2506        invalid.extend_from_slice(b"CTBMETA3");
2507        write_bytes(&mut invalid, &serde_json::to_vec(&record)?)?;
2508        assert!(
2509            read_entity_payload(
2510                &invalid,
2511                current_platform(),
2512                &context,
2513                &ctb_formats_dcstring::DcProjectionPolicy::strict()
2514            )
2515            .is_err()
2516        );
2517        Ok(())
2518    }
2519
2520    #[crate::ctb_test]
2521    fn test_legacy_raw_flags_normalized_only_at_journal_boundary() -> Result<()>
2522    {
2523        let context = SharedValueContext::default();
2524        let entity = FileEntity::from_vec(b"payload".to_vec());
2525        let mut encoded = Vec::new();
2526        write_entity_payload(&mut encoded, &entity, &context)?;
2527        let marker = encoded
2528            .windows(8)
2529            .position(|window| window == b"CTBMETA3")
2530            .context("Missing preservation record marker")?;
2531        let record_start = marker
2532            .checked_add(8)
2533            .context("Preservation record offset overflow")?;
2534        let mut cursor = encoded
2535            .get(record_start..)
2536            .context("Invalid preservation record offset")?;
2537        let mut record: PreservationRecord =
2538            serde_json::from_slice(&read_bytes(&mut cursor)?)?;
2539        let flags = serde_json::json!({
2540            "source_os": "linux", "raw_value": u64::MAX, "has_unparsed_flags": true
2541        });
2542        record.metadata["platform_raw_flags"] = flags.clone();
2543        assert!(
2544            serde_json::from_value::<ctb_io::file::PlatformRawFlags>(flags)
2545                .is_err()
2546        );
2547        for magic in [b"CTBMETA1", b"CTBMETA2", b"CTBMETA3"] {
2548            let mut legacy = encoded
2549                .get(..marker)
2550                .context("Invalid record prefix")?
2551                .to_vec();
2552            legacy.extend_from_slice(magic);
2553            write_bytes(&mut legacy, &serde_json::to_vec(&record)?)?;
2554            let decoded = read_entity_payload(
2555                &legacy,
2556                current_platform(),
2557                &context,
2558                &ctb_formats_dcstring::DcProjectionPolicy::strict(),
2559            )?;
2560            assert_eq!(
2561                decoded.metadata.platform_raw_flags,
2562                Some(ctb_io::file::PlatformRawFlags::from_raw(u64::MAX))
2563            );
2564        }
2565        record.metadata["platform_raw_flags"] =
2566            serde_json::json!({"raw_value": -1});
2567        let mut legacy = encoded
2568            .get(..marker)
2569            .context("Invalid record prefix")?
2570            .to_vec();
2571        legacy.extend_from_slice(b"CTBMETA3");
2572        write_bytes(&mut legacy, &serde_json::to_vec(&record)?)?;
2573        assert!(
2574            read_entity_payload(
2575                &legacy,
2576                current_platform(),
2577                &context,
2578                &ctb_formats_dcstring::DcProjectionPolicy::strict()
2579            )
2580            .is_err()
2581        );
2582        Ok(())
2583    }
2584
2585    #[crate::ctb_test]
2586    fn test_journal_semantic_identity_roundtrip() -> Result<()> {
2587        let context = SharedValueContext::default();
2588        for path in [None, Some(PathBuf::new()), Some(PathBuf::from("entry"))] {
2589            let mut entity = FileEntity::from_vec(b"payload".to_vec());
2590            entity.identity.relative_path = path;
2591            entity.identity.origin = FileOrigin::Archive {
2592                archive_path: PathBuf::from("source.tar"),
2593                entry_index: 3,
2594                archive_format: FormatId::Tar,
2595            };
2596            let mut encoded = Vec::new();
2597            write_entity_payload(&mut encoded, &entity, &context)?;
2598            let decoded = read_entity_payload(
2599                &encoded,
2600                current_platform(),
2601                &context,
2602                &ctb_formats_dcstring::DcProjectionPolicy::strict(),
2603            )?;
2604            assert_eq!(decoded.identity, entity.identity);
2605        }
2606        Ok(())
2607    }
2608
2609    #[crate::ctb_test]
2610    fn test_journal_conflicting_filename_rejected() -> Result<()> {
2611        let mut entity = FileEntity::from_vec(b"payload".to_vec());
2612        entity.identity.relative_path = Some(PathBuf::from("name"));
2613        let context = SharedValueContext::default();
2614        let mut encoded = Vec::new();
2615        write_entity_payload(&mut encoded, &entity, &context)?;
2616        let mut cursor = encoded.as_slice();
2617        assert_eq!(read_bytes(&mut cursor)?, b"name");
2618        let filename_length = usize::try_from(read_u32(&mut cursor)?)?;
2619        let filename_offset = encoded
2620            .len()
2621            .checked_sub(cursor.len())
2622            .context("Invalid journal filename offset")?;
2623        for byte in encoded
2624            .iter_mut()
2625            .skip(filename_offset)
2626            .take(filename_length)
2627        {
2628            *byte = b'x';
2629        }
2630        let error = read_entity_payload(
2631            &encoded,
2632            current_platform(),
2633            &context,
2634            &ctb_formats_dcstring::DcProjectionPolicy::strict(),
2635        )
2636        .expect_err("Conflicting identity fields must not be discarded");
2637        assert!(format!("{error:#}").contains("filename disagrees"));
2638        Ok(())
2639    }
2640
2641    #[crate::ctb_test]
2642    fn test_journal_shared_environment_provenance() -> Result<()> {
2643        let temp = tempdir()?;
2644        let journal_path = temp.path().join("sharing.cscjournal");
2645        let mut writer = StateJournal::create_at_path(
2646            &journal_path,
2647            &temp.path().join("sharing.cscdesc"),
2648            &[],
2649            temp.path(),
2650        )?;
2651        let environment = writer
2652            .environment
2653            .clone()
2654            .context("Missing writer environment")?;
2655        let distinct = Arc::new(EnvDescription {
2656            os: "original-foreign-environment".to_owned(),
2657            ..EnvDescription::default()
2658        });
2659        let mut entity = FileEntity::from_vec(b"parent".to_vec());
2660        entity.identity.relative_path = Some(PathBuf::from("parent"));
2661        entity.metadata.environment = Some(Arc::clone(&environment));
2662        let mut child = FileEntity::from_vec(b"child".to_vec());
2663        child.metadata.environment = Some(Arc::clone(&distinct));
2664        entity.streams.push(AttachedStream {
2665            name: None,
2666            kind: StreamKind::MacOsResourceFork,
2667            entity: Box::new(child),
2668            data: None,
2669            payload: None,
2670        });
2671        entity.streams.push(AttachedStream {
2672            name: None,
2673            kind: StreamKind::MacOsResourceFork,
2674            entity: Box::new(FileEntity::from_vec(b"unknown".to_vec())),
2675            data: None,
2676            payload: None,
2677        });
2678        writer.record_entity(&entity);
2679        let mut unknown = FileEntity::from_vec(b"unknown".to_vec());
2680        unknown.identity.relative_path = Some(PathBuf::from("unknown"));
2681        writer.record_entity(&unknown);
2682        let mut equal = FileEntity::from_vec(b"equal".to_vec());
2683        equal.identity.relative_path = Some(PathBuf::from("equal"));
2684        equal.metadata.environment = Some(Arc::new((*environment).clone()));
2685        writer.record_entity(&equal);
2686        writer.commit_batch()?;
2687        let snapshot = read_journal_snapshot(&journal_path)?;
2688        let stored = snapshot
2689            .environment
2690            .as_ref()
2691            .context("Missing persisted environment")?;
2692        let parent = snapshot
2693            .committed_entities
2694            .get(b"parent".as_slice())
2695            .context("Missing parent")?;
2696        assert!(
2697            parent
2698                .metadata
2699                .environment
2700                .as_ref()
2701                .is_some_and(|value| Arc::ptr_eq(value, stored))
2702        );
2703        assert_eq!(
2704            parent.streams[0].entity.metadata.environment.as_ref(),
2705            Some(&distinct)
2706        );
2707        assert!(parent.streams[1].entity.metadata.environment.is_none());
2708        assert!(
2709            snapshot
2710                .committed_entities
2711                .get(b"unknown".as_slice())
2712                .context("Missing unknown")?
2713                .metadata
2714                .environment
2715                .is_none()
2716        );
2717        assert!(
2718            snapshot
2719                .committed_entities
2720                .get(b"equal".as_slice())
2721                .context("Missing equal")?
2722                .metadata
2723                .environment
2724                .as_ref()
2725                .is_some_and(|value| Arc::ptr_eq(value, stored))
2726        );
2727        let mut payload = Vec::new();
2728        write_entity_payload(&mut payload, &entity, writer.writer.context())?;
2729        assert!(
2730            read_entity_payload(
2731                &payload,
2732                current_platform(),
2733                &SharedValueContext::default(),
2734                &ctb_formats_dcstring::DcProjectionPolicy::strict()
2735            )
2736            .is_err()
2737        );
2738        Ok(())
2739    }
2740
2741    #[crate::ctb_test]
2742    fn test_journal_legacy_resume_refused_and_v5_unknown_environment_preserved()
2743    -> Result<()> {
2744        let temp = tempdir()?;
2745
2746        // 1. Legacy v1 journal must be refused by open_for_resume without modifying disk bytes
2747        let v1_path = temp.path().join("legacy_v1.cscjournal");
2748        let mut v1_bytes = JOURNAL_MAGIC_V1.to_vec();
2749        v1_bytes.extend_from_slice(&[TAG_SESSION_HEADER, current_platform()]);
2750        write_u32(&mut v1_bytes, 0)?;
2751        write_bytes(&mut v1_bytes, b"")?;
2752        v1_bytes.push(TAG_JOB_COMPLETED);
2753        fs::write(&v1_path, &v1_bytes)?;
2754        let v1_snapshot = read_journal_snapshot(&v1_path)?;
2755        assert!(
2756            StateJournal::open_for_resume(
2757                &v1_path,
2758                &temp.path().join("legacy_v1.cscdesc"),
2759                &v1_snapshot
2760            )
2761            .is_err(),
2762            "Resuming a legacy v1 journal must fail with an error"
2763        );
2764        assert_eq!(
2765            fs::read(&v1_path)?,
2766            v1_bytes,
2767            "Refused v1 journal must remain unmodified"
2768        );
2769
2770        // 2. Legacy v4 (DcMixed1) journal must be refused by open_for_resume without modifying disk bytes
2771        let session = JournalSessionRecord {
2772            sources: Vec::new(),
2773            destination: PathBuf::new(),
2774            origin_platform: u32::from(current_platform()),
2775            environment: None,
2776        };
2777        let v5_bytes = stream::JournalWriter::new(
2778            Vec::new(),
2779            &session,
2780            stream::JournalMagic::JournalV5,
2781        )?
2782        .finish()?;
2783        let v5_mstr = DcMstring::from_slice(
2784            v5_bytes.get(8..).context("Missing v5 payload")?,
2785        )?;
2786        let (dcmm1_payload, _) =
2787            ctb_formats_dcstring::dc_mixed::dcmstring_to_dcmm1(&v5_mstr)?;
2788        let mut v4_bytes = JOURNAL_MAGIC_V4.to_vec();
2789        v4_bytes.extend_from_slice(&dcmm1_payload);
2790        let v4_path = temp.path().join("legacy_v4.cscjournal");
2791        fs::write(&v4_path, &v4_bytes)?;
2792        let v4_snapshot = read_journal_snapshot(&v4_path)?;
2793        assert!(
2794            StateJournal::open_for_resume(
2795                &v4_path,
2796                &temp.path().join("legacy_v4.cscdesc"),
2797                &v4_snapshot
2798            )
2799            .is_err(),
2800            "Resuming a legacy v4 (DcMixed1) journal must fail with an error"
2801        );
2802        assert_eq!(
2803            fs::read(&v4_path)?,
2804            v4_bytes,
2805            "Refused v4 journal must remain unmodified"
2806        );
2807        assert!(
2808            read_journal_snapshot(&v4_path)?.is_completed,
2809            "Refused v4 journal must remain readable"
2810        );
2811
2812        // Mismatched outer magic and inner DcMixed UUID must be rejected
2813        let mut mismatched_v4 = JOURNAL_MAGIC_V4.to_vec();
2814        mismatched_v4.extend_from_slice(v5_mstr.as_bytes());
2815        let mismatched_v4_path = temp.path().join("mismatched_v4.cscjournal");
2816        fs::write(&mismatched_v4_path, &mismatched_v4)?;
2817        assert!(read_journal_snapshot(&mismatched_v4_path).is_err());
2818
2819        // 3. Modern v5 (DcMixed2) journal with environment: None preserves unknown environment across resume
2820        let v5_path = temp.path().join("modern_v5.cscjournal");
2821        fs::write(&v5_path, v5_bytes)?;
2822        let snapshot = read_journal_snapshot(&v5_path)?;
2823        let mut writer = StateJournal::open_for_resume(
2824            &v5_path,
2825            &temp.path().join("modern_v5.cscdesc"),
2826            &snapshot,
2827        )?;
2828        assert!(writer.environment.is_none());
2829        let mut entity = FileEntity::from_vec(b"unknown".to_vec());
2830        entity.identity.relative_path = Some(PathBuf::from("unknown"));
2831        writer.record_entity(&entity);
2832        writer.commit_batch()?;
2833        let snapshot = read_journal_snapshot(&v5_path)?;
2834        assert!(snapshot.environment.is_none());
2835        assert!(
2836            snapshot
2837                .committed_entities
2838                .get(b"unknown".as_slice())
2839                .context("Missing resumed entity")?
2840                .metadata
2841                .environment
2842                .is_none()
2843        );
2844        Ok(())
2845    }
2846
2847    #[crate::ctb_test]
2848    fn test_journal_entity_format_and_checksum_resilience() {
2849        use crate::journal::{StateJournal, read_journal_snapshot};
2850        use ctb_io::file::entity::{FileEntity, FileEntityKind};
2851        use ctb_io::file::identity::{FileIdentity, FileOrigin};
2852        use ctb_io::file::metadata::{FileMetadata, FileTimestamps};
2853        use std::io::Write;
2854
2855        let temp = tempdir().expect("create tempdir");
2856        let src = temp.path().join("src");
2857        let dest = temp.path().join("dest");
2858        fs::create_dir_all(&src).expect("create src");
2859        fs::create_dir_all(&dest).expect("create dest");
2860
2861        let mut writer =
2862            StateJournal::create_new(temp.path(), &[src.clone()], &dest)
2863                .expect("create journal");
2864
2865        let read_time_expected = std::time::SystemTime::UNIX_EPOCH
2866            .checked_add(std::time::Duration::from_secs(1_700_000_000))
2867            .expect("valid timestamp");
2868
2869        let mut file_entity = FileEntity {
2870            identity: FileIdentity {
2871                origin: FileOrigin::Synthetic,
2872                relative_path: Some(PathBuf::from("hello.txt")),
2873                enclosing_path: Some(src.clone()),
2874                nlink: 1,
2875                hardlink_group: None,
2876            },
2877            metadata: FileMetadata {
2878                native: None,
2879                mode: Some(0o644),
2880                uid: Some(1000),
2881                gid: Some(1000),
2882                timestamps: Some(FileTimestamps {
2883                    atime_sec: 1_700_000_000,
2884                    atime_nsec: 100,
2885                    mtime_sec: 1_700_000_001,
2886                    mtime_nsec: 200,
2887                    ctime_sec: 1_700_000_002,
2888                    ctime_nsec: 300,
2889                    birthtime_sec: None,
2890                    birthtime_nsec: None,
2891                    resolution_nsec: None,
2892                }),
2893                flags: Some(Vec::new()),
2894                platform_raw_flags: None,
2895                read_time: Some(read_time_expected),
2896                filesystem_type: None,
2897                environment: None,
2898                apple: None,
2899                warnings: Vec::new(),
2900                errors: Vec::new(),
2901            },
2902            kind: FileEntityKind::Regular {
2903                size: 42,
2904                sha256: [0xAB; 32],
2905                is_sparse: false,
2906                extents: Vec::new(),
2907            },
2908            streams: Vec::new(),
2909        };
2910
2911        let link_entity = FileEntity {
2912            identity: FileIdentity {
2913                origin: FileOrigin::Synthetic,
2914                relative_path: Some(PathBuf::from("link.txt")),
2915                enclosing_path: None,
2916                nlink: 2,
2917                hardlink_group: Some(Natural::from(12345_u64)),
2918            },
2919            metadata: FileMetadata {
2920                native: None,
2921                mode: Some(0o644),
2922                uid: Some(1000),
2923                gid: Some(1000),
2924                timestamps: Some(FileTimestamps {
2925                    atime_sec: 1_700_000_000,
2926                    atime_nsec: 0,
2927                    mtime_sec: 1_700_000_000,
2928                    mtime_nsec: 0,
2929                    ctime_sec: 1_700_000_000,
2930                    ctime_nsec: 0,
2931                    birthtime_sec: None,
2932                    birthtime_nsec: None,
2933                    resolution_nsec: None,
2934                }),
2935                flags: Some(Vec::new()),
2936                platform_raw_flags: None,
2937                read_time: None,
2938                filesystem_type: None,
2939                environment: None,
2940                apple: None,
2941                warnings: Vec::new(),
2942                errors: Vec::new(),
2943            },
2944            kind: FileEntityKind::Hardlink {
2945                target_relative_path: LinkPath::from_bytes(
2946                    b"hello.txt",
2947                    cfg!(windows),
2948                ),
2949            },
2950            streams: Vec::new(),
2951        };
2952
2953        if let Some(ref mut ts) = file_entity.metadata.timestamps {
2954            ts.birthtime_sec = Some(-123);
2955            ts.birthtime_nsec = Some(if cfg!(windows) {
2956                987_654_300
2957            } else {
2958                987_654_321
2959            });
2960        }
2961        file_entity.metadata.native =
2962            Some(ctb_io::file::metadata::NativeMetadata {
2963                source_os: ctb_io::file::OsFamily::Darwin,
2964                values: std::collections::BTreeMap::from([
2965                    (
2966                        "opaque".to_owned(),
2967                        ctb_io::file::metadata::NativeMetadataValue::Bytes(
2968                            vec![0, 255, 128],
2969                        ),
2970                    ),
2971                    (
2972                        "unsigned".to_owned(),
2973                        ctb_io::file::metadata::NativeMetadataValue::Unsigned(
2974                            u64::MAX,
2975                        ),
2976                    ),
2977                    (
2978                        "signed".to_owned(),
2979                        ctb_io::file::metadata::NativeMetadataValue::Signed(
2980                            i64::MIN,
2981                        ),
2982                    ),
2983                ]),
2984            });
2985        file_entity.metadata.platform_raw_flags =
2986            Some(ctb_io::file::PlatformRawFlags::from_raw(u64::MAX));
2987        if let FileEntityKind::Regular { extents, .. } = &mut file_entity.kind {
2988            extents.push(ctb_io::file::Extent::Data {
2989                offset: 0,
2990                length: 42,
2991            });
2992        }
2993        let mut stream_entity = file_entity.clone();
2994        stream_entity.streams.clear();
2995        file_entity.streams.push(ctb_io::file::AttachedStream {
2996            name: Some(ctb_io::file::StreamName::from_bytes(b"user.raw\xff")),
2997            kind: ctb_io::file::StreamKind::SecurityLabel,
2998            entity: Box::new(stream_entity),
2999            data: Some(vec![0, 255, 128]),
3000            payload: None,
3001        });
3002        let mut wide_stream = file_entity.streams[0].clone();
3003        wide_stream.name =
3004            Some(ctb_io::file::StreamName::from_windows_utf16(&[
3005                0x003a, 0xd800, 0x0061,
3006            ]));
3007        file_entity.streams.push(wide_stream);
3008        for name in [
3009            ctb_io::file::StreamName::from_bytes(b"user.binary\xff"),
3010            ctb_io::file::StreamName::from_windows_utf16(&[
3011                0x003a, 0xd800, 0x0061,
3012            ]),
3013        ] {
3014            file_entity.streams.push(
3015                ctb_io::file::AttachedStream::from_data(
3016                    Some(name),
3017                    ctb_io::file::StreamKind::NtfsAlternateDataStream,
3018                    vec![0, 255, 128],
3019                )
3020                .unwrap(),
3021            );
3022        }
3023        file_entity.streams.push(
3024            ctb_io::file::AttachedStream::from_data(
3025                None,
3026                ctb_io::file::StreamKind::MacOsResourceFork,
3027                vec![1, 2, 3, 4],
3028            )
3029            .unwrap(),
3030        );
3031        file_entity.metadata.environment = writer.environment.clone();
3032        for stream in &mut file_entity.streams {
3033            stream.entity.metadata.environment = writer.environment.clone();
3034        }
3035        writer.record_entity(&file_entity);
3036        writer.record_entity(&link_entity);
3037        writer.commit_batch().expect("commit batch");
3038
3039        let snap = read_journal_snapshot(writer.journal_path())
3040            .expect("read snapshot");
3041        assert_eq!(snap.committed_entities.len(), 2);
3042        assert!(snap.is_committed(b"hello.txt"));
3043        assert!(snap.is_committed(b"link.txt"));
3044
3045        let read_file = snap
3046            .committed_entities
3047            .get(b"hello.txt".as_slice())
3048            .expect("get hello.txt");
3049        let mut expected_file = file_entity.clone();
3050        expected_file.strip_stream_bodies();
3051        assert_eq!(read_file, &expected_file);
3052        for stream in &read_file.streams {
3053            assert_eq!(stream.data, None);
3054        }
3055        assert_eq!(read_file.identity.enclosing_path, Some(src.clone()));
3056        assert_eq!(read_file.metadata.read_time, Some(read_time_expected));
3057        if let FileEntityKind::Regular { size, sha256, .. } = &read_file.kind {
3058            assert_eq!(*size, 42);
3059            assert_eq!(*sha256, [0xAB; 32]);
3060        } else {
3061            panic!("Expected regular file kind");
3062        }
3063
3064        let read_link = snap
3065            .committed_entities
3066            .get(b"link.txt".as_slice())
3067            .expect("get link.txt");
3068        if let FileEntityKind::Hardlink {
3069            target_relative_path,
3070        } = &read_link.kind
3071        {
3072            assert_eq!(target_relative_path, b"hello.txt");
3073        } else {
3074            panic!("Expected hardlink kind");
3075        }
3076
3077        // Test corruption resilience: Append corrupted bytes (bad checksum)
3078        {
3079            let mut file = std::fs::OpenOptions::new()
3080                .append(true)
3081                .open(writer.journal_path())
3082                .expect("open for append");
3083            // TAG_ENTITY (2) + len (10) + checksum (0) + 10 junk bytes
3084            file.write_all(&[2, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
3085                .expect("write junk");
3086            file.write_all(b"badpayload").expect("write junk payload");
3087        }
3088
3089        let malformed_journal =
3090            fs::read(writer.journal_path()).expect("read malformed journal");
3091        for policy in [
3092            ctb_formats_dcstring::DcProjectionPolicy::strict(),
3093            ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
3094        ] {
3095            let error = read_journal_snapshot_with_policy(
3096                writer.journal_path(),
3097                &policy,
3098            )
3099            .expect_err(
3100                "Malformed closed records must not be silently discarded",
3101            );
3102            assert!(
3103                format!("{error:#}").contains("Unsupported journal record")
3104            );
3105        }
3106        assert_eq!(
3107            fs::read(writer.journal_path()).expect("reread journal"),
3108            malformed_journal
3109        );
3110    }
3111
3112    #[crate::ctb_test]
3113    fn test_journal_pre_epoch_read_time_rejected() {
3114        use crate::journal::StateJournal;
3115        use ctb_io::file::entity::{FileEntity, FileEntityKind};
3116        use ctb_io::file::identity::{FileIdentity, FileOrigin};
3117        use ctb_io::file::metadata::{FileMetadata, FileTimestamps};
3118
3119        let temp = tempdir().expect("create tempdir");
3120        let src = temp.path().join("src");
3121        let dest = temp.path().join("dest");
3122        std::fs::create_dir_all(&src).expect("create src");
3123        std::fs::create_dir_all(&dest).expect("create dest");
3124
3125        let mut writer =
3126            StateJournal::create_new(temp.path(), &[src.clone()], &dest)
3127                .expect("create journal");
3128
3129        let pre_epoch_time = std::time::SystemTime::UNIX_EPOCH
3130            .checked_sub(std::time::Duration::from_secs(10))
3131            .expect("valid pre-epoch time");
3132
3133        let file_entity = FileEntity {
3134            identity: FileIdentity {
3135                origin: FileOrigin::Synthetic,
3136                relative_path: Some(PathBuf::from("pre_epoch.txt")),
3137                enclosing_path: Some(src),
3138                nlink: 1,
3139                hardlink_group: None,
3140            },
3141            metadata: FileMetadata {
3142                native: None,
3143                mode: Some(0o644),
3144                uid: Some(1000),
3145                gid: Some(1000),
3146                timestamps: Some(FileTimestamps {
3147                    atime_sec: 1_700_000_000,
3148                    atime_nsec: 0,
3149                    mtime_sec: 1_700_000_000,
3150                    mtime_nsec: 0,
3151                    ctime_sec: 1_700_000_000,
3152                    ctime_nsec: 0,
3153                    birthtime_sec: None,
3154                    birthtime_nsec: None,
3155                    resolution_nsec: None,
3156                }),
3157                flags: Some(Vec::new()),
3158                platform_raw_flags: None,
3159                read_time: Some(pre_epoch_time),
3160                filesystem_type: None,
3161                environment: None,
3162                apple: None,
3163                warnings: Vec::new(),
3164                errors: Vec::new(),
3165            },
3166            kind: FileEntityKind::Regular {
3167                size: 0,
3168                sha256: [0; 32],
3169                is_sparse: false,
3170                extents: Vec::new(),
3171            },
3172            streams: Vec::new(),
3173        };
3174
3175        writer.record_entity(&file_entity);
3176        assert!(writer.commit_batch().is_err());
3177    }
3178
3179    #[cfg(unix)]
3180    #[crate::ctb_test]
3181    fn test_failed_copy_retains_captured_metadata_and_destination() {
3182        let _fs_lock = ctb_io::file::FS_CACHE_TEST_MUTEX.lock().unwrap();
3183        ctb_io::file::clear_filesystem_cache();
3184        let temp = tempdir().unwrap();
3185        let source = temp.path().join("link");
3186        let destination = temp.path().join("destination");
3187        let state = temp.path().join("state");
3188        fs::create_dir(&state).unwrap();
3189        std::os::unix::fs::symlink("missing-target", &source).unwrap();
3190        fs::write(&destination, b"old destination").unwrap();
3191        let _ = std::fs::read_link(&source);
3192        let original =
3193            ctb_io::file::FileEntity::from_filesystem(&source, None).unwrap();
3194        assert!(
3195            original
3196                .metadata
3197                .timestamps
3198                .as_ref()
3199                .and_then(|ts| ts.birthtime_sec)
3200                .is_some()
3201        );
3202        let mut args = default_test_args(
3203            vec![source.clone(), destination.clone()],
3204            state.clone(),
3205        );
3206        args.best_effort_metadata = false;
3207        assert!(run_csc(args).is_err());
3208        assert_eq!(fs::read(&destination).unwrap(), b"old destination");
3209        assert!(fs::symlink_metadata(&source).is_ok());
3210        let journal = find_cscjournal(&state);
3211        let snapshot = crate::journal::read_journal_snapshot(&journal).unwrap();
3212        assert!(!snapshot.is_completed);
3213        let recorded = snapshot.committed_entities.values().next().unwrap();
3214        let mut expected_native = original.metadata.native.clone();
3215        let mut actual_native = recorded.metadata.native.clone();
3216        if let (Some(exp), Some(act)) =
3217            (&mut expected_native, &mut actual_native)
3218        {
3219            // Separate captures can cross a second boundary; readlink and
3220            // timestamp cleanup affect both components of atime/ctime.
3221            for name in [
3222                "statx.atime.sec",
3223                "statx.atime.nsec",
3224                "statx.ctime.sec",
3225                "statx.ctime.nsec",
3226            ] {
3227                exp.values.remove(name);
3228                act.values.remove(name);
3229            }
3230        }
3231        assert_eq!(actual_native, expected_native);
3232        let mut expected_ts = original.metadata.timestamps;
3233        let mut actual_ts = recorded.metadata.timestamps;
3234        if let Some(ref mut ts) = expected_ts {
3235            ts.atime_sec = 0;
3236            ts.atime_nsec = 0;
3237            ts.ctime_sec = 0;
3238            ts.ctime_nsec = 0;
3239        }
3240        if let Some(ref mut ts) = actual_ts {
3241            ts.atime_sec = 0;
3242            ts.atime_nsec = 0;
3243            ts.ctime_sec = 0;
3244            ts.ctime_nsec = 0;
3245        }
3246        assert_eq!(actual_ts, expected_ts);
3247        assert_eq!(
3248            recorded.metadata.platform_raw_flags,
3249            original.metadata.platform_raw_flags
3250        );
3251        assert_eq!(recorded.streams, original.streams);
3252        assert!(
3253            recorded
3254                .metadata
3255                .errors
3256                .iter()
3257                .any(|error| error.starts_with("Materialization failed:"))
3258        );
3259        assert!(snapshot.errors.iter().any(|error| matches!(
3260            error.stage,
3261            JournalErrorStage::Materialize
3262        )));
3263    }
3264
3265    #[cfg(unix)]
3266    #[crate::ctb_test]
3267    fn test_target_error_reporting_shows_target_file() {
3268        let temp = tempdir().expect("create tempdir");
3269        let scratch_file = temp.path().join("scratch.csc-tmp.12345");
3270        fs::write(&scratch_file, b"data").expect("write scratch");
3271
3272        let intended_target = temp.path().join("my_real_file.bin");
3273
3274        // Non-root user cannot chown to root (uid 0) unless running as root
3275        if nix::unistd::geteuid().as_raw() != 0 {
3276            let meta = ctb_io::file::FileMetadata {
3277                native: None,
3278                mode: Some(0o644),
3279                uid: Some(0),
3280                gid: Some(0),
3281                timestamps: Some(ctb_io::file::FileTimestamps {
3282                    atime_sec: 1_000_000,
3283                    atime_nsec: 0,
3284                    mtime_sec: 1_000_000,
3285                    mtime_nsec: 0,
3286                    ctime_sec: 1_000_000,
3287                    ctime_nsec: 0,
3288                    birthtime_sec: None,
3289                    birthtime_nsec: None,
3290                    resolution_nsec: None,
3291                }),
3292                flags: Some(Vec::new()),
3293                platform_raw_flags: None,
3294                read_time: None,
3295                filesystem_type: None,
3296                environment: None,
3297                apple: None,
3298                warnings: Vec::new(),
3299                errors: Vec::new(),
3300            };
3301
3302            let err = ctb_io::file::apply_entity_metadata(
3303                &scratch_file,
3304                Some(&intended_target),
3305                &meta,
3306                false,
3307                false,
3308                true, // strict_lossless
3309                true,
3310            )
3311            .unwrap_err();
3312
3313            let err_msg = format!("{err:#}");
3314            // The error MUST mention the intended destination path, and NOT the scratch temp file!
3315            assert!(
3316                err_msg.contains("my_real_file.bin"),
3317                "Error message should mention the intended target file: {err_msg}"
3318            );
3319            assert!(
3320                !err_msg.contains("scratch.csc-tmp.12345"),
3321                "Error message should NOT mention the scratch temp path: {err_msg}"
3322            );
3323        }
3324    }
3325
3326    #[crate::ctb_test("tokio")]
3327    async fn test_journal_and_index_environment_metadata() {
3328        use crate::journal::{StateJournal, read_journal_snapshot};
3329        use ctb_io::file::entity::{FileEntity, FileEntityKind};
3330        use ctb_io::file::identity::{FileIdentity, FileOrigin};
3331        use ctb_io::file::metadata::{FileMetadata, FileTimestamps};
3332        use std::sync::Arc;
3333        use turso::{Builder, Value};
3334
3335        let temp = tempdir().expect("tempdir");
3336        let journal_path = temp.path().join("test_env.cscjournal");
3337        let desc_path = temp.path().join("test_env.cscdesc");
3338        let src = temp.path().join("src");
3339        let dest = temp.path().join("dest");
3340        fs::create_dir_all(&src).expect("create src");
3341        fs::create_dir_all(&dest).expect("create dest");
3342
3343        // 1. Create journal and verify environment is initialized
3344        let mut writer = StateJournal::create_at_path(
3345            &journal_path,
3346            &desc_path,
3347            &[src.clone()],
3348            &dest,
3349        )
3350        .expect("create_at_path");
3351
3352        assert!(
3353            writer.environment.is_some(),
3354            "StateJournal should initialize environment"
3355        );
3356
3357        let rel_path = PathBuf::from("file_a.txt");
3358        let entity = FileEntity {
3359            identity: FileIdentity {
3360                origin: FileOrigin::Synthetic,
3361                relative_path: Some(rel_path.clone()),
3362                enclosing_path: None,
3363                nlink: 1,
3364                hardlink_group: None,
3365            },
3366            metadata: FileMetadata {
3367                native: None,
3368                mode: Some(0o644),
3369                uid: Some(1000),
3370                gid: Some(1000),
3371                timestamps: Some(FileTimestamps {
3372                    atime_sec: 1_700_000_000,
3373                    atime_nsec: 0,
3374                    mtime_sec: 1_700_000_000,
3375                    mtime_nsec: 0,
3376                    ctime_sec: 1_700_000_000,
3377                    ctime_nsec: 0,
3378                    birthtime_sec: None,
3379                    birthtime_nsec: None,
3380                    resolution_nsec: None,
3381                }),
3382                flags: Some(Vec::new()),
3383                platform_raw_flags: None,
3384                read_time: None,
3385                filesystem_type: None,
3386                environment: writer.environment.clone(),
3387                apple: None,
3388                warnings: Vec::new(),
3389                errors: Vec::new(),
3390            },
3391            kind: FileEntityKind::Regular {
3392                size: 25,
3393                sha256: [0x11; 32],
3394                is_sparse: false,
3395                extents: Vec::new(),
3396            },
3397            streams: Vec::new(),
3398        };
3399
3400        writer.record_entity(&entity);
3401        writer.commit_batch().expect("commit_batch");
3402        writer.mark_completed().expect("mark_completed");
3403
3404        // 2. Read snapshot and verify the explicit environment reference is shared.
3405        let snapshot =
3406            read_journal_snapshot(&journal_path).expect("read snapshot");
3407        assert!(
3408            snapshot.environment.is_some(),
3409            "Snapshot should have decoded environment"
3410        );
3411        let snap_env = snapshot.environment.as_ref().unwrap();
3412
3413        let committed = snapshot
3414            .committed_entities
3415            .get(b"file_a.txt".as_slice())
3416            .expect("committed entity");
3417        assert!(
3418            committed.metadata.environment.is_some(),
3419            "Entity should inherit deduplicated environment"
3420        );
3421        assert!(
3422            Arc::ptr_eq(
3423                snap_env,
3424                committed.metadata.environment.as_ref().unwrap()
3425            ),
3426            "Arc pointer should be shared (deduplicated)"
3427        );
3428
3429        // 3. Backward compatibility: reading a synthetic journal without TAG_SESSION_ENV
3430        let legacy_journal_path = temp.path().join("legacy.cscjournal");
3431        let mut legacy_bytes = Vec::new();
3432        legacy_bytes.extend_from_slice(b"CTBCSCJ\x01");
3433        // TAG_SESSION_HEADER = 1, current_platform = 1, sources count = 0, destination = ""
3434        legacy_bytes.push(1); // TAG_SESSION_HEADER
3435        legacy_bytes.push(1); // platform
3436        legacy_bytes.extend_from_slice(&0_u32.to_le_bytes()); // src_count = 0
3437        legacy_bytes.extend_from_slice(&0_u32.to_le_bytes()); // dest_len = 0
3438        legacy_bytes.push(4); // TAG_JOB_COMPLETED
3439        fs::write(&legacy_journal_path, legacy_bytes)
3440            .expect("write legacy journal");
3441
3442        let legacy_snapshot = read_journal_snapshot(&legacy_journal_path)
3443            .expect("read legacy snapshot");
3444        assert!(
3445            legacy_snapshot.environment.is_none(),
3446            "Legacy journal should yield None environment"
3447        );
3448
3449        // 4. Test SQLite database schema initialization, migration, and sources environment column
3450        let db_path = temp.path().join("env_test.cscindex.sqlite");
3451        let db = Builder::new_local(db_path.to_str().expect("valid path"))
3452            .experimental_index_method(true)
3453            .build()
3454            .await
3455            .expect("open db");
3456        let conn = db.connect().expect("connect db");
3457
3458        crate::index_engine::init_database_schema(&conn)
3459            .await
3460            .expect("init database schema");
3461
3462        // Verify environment column exists in sources table
3463        let mut pragma_stmt = conn
3464            .prepare("PRAGMA table_info(sources)")
3465            .await
3466            .expect("prepare pragma");
3467        let mut pragma_rows =
3468            pragma_stmt.query(()).await.expect("query pragma");
3469        let mut has_env_col = false;
3470        while let Some(row) = pragma_rows.next().await.expect("row") {
3471            if let Ok(Value::Text(col)) = row.get_value(1) {
3472                if col == "environment" {
3473                    has_env_col = true;
3474                    break;
3475                }
3476            }
3477        }
3478        assert!(has_env_col, "sources table must have environment column");
3479
3480        // Ingest snapshot into database
3481        let progress = ctb_utilities::Progress::new(false);
3482        let env_json =
3483            snapshot.environment.as_ref().and_then(|e| e.to_json().ok());
3484        let src_id = crate::index_engine::get_or_create_source(
3485            &conn,
3486            "test_source",
3487            &journal_path,
3488            env_json.as_deref(),
3489        )
3490        .await
3491        .expect("get_or_create_source");
3492
3493        let ingested = crate::index_engine::ingest_journal_snapshot(
3494            &conn, src_id, &snapshot, 100, &progress, None,
3495        )
3496        .await
3497        .expect("ingest");
3498        assert_eq!(ingested, 1);
3499
3500        // Verify the environment JSON in sources row
3501        let mut select_stmt = conn
3502            .prepare("SELECT environment FROM sources WHERE id = ?")
3503            .await
3504            .expect("prepare");
3505        let mut select_rows = select_stmt
3506            .query(vec![Value::Integer(src_id)])
3507            .await
3508            .expect("query");
3509        let row = select_rows
3510            .next()
3511            .await
3512            .expect("next")
3513            .expect("row present");
3514        let stored_env = row.get_value(0).expect("get value");
3515        if let Value::Text(json_str) = stored_env {
3516            assert!(
3517                json_str.contains("\"os\":"),
3518                "Stored JSON should contain os"
3519            );
3520            let decoded =
3521                ctb_io_environment::EnvDescription::from_json(&json_str)
3522                    .expect("valid environment JSON");
3523            assert_eq!(decoded.os, snap_env.os);
3524            assert_eq!(decoded.is_linux(), snap_env.is_linux());
3525            assert_eq!(decoded.is_windows(), snap_env.is_windows());
3526        } else {
3527            panic!("Expected Value::Text for sources.environment");
3528        }
3529    }
3530
3531    #[crate::ctb_test]
3532    fn test_environment_metadata_auto_population_and_operation_isolation() {
3533        let temp = tempdir().unwrap();
3534        let file1 = temp.path().join("file1.txt");
3535        let file2 = temp.path().join("file2.txt");
3536        fs::write(&file1, b"hello file 1").unwrap();
3537        fs::write(&file2, b"hello file 2").unwrap();
3538
3539        let scope = ctb_io_environment::EnvironmentScope::enter_fresh();
3540
3541        // 1. FileEntity::from_filesystem automatically populates environment metadata
3542        let mut entity1 =
3543            ctb_io::file::FileEntity::from_filesystem(&file1, None).unwrap();
3544        assert!(entity1.metadata.environment.is_some());
3545        assert!(entity1.environment().is_some());
3546
3547        // 2. Attached streams also automatically populate environment metadata
3548        let stream = ctb_io::file::AttachedStream::from_data(
3549            Some(ctb_io::file::StreamName::from_bytes(b"stream1")),
3550            ctb_io::file::StreamKind::NtfsAlternateDataStream,
3551            vec![1, 2, 3],
3552        )
3553        .unwrap();
3554        assert!(stream.entity.metadata.environment.is_some());
3555        entity1.streams.push(stream);
3556
3557        // 3. Calls within the same operation scope share the exact same Arc (pointer equality)
3558        let entity2 =
3559            ctb_io::file::FileEntity::from_filesystem(&file2, None).unwrap();
3560        let env1 = entity1.metadata.environment.as_ref().unwrap();
3561        let env2 = entity2.metadata.environment.as_ref().unwrap();
3562        assert!(std::sync::Arc::ptr_eq(env1, env2));
3563
3564        // 4. FileEntity::set_environment propagates to all attached streams
3565        let custom_env =
3566            std::sync::Arc::new(ctb_io_environment::capture_quick());
3567        entity1.set_environment(std::sync::Arc::clone(&custom_env));
3568        assert!(std::sync::Arc::ptr_eq(
3569            entity1.metadata.environment.as_ref().unwrap(),
3570            &custom_env
3571        ));
3572        assert!(std::sync::Arc::ptr_eq(
3573            entity1.streams[0]
3574                .entity
3575                .metadata
3576                .environment
3577                .as_ref()
3578                .unwrap(),
3579            &custom_env
3580        ));
3581        drop(scope);
3582
3583        // 5. Simulate two separate operations within a single process (e.g. successive csc runs):
3584        // Each operation enters its own GlobalEnvironmentScope, getting a distinct Arc snapshot.
3585        let arc_op1 = {
3586            let _scope1 =
3587                ctb_io_environment::GlobalEnvironmentScope::enter_fresh();
3588            let e = ctb_io::file::FileEntity::from_filesystem(&file1, None)
3589                .unwrap();
3590            e.metadata.environment.unwrap()
3591        };
3592
3593        let arc_op2 = {
3594            let _scope2 =
3595                ctb_io_environment::GlobalEnvironmentScope::enter_fresh();
3596            let e = ctb_io::file::FileEntity::from_filesystem(&file1, None)
3597                .unwrap();
3598            e.metadata.environment.unwrap()
3599        };
3600
3601        // Independent operations get distinct Arc instances (not inadvertently cached together)
3602        assert!(!std::sync::Arc::ptr_eq(&arc_op1, &arc_op2));
3603
3604        // Global network caches remain intact across operations
3605        if let Ok(ip) = ctb_io_environment::local_ipv4() {
3606            let cached = ctb_io_environment::cached_local_ipv4();
3607            assert_eq!(cached.ok(), Some(ip));
3608        }
3609    }
3610
3611    #[crate::ctb_test("tokio")]
3612    async fn test_full_provenance_csc_and_related_commands() {
3613        use crate::args::{
3614            MvArgs, default_fsindex_args, default_test_args,
3615            default_verify_args,
3616        };
3617        use crate::cli::run_csc;
3618        use crate::index_engine::run_fsindex;
3619        use crate::journal::{find_cscjournal, read_journal_snapshot};
3620        use crate::move_engine::run_mv;
3621        use crate::verifier::run_csc_verify;
3622        use turso::Builder;
3623
3624        let download_attempts =
3625            Arc::new(std::sync::atomic::AtomicUsize::new(0));
3626        let attempted = Arc::clone(&download_attempts);
3627        let _offline =
3628            ctb_utilities::https::crlite::set_test_download_override(
3629                move |_| {
3630                    attempted
3631                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3632                    anyhow::bail!(
3633                        "Provenance test is deterministically offline"
3634                    )
3635                },
3636            )
3637            .unwrap();
3638        let temp = tempdir().unwrap();
3639        let src = temp.path().join("src");
3640        let dest = temp.path().join("dest");
3641        let state = temp.path().join("state");
3642        fs::create_dir_all(&src).unwrap();
3643        fs::create_dir_all(&dest).unwrap();
3644        fs::create_dir_all(&state).unwrap();
3645
3646        fs::write(src.join("test.txt"), b"full provenance test content")
3647            .unwrap();
3648
3649        // 1. Run csc with full_provenance: true
3650        let mut csc_args = default_test_args(
3651            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3652            state.clone(),
3653        );
3654        csc_args.full_provenance = true;
3655        csc_args.overwrite = true;
3656        run_csc(csc_args).expect("run csc with full provenance");
3657
3658        let journal_path = find_cscjournal(&state);
3659        let snapshot = read_journal_snapshot(&journal_path)
3660            .expect("read journal snapshot");
3661        assert!(
3662            snapshot.environment.is_some(),
3663            "Journal snapshot must have environment"
3664        );
3665        let env = snapshot.environment.as_ref().unwrap();
3666        assert!(!env.ctb_version.is_empty());
3667
3668        // Verify entities committed in snapshot have matching environment
3669        for entity in snapshot.committed_entities.values() {
3670            assert!(entity.metadata.environment.is_some());
3671        }
3672
3673        // 2. Run csc-verify with full_provenance: true
3674        let mut verify_args = default_verify_args(journal_path.clone(), None);
3675        verify_args.full_provenance = true;
3676        let v_res = run_csc_verify(&verify_args)
3677            .expect("run csc-verify with full provenance");
3678        match v_res {
3679            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
3680                assert_eq!(exit_code, 0);
3681            }
3682            _ => panic!("Expected Immediate ToolResult from csc-verify"),
3683        }
3684
3685        // 3. Run fsindex with full_provenance: true
3686        let db_path = temp.path().join("provenance.cscindex.sqlite");
3687        let mut fsindex_args =
3688            default_fsindex_args(vec![dest.clone()], Some(db_path.clone()));
3689        fsindex_args.full_provenance = true;
3690        run_fsindex(fsindex_args)
3691            .await
3692            .expect("run fsindex with full provenance");
3693
3694        let db = Builder::new_local(db_path.to_str().unwrap())
3695            .build()
3696            .await
3697            .expect("open db");
3698        let conn = db.connect().expect("connect db");
3699        let mut select_stmt = conn
3700            .prepare("SELECT environment FROM sources")
3701            .await
3702            .expect("prepare");
3703        let mut rows = select_stmt.query(()).await.expect("query");
3704        let row = rows.next().await.expect("next").expect("row exists");
3705        let env_val = row.get_value(0).expect("get_value");
3706        match env_val {
3707            turso::Value::Text(json_str) => {
3708                let parsed =
3709                    ctb_io_environment::EnvDescription::from_json(&json_str)
3710                        .expect("parse environment JSON");
3711                assert_eq!(parsed.ctb_version, env.ctb_version);
3712            }
3713            _ => panic!("Expected Value::Text for sources.environment"),
3714        }
3715
3716        // 4. Run mv with full_provenance: true
3717        let mv_src = temp.path().join("mv_src");
3718        let mv_dest = temp.path().join("mv_dest");
3719        fs::create_dir_all(&mv_src).unwrap();
3720        fs::write(mv_src.join("mv_test.txt"), b"move with provenance").unwrap();
3721        let mv_args = MvArgs {
3722            paths: vec![mv_src.clone(), mv_dest.clone()],
3723            resume: None,
3724            journal_path: None,
3725            state_dir: None,
3726            verbose: false,
3727            progress: false,
3728            no_progress: true,
3729            verify_after: true,
3730            no_verify_after: false,
3731            best_effort_metadata: false,
3732            allow_unknown_fs: false,
3733            force: false,
3734            dry_run: false,
3735            full_provenance: true,
3736        };
3737        run_mv(mv_args).expect("run mv with full provenance");
3738        assert!(mv_dest.join("mv_test.txt").exists());
3739        assert!(
3740            download_attempts.load(std::sync::atomic::Ordering::Relaxed) > 0,
3741            "Full provenance must exercise network discovery through the offline transport"
3742        );
3743    }
3744
3745    /// Verifies authentic multi-revision journal test fixtures:
3746    /// - Revision 1 (CTBMETA1): Commit `d90071e25` (last buildable commit before CTBMETA2 in 8a1f3786d)
3747    /// - Revision 2 (CTBMETA2): Commit `02070a495` (last buildable commit before CTBMETA3 in 14737998c)
3748    /// - Revision 3 (CTBMETA3): Commit `14737998c` (last buildable commit before DcMixed in a48081c47)
3749    /// - Revision 4 (DcMixed): Commit `HEAD` / `main` (CTBCSCJ\x04 with DcMM)
3750    #[crate::ctb_test]
3751    fn test_all_journal_revision_fixtures() -> Result<()> {
3752        let fixtures_dir = ctb_utilities::manifest_fixture_path(
3753            env!("CARGO_MANIFEST_DIR"),
3754            "fixtures/journals",
3755        );
3756
3757        let s1 = read_journal_snapshot(
3758            &fixtures_dir.join("v1_ctbmeta1-20261011.cscjournal"),
3759        )
3760        .context("Failed to read revision 1 fixture")?;
3761        let s2 = read_journal_snapshot(
3762            &fixtures_dir.join("v2_ctbmeta2-20261011.cscjournal"),
3763        )
3764        .context("Failed to read revision 2 fixture")?;
3765        let v3_fixture = fixtures_dir.join("v3_ctbmeta3-20261011.cscjournal");
3766        let strict_error = read_journal_snapshot(&v3_fixture).expect_err(
3767            "Historical untyped path literals must be rejected strictly",
3768        );
3769        assert!(
3770            format!("{strict_error:#}")
3771                .contains("missing Dc 262..263 type header")
3772        );
3773        let s3 = read_journal_snapshot_with_policy(
3774            &v3_fixture,
3775            &ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
3776        ).context("Failed to recover revision 3 fixture with explicit forgiving policy")?;
3777        let v4_fixture = fixtures_dir.join("v4_dcmixed-20261011.cscjournal");
3778        assert!(
3779            read_journal_snapshot(&v4_fixture).is_err(),
3780            "Development-era malformed closed records must be rejected in strict mode"
3781        );
3782        let s4 = read_journal_snapshot_with_policy(
3783            &v4_fixture,
3784            &ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
3785        )?;
3786
3787        // Verify snapshots across all four format revisions
3788        for (rev_name, snap) in [
3789            ("v1_ctbmeta1", &s1),
3790            ("v2_ctbmeta2", &s2),
3791            ("v3_ctbmeta3", &s3),
3792            ("v4_dcmixed", &s4),
3793        ] {
3794            assert!(snap.is_completed, "{rev_name} must be completed");
3795            assert!(
3796                !snap.committed_entities.is_empty(),
3797                "{rev_name} must have entities"
3798            );
3799            assert!(
3800                snap.committed_entities
3801                    .contains_key(b"src/fixture_info.txt".as_slice())
3802                    || snap
3803                        .committed_entities
3804                        .contains_key(b"src\\fixture_info.txt".as_slice())
3805                    || snap
3806                        .committed_entities
3807                        .contains_key(b"src/main.rs".as_slice())
3808                    || snap
3809                        .committed_entities
3810                        .contains_key(b"src\\main.rs".as_slice()),
3811                "{rev_name} must contain payload files"
3812            );
3813        }
3814
3815        assert!(
3816            s4.environment.is_some(),
3817            "v4_dcmixed must record environment"
3818        );
3819
3820        Ok(())
3821    }
3822
3823    #[crate::ctb_test]
3824    fn test_journal_revision_rejects_retired_dcmm_types() -> Result<()> {
3825        let temp = tempdir()?;
3826        let path = temp.path().join("retired.cscjournal");
3827        for type_byte in [1, 4] {
3828            let mut payload = DcMstring::new().into_bytes();
3829            payload.extend_from_slice(
3830                &ctb_formats_dcstring::dc_mixed::DC_203_BYTES,
3831            );
3832            payload.push(type_byte);
3833            let expected_offset = payload.len().saturating_sub(1);
3834            payload.extend_from_slice(&0u128.to_be_bytes());
3835            if type_byte == 4 {
3836                payload.extend_from_slice(&ctb_formats_checksum::sha256(b""));
3837            }
3838            let mut bytes = JOURNAL_MAGIC_V4.to_vec();
3839            bytes.extend_from_slice(&payload);
3840            fs::write(&path, &bytes)?;
3841            for error in [
3842                read_journal_snapshot(&path)
3843                    .err()
3844                    .context("Retired types must not be recovered as a truncated journal")?,
3845                convert_cscjournal_to_dcmstring(&bytes)
3846                    .err()
3847                    .context("Retired types must not be converted")?,
3848            ] {
3849                let cause = error
3850                    .downcast_ref::<ctb_formats_dcstring::DcMixedError>()
3851                    .context("Missing DcMixed error")?;
3852                assert_eq!(
3853                    cause,
3854                    &ctb_formats_dcstring::DcMixedError::UnsupportedLegacyType {
3855                        offset: expected_offset,
3856                        type_byte,
3857                    },
3858                );
3859            }
3860        }
3861        Ok(())
3862    }
3863
3864    #[crate::ctb_test]
3865    fn test_journal_conversion_all_revisions_to_bytes_and_dcmstring()
3866    -> Result<()> {
3867        let fixtures_dir = ctb_utilities::manifest_fixture_path(
3868            env!("CARGO_MANIFEST_DIR"),
3869            "fixtures/journals",
3870        );
3871
3872        let temp = tempfile::tempdir()?;
3873
3874        // Test converting legacy revisions 1..=3 to current bytes and validating snapshot parity
3875        for (rev_name, filename, policy) in [
3876            (
3877                "v1_ctbmeta1",
3878                "v1_ctbmeta1-20261011.cscjournal",
3879                ctb_formats_dcstring::DcProjectionPolicy::strict(),
3880            ),
3881            (
3882                "v2_ctbmeta2",
3883                "v2_ctbmeta2-20261011.cscjournal",
3884                ctb_formats_dcstring::DcProjectionPolicy::strict(),
3885            ),
3886            (
3887                "v3_ctbmeta3",
3888                "v3_ctbmeta3-20261011.cscjournal",
3889                ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
3890            ),
3891        ] {
3892            let legacy_path = fixtures_dir.join(filename);
3893            let legacy_bytes = fs::read(&legacy_path)?;
3894            let orig_snap = read_journal_snapshot_with_policy(
3895                &legacy_path,
3896                &policy,
3897            )
3898            .with_context(|| {
3899                format!("Failed to read {rev_name} fixture before conversion")
3900            })?;
3901
3902            let converted_bytes = convert_cscjournal_to_bytes_with_policy(
3903                &legacy_bytes,
3904                &policy,
3905            )?;
3906            assert!(
3907                converted_bytes.starts_with(JOURNAL_MAGIC),
3908                "{rev_name} converted bytes must start with JOURNAL_MAGIC"
3909            );
3910
3911            let converted_path =
3912                temp.path().join(format!("{rev_name}_converted.cscjournal"));
3913            fs::write(&converted_path, &converted_bytes)?;
3914
3915            let converted_snap = read_journal_snapshot(&converted_path)?;
3916            assert_eq!(
3917                converted_snap.is_completed, orig_snap.is_completed,
3918                "{rev_name}: completed status must match"
3919            );
3920            assert_eq!(
3921                converted_snap.committed_entities.len(),
3922                orig_snap.committed_entities.len(),
3923                "{rev_name}: entity count must match"
3924            );
3925            assert_eq!(
3926                converted_snap.origin_platform, orig_snap.origin_platform,
3927                "{rev_name}: origin platform must match"
3928            );
3929            assert_eq!(
3930                converted_snap.destination, orig_snap.destination,
3931                "{rev_name}: destination must match"
3932            );
3933            for key in orig_snap.committed_entities.keys() {
3934                assert!(
3935                    converted_snap.committed_entities.contains_key(key),
3936                    "{rev_name}: converted journal must retain entity {key:?}"
3937                );
3938            }
3939        }
3940
3941        // Test converting all 4 revisions directly to DcMstring
3942        for (filename, policy) in [
3943            (
3944                "v1_ctbmeta1-20261011.cscjournal",
3945                ctb_formats_dcstring::DcProjectionPolicy::strict(),
3946            ),
3947            (
3948                "v2_ctbmeta2-20261011.cscjournal",
3949                ctb_formats_dcstring::DcProjectionPolicy::strict(),
3950            ),
3951            (
3952                "v3_ctbmeta3-20261011.cscjournal",
3953                ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
3954            ),
3955            (
3956                "v4_dcmixed-20261011.cscjournal",
3957                ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
3958            ),
3959        ] {
3960            let bytes = fs::read(fixtures_dir.join(filename))?;
3961            let (doc, log) =
3962                convert_cscjournal_to_dcmstring_with_policy(&bytes, &policy)?;
3963            assert!(
3964                doc.len() > ctb_formats_dcstring::DCMM_HEADER_LEN,
3965                "{filename}: DcMstring document must have payload beyond 21-byte header"
3966            );
3967            assert!(
3968                !log.has_errors(),
3969                "{filename}: conversion should not log errors"
3970            );
3971        }
3972
3973        Ok(())
3974    }
3975
3976    #[crate::ctb_test]
3977    fn test_copy_journal_strips_attached_stream_bodies() -> Result<()> {
3978        let temp = tempdir()?;
3979        let journal_path = temp.path().join("copy.cscjournal");
3980        let desc_path = temp.path().join("copy.cscdesc");
3981        let source = temp.path().join("source.bin");
3982        let destination = temp.path().join("dest.bin");
3983
3984        let mut journal = StateJournal::create_at_path(
3985            &journal_path,
3986            &desc_path,
3987            std::slice::from_ref(&source),
3988            &destination,
3989        )?;
3990
3991        let mut entity = FileEntity::from_vec(b"primary content".to_vec());
3992        entity.identity.relative_path = Some("source.bin".into());
3993
3994        let stream_payload =
3995            b"large stream payload that should not be in journal".to_vec();
3996        let expected_size = u64::try_from(stream_payload.len())?;
3997        let expected_hash = ctb_formats_checksum::sha256(&stream_payload);
3998
3999        let stream = AttachedStream::from_data(
4000            Some(StreamName::from_str("user.test_stream")),
4001            StreamKind::ExtendedAttribute,
4002            stream_payload.clone(),
4003        )?;
4004        entity.streams.push(stream);
4005
4006        journal.record_entity(&entity);
4007        journal.commit_batch()?;
4008
4009        // Verify on-disk .cscjournal does not contain the stream body bytes
4010        let journal_bytes = fs::read(&journal_path)?;
4011        assert!(
4012            !journal_bytes
4013                .windows(stream_payload.len())
4014                .any(|w| w == stream_payload.as_slice()),
4015            "Copy mode .cscjournal must not contain stream payload bodies"
4016        );
4017
4018        // Verify reading snapshot restores metadata and digests but stream.data is None
4019        let snapshot = read_journal_snapshot(&journal_path)?;
4020        let recorded = snapshot
4021            .committed_entities
4022            .values()
4023            .next()
4024            .context("Missing committed entity")?;
4025        assert_eq!(recorded.streams.len(), 1);
4026        assert_eq!(
4027            recorded.streams[0].name,
4028            Some(StreamName::from_str("user.test_stream"))
4029        );
4030        assert_eq!(recorded.streams[0].kind, StreamKind::ExtendedAttribute);
4031        assert_eq!(
4032            recorded.streams[0].data, None,
4033            "Stream data must be stripped in journal snapshot"
4034        );
4035
4036        // Metadata and checksums are preserved on stream.entity
4037        if let FileEntityKind::Regular { size, sha256, .. } =
4038            &recorded.streams[0].entity.kind
4039        {
4040            assert_eq!(*size, expected_size);
4041            assert_eq!(*sha256, expected_hash);
4042        } else {
4043            panic!("Expected regular stream entity kind");
4044        }
4045
4046        Ok(())
4047    }
4048
4049    #[crate::ctb_test]
4050    fn test_journal_durable_applied_directory_receipts() -> Result<()> {
4051        let temp = tempdir()?;
4052        let journal_path = temp.path().join("applied.cscjournal");
4053        let desc_path = temp.path().join("applied.cscdesc");
4054        let source = temp.path().join("src");
4055        let destination = temp.path().join("dst");
4056
4057        let mut journal = StateJournal::create_at_path(
4058            &journal_path,
4059            &desc_path,
4060            std::slice::from_ref(&source),
4061            &destination,
4062        )?;
4063
4064        let rel1 = PathBuf::from("dir1");
4065        let id1 = InodeKey::new(12345, 67890_u64);
4066        let rel2 = PathBuf::from("dir1/nested");
4067        let id2 = InodeKey::new(12345, 67891_u64);
4068
4069        journal.record_applied_directory(rel1.clone(), id1.clone());
4070        journal.record_applied_directory(rel2.clone(), id2.clone());
4071
4072        let mut dummy = FileEntity::from_vec(b"dummy".to_vec());
4073        dummy.identity.relative_path = Some("dir1/file.txt".into());
4074        journal.record_entity(&dummy);
4075        journal.commit_batch()?;
4076
4077        // Verify .cscdesc contains AppliedDirectories section
4078        let desc_content = fs::read_to_string(&desc_path)?;
4079        assert!(desc_content.contains("AppliedDirectories:"));
4080
4081        // Snapshot reading restores applied_directories
4082        let snapshot = read_journal_snapshot(&journal_path)?;
4083        assert_eq!(snapshot.applied_directories.len(), 2);
4084        assert_eq!(snapshot.applied_directories.get(&rel1), Some(&id1));
4085        assert_eq!(snapshot.applied_directories.get(&rel2), Some(&id2));
4086
4087        // Reopening journal for resume retains applied_directories
4088        let resumed = StateJournal::open_for_resume(
4089            &journal_path,
4090            &desc_path,
4091            &snapshot,
4092        )?;
4093        assert_eq!(resumed.applied_directories().len(), 2);
4094        assert_eq!(resumed.applied_directories().get(&rel1), Some(&id1));
4095        assert_eq!(resumed.applied_directories().get(&rel2), Some(&id2));
4096
4097        Ok(())
4098    }
4099
4100    #[crate::ctb_test]
4101    fn test_128_bit_file_id_applied_directory_receipt() -> Result<()> {
4102        let temp_dir = tempfile::tempdir()?;
4103        let journal_path = temp_dir.path().join("test_128.cscjournal");
4104        let desc_path = temp_dir.path().join("test_128.cscdesc");
4105        let source = temp_dir.path().join("source");
4106        let destination = temp_dir.path().join("destination");
4107
4108        let mut journal = StateJournal::create_at_path(
4109            &journal_path,
4110            &desc_path,
4111            std::slice::from_ref(&source),
4112            &destination,
4113        )?;
4114
4115        // 128-bit file ID (e.g. ReFS or 128-bit NTFS FILE_ID_128)
4116        let file_id_128: u128 = 0x0123_4567_89ab_cdef_fedc_ba98_7654_3210;
4117        let volume_64: u64 = 0xfeed_cafe_dead_beef;
4118        let id_128 = InodeKey::from_file_id_128(volume_64, file_id_128);
4119        assert_eq!(id_128.as_u128(), Some(file_id_128));
4120
4121        let rel = PathBuf::from("refs_dir");
4122        journal.record_applied_directory(rel.clone(), id_128.clone());
4123
4124        let mut dummy = FileEntity::from_vec(b"test".to_vec());
4125        dummy.identity.relative_path = Some("refs_dir/file.txt".into());
4126        journal.record_entity(&dummy);
4127        journal.commit_batch()?;
4128
4129        // Verify .cscdesc contains 128-bit number
4130        let desc_content = fs::read_to_string(&desc_path)?;
4131        assert!(desc_content.contains("AppliedDirectories:"));
4132
4133        // Snapshot reading restores exact 128-bit identity
4134        let snapshot = read_journal_snapshot(&journal_path)?;
4135        let restored_identity = snapshot
4136            .applied_directories
4137            .get(&rel)
4138            .context("Missing restored directory receipt")?;
4139        assert_eq!(restored_identity, &id_128);
4140        assert_eq!(restored_identity.as_u128(), Some(file_id_128));
4141
4142        Ok(())
4143    }
4144
4145    #[crate::ctb_test]
4146    fn test_copy_journal_warns_on_unexpected_stream_body() -> Result<()> {
4147        let temp_dir = tempfile::tempdir()?;
4148        let journal_path = temp_dir.path().join("warn_test.cscjournal");
4149        let desc_path = temp_dir.path().join("warn_test.cscdesc");
4150        let source = temp_dir.path().join("source");
4151        let destination = temp_dir.path().join("destination");
4152
4153        let mut journal = StateJournal::create_at_path(
4154            &journal_path,
4155            &desc_path,
4156            std::slice::from_ref(&source),
4157            &destination,
4158        )?;
4159
4160        // Manually inject an entity that retains an in-memory stream body into the record queue
4161        let mut entity = FileEntity::from_vec(b"hello".to_vec());
4162        entity.identity.relative_path = Some("file_with_stream.txt".into());
4163        let mut stream = AttachedStream::from_data(
4164            Some(StreamName::from_str("user.stream")),
4165            StreamKind::ExtendedAttribute,
4166            b"embedded_stream_body".to_vec(),
4167        )?;
4168        stream.entity.streams.push(AttachedStream::from_data(
4169            Some(StreamName::from_str("user.nested")),
4170            StreamKind::ExtendedAttribute,
4171            b"nested_stream_body".to_vec(),
4172        )?);
4173        entity.streams.push(stream);
4174
4175        // Bypass copy-mode stripping to exercise both primary and stream bodies.
4176        let mut payload =
4177            ctb_io::file::MemoryPayloadSource::new(b"hello".to_vec())?;
4178        journal.writer.write_entity(&entity, Some(&mut payload))?;
4179        StateJournal::sync_output(journal.writer.output_mut())?;
4180
4181        // Reading snapshot must emit and record a warning for the unexpected stream body
4182        let snapshot = read_journal_snapshot(&journal_path)?;
4183        assert!(
4184            snapshot
4185                .warnings
4186                .iter()
4187                .any(|w| w.code == "unexpected-journal-stream-body"),
4188            "Expected unexpected-journal-stream-body warning in copy journal snapshot"
4189        );
4190        assert_eq!(
4191            snapshot
4192                .warnings
4193                .iter()
4194                .filter(
4195                    |warning| warning.code == "unexpected-journal-stream-body"
4196                )
4197                .count(),
4198            2
4199        );
4200        assert_eq!(snapshot.warnings.iter().filter(|warning| warning.code == "unexpected-journal-file-body").count(), 1);
4201        let direct = read_v4_journal_snapshot(
4202            &mut File::open(&journal_path)?,
4203            &journal_path,
4204            false,
4205            &ctb_formats_dcstring::DcProjectionPolicy::strict(),
4206        )?;
4207        assert_eq!(direct.warnings, snapshot.warnings);
4208
4209        Ok(())
4210    }
4211}