Skip to main content

folderbase_core/
change_set.rs

1//! Least-authority ordinary-folder checkouts and immutable Change Sets.
2//!
3//! The public records in this module are the runtime for the optional
4//! `folderbase.change-set@0.1.0` capability. A checkout is deliberately not a
5//! Folderbase root: it carries one closed projection receipt and ordinary
6//! files. Trusted projection-to-Version authority remains private to the
7//! source Folderbase.
8
9use std::{
10    collections::{BTreeMap, BTreeSet},
11    fs::{self, File, OpenOptions},
12    io::{Read, Seek, SeekFrom, Write},
13    path::{Component, Path, PathBuf},
14};
15
16use chrono::{SecondsFormat, Utc};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use unicode_casefold::UnicodeCaseFold;
20use unicode_normalization::UnicodeNormalization;
21use uuid::Uuid;
22
23use crate::{
24    FolderbaseVersionStore, LocalVersionStore, PathBindingKind, attest_folderbase_root,
25    folderbase_capture::FolderbaseCaptureError,
26    folderbase_state::FolderbaseState,
27    folderbase_version::{ExclusionKind, FolderbaseVersion, PathBinding, validate_capture_path},
28    transfer_manifest::{
29        ChunkManifest, LARGE_PROFILE_V1, MAX_OBJECT_BYTES, STANDARD_PROFILE_V1,
30        plan_streamed_manifest,
31    },
32};
33
34pub const MAX_CHANGE_SET_BYTES: u64 = 8 * 1024 * 1024;
35pub const MAX_CHANGE_SET_ENTRIES: usize = 16_384;
36const MAX_PROJECTION_RECORD_BYTES: u64 = 64 * 1024 * 1024;
37const IO_BUFFER_BYTES: usize = 64 * 1024;
38const LARGE_PROFILE_THRESHOLD_BYTES: u64 = 1024 * 1024 * 1024;
39const PROJECTIONS_DIRECTORY: &str = ".folderbase/change-set/projections";
40const CHANGE_SET_IDS_DIRECTORY: &str = ".folderbase/change-set/ids";
41const APPLIED_CHANGE_SETS_DIRECTORY: &str = ".folderbase/change-set/applied";
42const CHANGE_SET_TRANSACTIONS_DIRECTORY: &str = ".folderbase/transactions/change-set";
43const ACTIVE_CHANGE_SET_TRANSACTION: &str = ".folderbase/transactions/change-set/active.json";
44
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46#[serde(deny_unknown_fields)]
47pub struct AuthorizedPath {
48    pub path_prefix: Option<String>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
52#[serde(deny_unknown_fields)]
53pub struct CheckoutRequest {
54    pub format: String,
55    pub folderbase_id: String,
56    pub projection_id: String,
57    pub folder_scope_id: String,
58    pub scope_revision_sha256: String,
59    pub permission: String,
60    pub authorized_paths: Vec<AuthorizedPath>,
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
64#[serde(tag = "kind")]
65pub enum ProjectedEntry {
66    #[serde(rename = "directory")]
67    Directory { path: String, object_id: String },
68    #[serde(rename = "regular_file")]
69    RegularFile {
70        path: String,
71        object_id: String,
72        object_version_id: String,
73        content_sha256: String,
74        bytes: u64,
75        executable: bool,
76    },
77    #[serde(rename = "symlink")]
78    Symlink {
79        path: String,
80        object_id: String,
81        object_version_id: String,
82        target: String,
83        target_safety: String,
84    },
85}
86
87impl ProjectedEntry {
88    pub(crate) fn path(&self) -> &str {
89        match self {
90            Self::Directory { path, .. }
91            | Self::RegularFile { path, .. }
92            | Self::Symlink { path, .. } => path,
93        }
94    }
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
98#[serde(deny_unknown_fields)]
99pub struct ProjectionExclusion {
100    pub path: String,
101    pub reason: String,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
105#[serde(deny_unknown_fields)]
106pub struct CheckoutReceipt {
107    pub format: String,
108    pub checkout_id: String,
109    pub folderbase_id: String,
110    pub projection_id: String,
111    pub folder_scope_id: String,
112    pub scope_revision_sha256: String,
113    pub permission: String,
114    pub authorized_paths: Vec<AuthorizedPath>,
115    pub projection_base_sha256: String,
116    pub entries: Vec<ProjectedEntry>,
117    pub exclusions: Vec<ProjectionExclusion>,
118}
119
120#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
121#[serde(deny_unknown_fields)]
122pub struct CheckoutResult {
123    pub format: String,
124    pub checkout_id: String,
125    pub projection_id: String,
126    pub projection_base_sha256: String,
127    pub entry_count: usize,
128    pub exclusion_count: usize,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
132#[serde(deny_unknown_fields)]
133pub struct ProjectionBaseContent {
134    pub source: String,
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
138#[serde(deny_unknown_fields)]
139pub struct StagedContent {
140    pub source: String,
141    pub staging_id: String,
142    pub chunk_manifest_sha256: String,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
146#[serde(untagged)]
147pub enum ContentReference {
148    ProjectionBase(ProjectionBaseContent),
149    Staged(StagedContent),
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
153#[serde(deny_unknown_fields)]
154pub struct DeltaDirectory {
155    pub path: String,
156    pub kind: String,
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
160#[serde(deny_unknown_fields)]
161pub struct DeltaRegularFile {
162    pub path: String,
163    pub kind: String,
164    pub object_version_id: String,
165    pub content_sha256: String,
166    pub bytes: u64,
167    pub executable: bool,
168    pub content: ContentReference,
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
172#[serde(deny_unknown_fields)]
173pub struct DeltaSymlink {
174    pub path: String,
175    pub kind: String,
176    pub object_version_id: String,
177    pub target: String,
178    pub target_safety: String,
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
182#[serde(untagged)]
183pub enum DeltaState {
184    Directory(DeltaDirectory),
185    RegularFile(DeltaRegularFile),
186    Symlink(DeltaSymlink),
187}
188
189impl DeltaState {
190    pub(crate) fn path(&self) -> &str {
191        match self {
192            Self::Directory(value) => &value.path,
193            Self::RegularFile(value) => &value.path,
194            Self::Symlink(value) => &value.path,
195        }
196    }
197
198    fn kind(&self) -> InventoryKind {
199        match self {
200            Self::Directory(_) => InventoryKind::Directory,
201            Self::RegularFile(_) => InventoryKind::RegularFile,
202            Self::Symlink(_) => InventoryKind::Symlink,
203        }
204    }
205}
206
207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
208#[serde(deny_unknown_fields)]
209pub struct ObjectDelta {
210    pub object_id: String,
211    pub before: Option<DeltaState>,
212    pub after: Option<DeltaState>,
213}
214
215#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
216#[serde(deny_unknown_fields)]
217pub struct ChangeSetPayload {
218    pub format: String,
219    pub change_set_id: String,
220    pub checkout_id: String,
221    pub folderbase_id: String,
222    pub projection_id: String,
223    pub folder_scope_id: String,
224    pub scope_revision_sha256: String,
225    pub permission: String,
226    pub authorized_paths: Vec<AuthorizedPath>,
227    pub projection_base_sha256: String,
228    pub created_at: String,
229    pub deltas: Vec<ObjectDelta>,
230}
231
232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
233#[serde(deny_unknown_fields)]
234pub struct ChangeSetEnvelope {
235    pub format: String,
236    pub change_set_sha256: String,
237    pub payload: ChangeSetPayload,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
241#[serde(deny_unknown_fields)]
242pub struct StagingObject {
243    pub staging_id: String,
244    pub chunk_manifest_sha256: String,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
248#[serde(deny_unknown_fields)]
249pub struct StagingIndex {
250    pub format: String,
251    pub objects: Vec<StagingObject>,
252}
253
254#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
255#[serde(deny_unknown_fields)]
256pub struct ChangeSetConflict {
257    pub code: String,
258    pub path: String,
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub other_path: Option<String>,
261    pub object_id: Option<String>,
262}
263
264#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
265#[serde(deny_unknown_fields)]
266pub struct ChangeSetAssessment {
267    pub format: String,
268    pub change_set_sha256: String,
269    pub status: String,
270    pub conflicts: Vec<ChangeSetConflict>,
271    pub current_projection_sha256: String,
272}
273
274#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
275#[serde(deny_unknown_fields)]
276pub struct ChangeSetAttentionDetail {
277    pub code: String,
278    pub message: String,
279    pub retryable: bool,
280    pub conflicts: Vec<ChangeSetConflict>,
281}
282
283#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
284#[serde(deny_unknown_fields)]
285pub struct ChangeSetAttention {
286    pub format: String,
287    pub change_set_sha256: String,
288    pub attention: ChangeSetAttentionDetail,
289}
290
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub enum ChangeSetAssessmentOutcome {
293    Clean(ChangeSetAssessment),
294    Attention(ChangeSetAttention),
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
298#[serde(deny_unknown_fields)]
299pub struct ChangeSetApplyResult {
300    pub format: String,
301    pub change_set_sha256: String,
302    pub status: String,
303    pub projection_result_sha256: String,
304}
305
306#[derive(Debug, Clone, PartialEq, Eq)]
307pub enum ChangeSetApplyOutcome {
308    Applied(ChangeSetApplyResult),
309    Attention(ChangeSetAttention),
310}
311
312#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
313#[serde(deny_unknown_fields)]
314struct ChangeSetIdBinding {
315    format: String,
316    change_set_id: String,
317    change_set_sha256: String,
318}
319
320#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
321#[serde(deny_unknown_fields)]
322struct ChangeSetApplyJournal {
323    format: String,
324    change_set_id: String,
325    change_set_sha256: String,
326    projection_id: String,
327    phase: String,
328    projection_result_sha256: Option<String>,
329}
330
331#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
332#[serde(deny_unknown_fields)]
333struct TrustedProjection {
334    format: String,
335    source_version_id: String,
336    source_version_sha256: String,
337    receipt: CheckoutReceipt,
338}
339
340#[derive(Debug, thiserror::Error)]
341pub enum ChangeSetError {
342    #[error("{code}: {message}")]
343    Invalid { code: &'static str, message: String },
344    #[error("{code}: {message}")]
345    Operational { code: &'static str, message: String },
346}
347
348impl ChangeSetError {
349    pub fn code(&self) -> &'static str {
350        match self {
351            Self::Invalid { code, .. } | Self::Operational { code, .. } => code,
352        }
353    }
354
355    pub fn message(&self) -> String {
356        match self {
357            Self::Invalid { message, .. } | Self::Operational { message, .. } => message.clone(),
358        }
359    }
360}
361
362pub fn checkout_change_set_projection(
363    root: impl AsRef<Path>,
364    destination: impl AsRef<Path>,
365    request: CheckoutRequest,
366) -> Result<CheckoutResult, ChangeSetError> {
367    let root = root.as_ref();
368    let destination = destination.as_ref();
369    validate_checkout_request(&request)?;
370    let attestation = attest_folderbase_root(root).map_err(operational)?;
371    if attestation.folderbase_id != request.folderbase_id {
372        return Err(invalid(
373            "invalid_checkout_request",
374            "checkout request names a different Folderbase",
375        ));
376    }
377    require_new_destination(destination)?;
378
379    // Pin the exact source state before deriving the scoped projection. This
380    // may reuse an unchanged Local Head and never exposes that Head to the
381    // checkout.
382    let store = FolderbaseVersionStore::open(root).map_err(capture_operational)?;
383    let plan = store.plan_capture().map_err(capture_operational)?;
384    let sealed = store.seal_capture(plan).map_err(capture_operational)?;
385    let version = store
386        .read_version(sealed.version_id())
387        .map_err(capture_operational)?;
388
389    let mut entries = version
390        .bindings()
391        .iter()
392        .filter(|binding| is_authorized(binding.path(), &request.authorized_paths))
393        .map(projected_entry)
394        .collect::<Result<Vec<_>, _>>()?;
395    entries.sort_by(|left, right| left.path().as_bytes().cmp(right.path().as_bytes()));
396    if entries.len() > MAX_CHANGE_SET_ENTRIES {
397        return Err(invalid(
398            "invalid_checkout_request",
399            "scoped checkout exceeds the entry limit",
400        ));
401    }
402    let mut exclusions = version
403        .exclusions()
404        .iter()
405        .filter(|exclusion| is_authorized(exclusion.path(), &request.authorized_paths))
406        .map(|exclusion| ProjectionExclusion {
407            path: exclusion.path().to_owned(),
408            reason: match exclusion.kind() {
409                ExclusionKind::NestedFolderbase => "nested-folderbase-boundary",
410                _ => "unsupported-v1",
411            }
412            .to_owned(),
413        })
414        .collect::<Vec<_>>();
415    exclusions.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
416
417    let projection_base_sha256 = projection_digest(&request, &entries, &exclusions)?;
418    let receipt = CheckoutReceipt {
419        format: "folderbase-checkout-projection-v1".to_owned(),
420        checkout_id: format!("checkout_{}", Uuid::now_v7()),
421        folderbase_id: request.folderbase_id.clone(),
422        projection_id: request.projection_id.clone(),
423        folder_scope_id: request.folder_scope_id.clone(),
424        scope_revision_sha256: request.scope_revision_sha256.clone(),
425        permission: request.permission.clone(),
426        authorized_paths: request.authorized_paths.clone(),
427        projection_base_sha256: projection_base_sha256.clone(),
428        entries,
429        exclusions,
430    };
431
432    materialize_checkout(root, destination, &receipt)?;
433    let trusted = TrustedProjection {
434        format: "folderbase-trusted-projection-v1".to_owned(),
435        source_version_id: version.version_id().to_owned(),
436        source_version_sha256: sealed.version_sha256().to_owned(),
437        receipt: receipt.clone(),
438    };
439    install_trusted_projection(root, &trusted)?;
440
441    Ok(CheckoutResult {
442        format: "folderbase-checkout-result-v1".to_owned(),
443        checkout_id: receipt.checkout_id,
444        projection_id: receipt.projection_id,
445        projection_base_sha256,
446        entry_count: receipt.entries.len(),
447        exclusion_count: receipt.exclusions.len(),
448    })
449}
450
451pub fn propose_change_set(
452    checkout: impl AsRef<Path>,
453    staging: impl AsRef<Path>,
454) -> Result<ChangeSetEnvelope, ChangeSetError> {
455    let checkout = checkout.as_ref();
456    let staging = staging.as_ref();
457    let receipt: CheckoutReceipt = read_json_bounded_file(
458        &checkout.join(".folderbase/checkout.json"),
459        MAX_PROJECTION_RECORD_BYTES,
460        "invalid_projection_receipt",
461    )?;
462    validate_receipt(&receipt)?;
463    require_new_destination(staging)?;
464    fs::create_dir(staging).map_err(operational)?;
465    fs::create_dir(staging.join("manifests")).map_err(operational)?;
466    fs::create_dir(staging.join("chunks")).map_err(operational)?;
467
468    let current = inventory_checkout(checkout)?;
469    let base = receipt
470        .entries
471        .iter()
472        .map(InventoryEntry::from_projected)
473        .collect::<Vec<_>>();
474    let matches = match_inventory(&base, &current);
475    let mut matched_base = BTreeSet::new();
476    let mut matched_current = BTreeSet::new();
477    let mut deltas = Vec::new();
478    let mut staged_objects = Vec::new();
479
480    for (base_index, current_index) in matches {
481        matched_base.insert(base_index);
482        matched_current.insert(current_index);
483        let before_entry = &base[base_index];
484        let after_entry = &current[current_index];
485        if before_entry.same_state(after_entry) {
486            continue;
487        }
488        let before = delta_state_from_base(before_entry);
489        let after = delta_state_from_current(
490            checkout,
491            staging,
492            after_entry,
493            Some(before_entry),
494            &mut staged_objects,
495        )?;
496        deltas.push(ObjectDelta {
497            object_id: before_entry
498                .object_id
499                .clone()
500                .ok_or_else(|| operational_message("trusted projection entry omitted Object ID"))?,
501            before: Some(before),
502            after: Some(after),
503        });
504    }
505
506    for (index, entry) in base.iter().enumerate() {
507        if matched_base.contains(&index) {
508            continue;
509        }
510        deltas.push(ObjectDelta {
511            object_id: entry
512                .object_id
513                .clone()
514                .ok_or_else(|| operational_message("trusted projection entry omitted Object ID"))?,
515            before: Some(delta_state_from_base(entry)),
516            after: None,
517        });
518    }
519
520    for (index, entry) in current.iter().enumerate() {
521        if matched_current.contains(&index) {
522            continue;
523        }
524        let object_id = format!("obj_{}", Uuid::now_v7());
525        let after = delta_state_from_current(checkout, staging, entry, None, &mut staged_objects)?;
526        deltas.push(ObjectDelta {
527            object_id,
528            before: None,
529            after: Some(after),
530        });
531    }
532
533    if deltas.is_empty() || deltas.len() > MAX_CHANGE_SET_ENTRIES {
534        return Err(invalid(
535            "invalid_change_set_input",
536            "a Change Set must contain from 1 through 16384 deltas",
537        ));
538    }
539    deltas.sort_by(|left, right| left.object_id.as_bytes().cmp(right.object_id.as_bytes()));
540    staged_objects
541        .sort_by(|left, right| left.staging_id.as_bytes().cmp(right.staging_id.as_bytes()));
542    let index = StagingIndex {
543        format: "folderbase-change-set-staging-v1".to_owned(),
544        objects: staged_objects,
545    };
546    create_new_file(
547        &staging.join("index.json"),
548        &encode_pretty_bounded(&index, MAX_CHANGE_SET_BYTES)?,
549    )?;
550
551    let payload = ChangeSetPayload {
552        format: "folderbase-change-set-payload-v1".to_owned(),
553        change_set_id: format!("changeset_{}", Uuid::now_v7()),
554        checkout_id: receipt.checkout_id,
555        folderbase_id: receipt.folderbase_id,
556        projection_id: receipt.projection_id,
557        folder_scope_id: receipt.folder_scope_id,
558        scope_revision_sha256: receipt.scope_revision_sha256,
559        permission: receipt.permission,
560        authorized_paths: receipt.authorized_paths,
561        projection_base_sha256: receipt.projection_base_sha256,
562        created_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
563        deltas,
564    };
565    let change_set_sha256 = change_set_digest(&payload)?;
566    let envelope = ChangeSetEnvelope {
567        format: "folderbase-change-set-v1".to_owned(),
568        change_set_sha256,
569        payload,
570    };
571    let encoded = serde_json::to_vec(&envelope).map_err(operational)?;
572    if encoded.len() as u64 > MAX_CHANGE_SET_BYTES {
573        return Err(invalid(
574            "invalid_change_set_input",
575            "Change Set envelope exceeds 8 MiB",
576        ));
577    }
578    Ok(envelope)
579}
580
581pub fn assess_change_set(
582    root: impl AsRef<Path>,
583    staging: impl AsRef<Path>,
584    envelope: ChangeSetEnvelope,
585) -> Result<ChangeSetAssessmentOutcome, ChangeSetError> {
586    let root = root.as_ref();
587    let staging = staging.as_ref();
588    validate_change_set_envelope(&envelope)?;
589    let attestation = attest_folderbase_root(root).map_err(operational)?;
590    if attestation.folderbase_id != envelope.payload.folderbase_id {
591        return Err(invalid(
592            "change_set_root_mismatch",
593            "Change Set belongs to a different Folderbase",
594        ));
595    }
596
597    let Some(trusted) = read_trusted_projection(root, &envelope.payload.projection_id)? else {
598        return Ok(ChangeSetAssessmentOutcome::Attention(attention(
599            &envelope,
600            "change_set_stale_base",
601            "trusted projection base is absent; create a fresh checkout",
602            true,
603            Vec::new(),
604        )));
605    };
606    if !payload_matches_projection(&envelope.payload, &trusted.receipt) {
607        return Ok(ChangeSetAssessmentOutcome::Attention(attention(
608            &envelope,
609            "change_set_authorization_changed",
610            "Folder Scope authority no longer matches the checkout",
611            false,
612            Vec::new(),
613        )));
614    }
615    let version_store = FolderbaseVersionStore::open(root).map_err(capture_operational)?;
616    let retained = match version_store.read_version(&trusted.source_version_id) {
617        Ok(version) => version,
618        Err(_) => {
619            return Ok(ChangeSetAssessmentOutcome::Attention(attention(
620                &envelope,
621                "change_set_stale_base",
622                "trusted source Version is no longer retained",
623                true,
624                Vec::new(),
625            )));
626        }
627    };
628    if retained.canonical_digest().map_err(operational)? != trusted.source_version_sha256 {
629        return Ok(ChangeSetAssessmentOutcome::Attention(attention(
630            &envelope,
631            "change_set_stale_base",
632            "trusted source Version failed exact verification",
633            true,
634            Vec::new(),
635        )));
636    }
637
638    verify_staging(staging, &envelope)?;
639    let current = inventory_source_scope(
640        root,
641        &trusted.receipt.authorized_paths,
642        &trusted.receipt.exclusions,
643    )?;
644    let current_projection_sha256 = scoped_inventory_digest(&current)?;
645    let conflicts = assess_conflicts(&envelope, &trusted.receipt, &current);
646    if conflicts.is_empty() {
647        Ok(ChangeSetAssessmentOutcome::Clean(ChangeSetAssessment {
648            format: "folderbase-change-set-assessment-v1".to_owned(),
649            change_set_sha256: envelope.change_set_sha256,
650            status: "clean".to_owned(),
651            conflicts,
652            current_projection_sha256,
653        }))
654    } else {
655        Ok(ChangeSetAssessmentOutcome::Attention(attention(
656            &envelope,
657            "change_set_conflicted",
658            "Change Set overlaps current source work",
659            false,
660            conflicts,
661        )))
662    }
663}
664
665pub fn apply_change_set(
666    root: impl AsRef<Path>,
667    staging: impl AsRef<Path>,
668    envelope: ChangeSetEnvelope,
669) -> Result<ChangeSetApplyOutcome, ChangeSetError> {
670    let root = root.as_ref();
671    let staging = staging.as_ref();
672    validate_change_set_envelope(&envelope)?;
673    let attestation = attest_folderbase_root(root).map_err(operational)?;
674    if attestation.folderbase_id != envelope.payload.folderbase_id {
675        return Err(invalid(
676            "change_set_root_mismatch",
677            "Change Set belongs to a different Folderbase",
678        ));
679    }
680
681    // Replay is resolved before three-way assessment because the source now
682    // intentionally contains the applied after-state rather than the old
683    // projection base.
684    {
685        let replay_state = FolderbaseState::open_existing(root).map_err(operational)?;
686        for directory in [
687            CHANGE_SET_IDS_DIRECTORY,
688            APPLIED_CHANGE_SETS_DIRECTORY,
689            CHANGE_SET_TRANSACTIONS_DIRECTORY,
690        ] {
691            replay_state
692                .ensure_private_dir(Path::new(directory))
693                .map_err(operational)?;
694        }
695        let replay_local = LocalVersionStore::open_read_only(root).map_err(operational)?;
696        let _replay_lease = replay_local
697            .acquire_transaction_lock_in(&replay_state)
698            .map_err(operational)?;
699        if let Some(completed) = read_completed_apply(&replay_state, &envelope.change_set_sha256)? {
700            validate_id_binding(&replay_state, &envelope)?;
701            cleanup_completed_change_set(root, &replay_state, &envelope.change_set_sha256)?;
702            return Ok(ChangeSetApplyOutcome::Applied(ChangeSetApplyResult {
703                status: "already_applied".to_owned(),
704                ..completed
705            }));
706        }
707    }
708
709    let trusted_before_apply = read_trusted_projection(root, &envelope.payload.projection_id)?
710        .ok_or_else(|| operational_message("trusted projection disappeared before apply"))?;
711
712    let state = FolderbaseState::open_existing(root).map_err(operational)?;
713    for directory in [
714        CHANGE_SET_IDS_DIRECTORY,
715        APPLIED_CHANGE_SETS_DIRECTORY,
716        CHANGE_SET_TRANSACTIONS_DIRECTORY,
717    ] {
718        state
719            .ensure_private_dir(Path::new(directory))
720            .map_err(operational)?;
721    }
722    let local = LocalVersionStore::open_read_only(root).map_err(operational)?;
723    let lease = local
724        .acquire_transaction_lock_in(&state)
725        .map_err(operational)?;
726
727    if let Some(completed) = read_completed_apply(&state, &envelope.change_set_sha256)? {
728        validate_id_binding(&state, &envelope)?;
729        cleanup_completed_change_set(root, &state, &envelope.change_set_sha256)?;
730        return Ok(ChangeSetApplyOutcome::Applied(ChangeSetApplyResult {
731            status: "already_applied".to_owned(),
732            ..completed
733        }));
734    }
735    bind_change_set_id(&state, &envelope)?;
736
737    let active = read_active_apply(&state)?;
738    let mut resume_published = false;
739    let mut resume_prepared = false;
740    if let Some(active) = active {
741        if active.change_set_sha256 != envelope.change_set_sha256
742            || active.change_set_id != envelope.payload.change_set_id
743        {
744            return Err(operational_message(
745                "another Change Set transaction requires recovery",
746            ));
747        }
748        match active.phase.as_str() {
749            "prepared" => {
750                if workspace_matches_after(root, &envelope)? {
751                    resume_published = true;
752                } else if workspace_is_recoverable_transition(root, &envelope)? {
753                    resume_prepared = true;
754                } else {
755                    return Err(operational_message(
756                        "interrupted Change Set paths contain unrelated changes",
757                    ));
758                }
759            }
760            "published" => {
761                if !workspace_matches_after(root, &envelope)? {
762                    return Err(operational_message(
763                        "published Change Set workspace no longer matches its journal",
764                    ));
765                }
766                resume_published = true;
767            }
768            _ => {
769                return Err(operational_message(
770                    "active Change Set journal has an unknown phase",
771                ));
772            }
773        }
774    }
775
776    let mut projection_result_sha256 = if resume_published {
777        let trusted = read_trusted_projection(root, &envelope.payload.projection_id)?
778            .ok_or_else(|| operational_message("trusted projection disappeared during apply"))?;
779        let current = inventory_source_scope(
780            root,
781            &trusted.receipt.authorized_paths,
782            &trusted.receipt.exclusions,
783        )?;
784        scoped_inventory_digest(&current)?
785    } else {
786        let work = if resume_prepared {
787            reopen_prepared_change_set_work(root, &envelope)?
788        } else {
789            match assess_change_set(root, staging, envelope.clone())? {
790                ChangeSetAssessmentOutcome::Attention(attention) => {
791                    return Ok(ChangeSetApplyOutcome::Attention(attention));
792                }
793                ChangeSetAssessmentOutcome::Clean(_) => {}
794            }
795            let work = prepare_change_set_work(root, staging, &envelope)?;
796            let prepared = ChangeSetApplyJournal {
797                format: "folderbase-change-set-apply-journal-v1".to_owned(),
798                change_set_id: envelope.payload.change_set_id.clone(),
799                change_set_sha256: envelope.change_set_sha256.clone(),
800                projection_id: envelope.payload.projection_id.clone(),
801                phase: "prepared".to_owned(),
802                projection_result_sha256: None,
803            };
804            state
805                .replace(
806                    Path::new(ACTIVE_CHANGE_SET_TRANSACTION),
807                    &encode_pretty_bounded(&prepared, MAX_CHANGE_SET_BYTES)?,
808                )
809                .map_err(operational)?;
810
811            if std::env::var_os("FOLDERBASE_CHANGE_SET_CONFORMANCE_CRASH_AFTER")
812                .is_some_and(|value| value == "prepared-journal")
813            {
814                std::process::exit(86);
815            }
816            work
817        };
818
819        publish_change_set_work(root, &work, &envelope)?;
820        let published = ChangeSetApplyJournal {
821            format: "folderbase-change-set-apply-journal-v1".to_owned(),
822            change_set_id: envelope.payload.change_set_id.clone(),
823            change_set_sha256: envelope.change_set_sha256.clone(),
824            projection_id: envelope.payload.projection_id.clone(),
825            phase: "published".to_owned(),
826            projection_result_sha256: None,
827        };
828        state
829            .replace(
830                Path::new(ACTIVE_CHANGE_SET_TRANSACTION),
831                &encode_pretty_bounded(&published, MAX_CHANGE_SET_BYTES)?,
832            )
833            .map_err(operational)?;
834        String::new()
835    };
836
837    // Keep publication and history in one logical operation. The workspace is
838    // still protected by the durable journal while the shared lease is
839    // released and the existing capture transaction acquires it.
840    drop(lease);
841    let store = FolderbaseVersionStore::open(root).map_err(capture_operational)?;
842    let plan = store.plan_capture().map_err(capture_operational)?;
843    let final_capture = store.seal_capture(plan).map_err(capture_operational)?;
844    let history = store
845        .finalize_change_set_history(
846            &trusted_before_apply.source_version_id,
847            final_capture.version_id(),
848            &envelope.payload.created_at,
849            &envelope.change_set_sha256,
850            &envelope.payload.deltas,
851        )
852        .map_err(capture_operational)?;
853    if std::env::var_os("FOLDERBASE_CHANGE_SET_CONFORMANCE_CRASH_AFTER")
854        .is_some_and(|value| value == "history-head")
855    {
856        std::process::exit(89);
857    }
858    let history_version = store
859        .read_version(history.version_id())
860        .map_err(capture_operational)?;
861    let version_inventory = inventory_version_scope(
862        &history_version,
863        &trusted_before_apply.receipt.authorized_paths,
864        &trusted_before_apply.receipt.exclusions,
865    )?;
866    let history_projection_sha256 = scoped_inventory_digest(&version_inventory)?;
867    if !projection_result_sha256.is_empty() && projection_result_sha256 != history_projection_sha256
868    {
869        return Err(operational_message(
870            "recovered workspace differs from finalized Change Set history",
871        ));
872    }
873    projection_result_sha256 = history_projection_sha256;
874
875    let state = FolderbaseState::open_existing(root).map_err(operational)?;
876    let local = LocalVersionStore::open_read_only(root).map_err(operational)?;
877    let _lease = local
878        .acquire_transaction_lock_in(&state)
879        .map_err(operational)?;
880    let result = ChangeSetApplyResult {
881        format: "folderbase-change-set-apply-result-v1".to_owned(),
882        change_set_sha256: envelope.change_set_sha256.clone(),
883        status: "applied".to_owned(),
884        projection_result_sha256,
885    };
886    let completion_path = applied_change_set_path(&envelope.change_set_sha256);
887    match state.publish_new(
888        &completion_path,
889        &encode_pretty_bounded(&result, MAX_CHANGE_SET_BYTES)?,
890    ) {
891        Ok(()) => {}
892        Err(crate::FolderbaseError::WouldOverwrite(_)) => {
893            let existing = read_completed_apply(&state, &envelope.change_set_sha256)?
894                .ok_or_else(|| operational_message("completion receipt disappeared"))?;
895            if existing != result {
896                return Err(operational_message(
897                    "completion receipt names a different Change Set result",
898                ));
899            }
900        }
901        Err(error) => return Err(operational(error)),
902    }
903    cleanup_completed_change_set(root, &state, &envelope.change_set_sha256)?;
904    Ok(ChangeSetApplyOutcome::Applied(result))
905}
906
907fn bind_change_set_id(
908    state: &FolderbaseState,
909    envelope: &ChangeSetEnvelope,
910) -> Result<(), ChangeSetError> {
911    let binding = ChangeSetIdBinding {
912        format: "folderbase-change-set-id-binding-v1".to_owned(),
913        change_set_id: envelope.payload.change_set_id.clone(),
914        change_set_sha256: envelope.change_set_sha256.clone(),
915    };
916    let path = Path::new(CHANGE_SET_IDS_DIRECTORY)
917        .join(format!("{}.json", envelope.payload.change_set_id));
918    let encoded = encode_pretty_bounded(&binding, MAX_CHANGE_SET_BYTES)?;
919    match state.publish_new(&path, &encoded) {
920        Ok(()) => Ok(()),
921        Err(crate::FolderbaseError::WouldOverwrite(_)) => {
922            let bytes = state
923                .read_bounded(&path, MAX_CHANGE_SET_BYTES)
924                .map_err(operational)?
925                .ok_or_else(|| operational_message("Change Set ID binding disappeared"))?;
926            let existing: ChangeSetIdBinding = serde_json::from_slice(&bytes)
927                .map_err(|error| invalid("change_set_id_reused", error.to_string()))?;
928            if existing == binding {
929                Ok(())
930            } else {
931                Err(invalid(
932                    "change_set_id_reused",
933                    "Change Set ID already names different bytes",
934                ))
935            }
936        }
937        Err(error) => Err(operational(error)),
938    }
939}
940
941fn validate_id_binding(
942    state: &FolderbaseState,
943    envelope: &ChangeSetEnvelope,
944) -> Result<(), ChangeSetError> {
945    let path = Path::new(CHANGE_SET_IDS_DIRECTORY)
946        .join(format!("{}.json", envelope.payload.change_set_id));
947    let bytes = state
948        .read_bounded(&path, MAX_CHANGE_SET_BYTES)
949        .map_err(operational)?
950        .ok_or_else(|| invalid("change_set_id_reused", "Change Set ID binding is missing"))?;
951    let binding: ChangeSetIdBinding = serde_json::from_slice(&bytes)
952        .map_err(|error| invalid("change_set_id_reused", error.to_string()))?;
953    if binding.change_set_sha256 != envelope.change_set_sha256 {
954        return Err(invalid(
955            "change_set_id_reused",
956            "Change Set ID already names different bytes",
957        ));
958    }
959    Ok(())
960}
961
962fn read_active_apply(
963    state: &FolderbaseState,
964) -> Result<Option<ChangeSetApplyJournal>, ChangeSetError> {
965    state
966        .read_bounded_if_present(
967            Path::new(ACTIVE_CHANGE_SET_TRANSACTION),
968            MAX_CHANGE_SET_BYTES,
969        )
970        .map_err(operational)?
971        .map(|bytes| {
972            serde_json::from_slice(&bytes)
973                .map_err(|error| operational_message(format!("invalid apply journal: {error}")))
974        })
975        .transpose()
976}
977
978fn read_completed_apply(
979    state: &FolderbaseState,
980    digest: &str,
981) -> Result<Option<ChangeSetApplyResult>, ChangeSetError> {
982    state
983        .read_bounded_if_present(&applied_change_set_path(digest), MAX_CHANGE_SET_BYTES)
984        .map_err(operational)?
985        .map(|bytes| {
986            serde_json::from_slice(&bytes).map_err(|error| {
987                operational_message(format!("invalid apply completion receipt: {error}"))
988            })
989        })
990        .transpose()
991}
992
993fn applied_change_set_path(digest: &str) -> PathBuf {
994    Path::new(APPLIED_CHANGE_SETS_DIRECTORY).join(format!("{digest}.json"))
995}
996
997fn cleanup_completed_change_set(
998    root: &Path,
999    state: &FolderbaseState,
1000    digest: &str,
1001) -> Result<(), ChangeSetError> {
1002    let work = change_set_work_directory(root, digest);
1003    match fs::symlink_metadata(&work) {
1004        Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {
1005            fs::remove_dir_all(&work).map_err(operational)?;
1006        }
1007        Ok(_) => return Err(operational_message("Change Set work path is unsafe")),
1008        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1009        Err(error) => return Err(operational(error)),
1010    }
1011    if read_active_apply(state)?.is_some_and(|active| active.change_set_sha256 == digest) {
1012        state
1013            .remove_durable(Path::new(ACTIVE_CHANGE_SET_TRANSACTION))
1014            .map_err(operational)?;
1015    }
1016    Ok(())
1017}
1018
1019#[derive(Debug)]
1020struct PreparedChangeSetWork {
1021    directory: PathBuf,
1022    regular_files: BTreeMap<String, PathBuf>,
1023}
1024
1025fn change_set_work_directory(root: &Path, digest: &str) -> PathBuf {
1026    root.join(CHANGE_SET_TRANSACTIONS_DIRECTORY)
1027        .join(format!("work-{digest}"))
1028}
1029
1030fn reopen_prepared_change_set_work(
1031    root: &Path,
1032    envelope: &ChangeSetEnvelope,
1033) -> Result<PreparedChangeSetWork, ChangeSetError> {
1034    let directory = change_set_work_directory(root, &envelope.change_set_sha256);
1035    let metadata = fs::symlink_metadata(&directory).map_err(operational)?;
1036    if !metadata.is_dir() || metadata.file_type().is_symlink() {
1037        return Err(operational_message("Change Set prepared work is unsafe"));
1038    }
1039    let mut regular_files = BTreeMap::new();
1040    for delta in &envelope.payload.deltas {
1041        let Some(DeltaState::RegularFile(after)) = &delta.after else {
1042            continue;
1043        };
1044        let unchanged_move = matches!(after.content, ContentReference::ProjectionBase(_))
1045            && delta.before.as_ref().is_some_and(|before| {
1046                before.path() != after.path && before.kind() == InventoryKind::RegularFile
1047            });
1048        if unchanged_move {
1049            continue;
1050        }
1051        let prepared = directory.join(&delta.object_id);
1052        let metadata = fs::symlink_metadata(&prepared).map_err(operational)?;
1053        if !metadata.is_file() || metadata.file_type().is_symlink() {
1054            return Err(operational_message(
1055                "Change Set prepared regular file is unsafe",
1056            ));
1057        }
1058        regular_files.insert(delta.object_id.clone(), prepared);
1059    }
1060    Ok(PreparedChangeSetWork {
1061        directory,
1062        regular_files,
1063    })
1064}
1065
1066fn prepare_change_set_work(
1067    root: &Path,
1068    staging: &Path,
1069    envelope: &ChangeSetEnvelope,
1070) -> Result<PreparedChangeSetWork, ChangeSetError> {
1071    let directory = change_set_work_directory(root, &envelope.change_set_sha256);
1072    match fs::symlink_metadata(&directory) {
1073        Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {
1074            fs::remove_dir_all(&directory).map_err(operational)?;
1075        }
1076        Ok(_) => return Err(operational_message("Change Set work path is unsafe")),
1077        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1078        Err(error) => return Err(operational(error)),
1079    }
1080    fs::create_dir(&directory).map_err(operational)?;
1081    let mut regular_files = BTreeMap::new();
1082    for delta in &envelope.payload.deltas {
1083        let Some(DeltaState::RegularFile(after)) = &delta.after else {
1084            continue;
1085        };
1086        let unchanged_move = matches!(after.content, ContentReference::ProjectionBase(_))
1087            && delta.before.as_ref().is_some_and(|before| {
1088                before.path() != after.path && before.kind() == InventoryKind::RegularFile
1089            });
1090        if unchanged_move {
1091            continue;
1092        }
1093        let target = directory.join(&delta.object_id);
1094        match &after.content {
1095            ContentReference::ProjectionBase(_) => {
1096                let before = match &delta.before {
1097                    Some(DeltaState::RegularFile(before)) => before,
1098                    _ => {
1099                        return Err(invalid(
1100                            "invalid_change_set_input",
1101                            "projection-base bytes have no regular-file before state",
1102                        ));
1103                    }
1104                };
1105                copy_regular_verified(
1106                    &resolve_portable(root, &before.path)?,
1107                    &target,
1108                    &after.content_sha256,
1109                    after.bytes,
1110                    after.executable,
1111                )?;
1112            }
1113            ContentReference::Staged(reference) => {
1114                materialize_staged_regular(staging, reference, &target, after)?;
1115            }
1116        }
1117        regular_files.insert(delta.object_id.clone(), target);
1118    }
1119    sync_directory(&directory)?;
1120    Ok(PreparedChangeSetWork {
1121        directory,
1122        regular_files,
1123    })
1124}
1125
1126fn materialize_staged_regular(
1127    staging: &Path,
1128    reference: &StagedContent,
1129    target: &Path,
1130    expected: &DeltaRegularFile,
1131) -> Result<(), ChangeSetError> {
1132    let manifest_path = staging
1133        .join("manifests")
1134        .join(format!("{}.json", reference.chunk_manifest_sha256));
1135    let manifest = ChunkManifest::decode_bounded(File::open(manifest_path).map_err(operational)?)
1136        .map_err(|error| invalid("invalid_staging", error.to_string()))?;
1137    if manifest.object_sha256 != expected.content_sha256
1138        || manifest.object_bytes != expected.bytes
1139        || manifest.canonical_digest().map_err(operational)? != reference.chunk_manifest_sha256
1140    {
1141        return Err(invalid(
1142            "invalid_staging",
1143            "staged object does not match Change Set after-state",
1144        ));
1145    }
1146    let mut options = OpenOptions::new();
1147    options.write(true).create_new(true);
1148    let mut output = options.open(target).map_err(operational)?;
1149    for chunk in &manifest.chunks {
1150        let mut input =
1151            File::open(staging.join("chunks").join(&chunk.sha256)).map_err(operational)?;
1152        std::io::copy(&mut input, &mut output).map_err(operational)?;
1153    }
1154    output.sync_all().map_err(operational)?;
1155    verify_regular_digest(target, expected.bytes, &expected.content_sha256)?;
1156    set_executable(target, expected.executable)
1157}
1158
1159fn publish_change_set_work(
1160    root: &Path,
1161    work: &PreparedChangeSetWork,
1162    envelope: &ChangeSetEnvelope,
1163) -> Result<(), ChangeSetError> {
1164    // Preserve filesystem identity for true moves. Folderbase capture uses
1165    // that physical continuity to retain the stable Object ID across paths.
1166    let mut moves = envelope
1167        .payload
1168        .deltas
1169        .iter()
1170        .filter_map(|delta| match (&delta.before, &delta.after) {
1171            (Some(before), Some(after))
1172                if before.path() != after.path() && before.kind() == after.kind() =>
1173            {
1174                Some((before.path().to_owned(), after.path().to_owned()))
1175            }
1176            _ => None,
1177        })
1178        .collect::<Vec<_>>();
1179    moves.sort_by(|left, right| {
1180        left.0
1181            .split('/')
1182            .count()
1183            .cmp(&right.0.split('/').count())
1184            .then_with(|| left.0.as_bytes().cmp(right.0.as_bytes()))
1185    });
1186    for (before, after) in &moves {
1187        let source = resolve_portable(root, before)?;
1188        let destination = resolve_portable(root, after)?;
1189        let source_exists = fs::symlink_metadata(&source).is_ok();
1190        let destination_exists = fs::symlink_metadata(&destination).is_ok();
1191        match (source_exists, destination_exists) {
1192            (true, false) => {
1193                if let Some(parent) = destination.parent() {
1194                    fs::create_dir_all(parent).map_err(operational)?;
1195                }
1196                fs::rename(source, destination).map_err(operational)?;
1197                crash_after_first_mutation_if_requested();
1198            }
1199            (false, true) => {}
1200            _ => {
1201                return Err(operational_message(
1202                    "Change Set move is not in a recoverable state",
1203                ));
1204            }
1205        }
1206    }
1207    let moved_from = moves
1208        .iter()
1209        .map(|(before, _)| before.as_str())
1210        .collect::<BTreeSet<_>>();
1211    let mut removals = envelope
1212        .payload
1213        .deltas
1214        .iter()
1215        .filter_map(|delta| {
1216            let before = delta.before.as_ref()?;
1217            if moved_from.contains(before.path())
1218                || (delta
1219                    .after
1220                    .as_ref()
1221                    .is_some_and(|after| after.path() == before.path())
1222                    && matches!(before, DeltaState::Directory(_)))
1223            {
1224                None
1225            } else {
1226                Some(before.path().to_owned())
1227            }
1228        })
1229        .collect::<Vec<_>>();
1230    removals.sort_by(|left, right| {
1231        right
1232            .split('/')
1233            .count()
1234            .cmp(&left.split('/').count())
1235            .then_with(|| right.as_bytes().cmp(left.as_bytes()))
1236    });
1237    for path in removals {
1238        if remove_workspace_path(&resolve_portable(root, &path)?)? {
1239            crash_after_first_mutation_if_requested();
1240        }
1241    }
1242
1243    let mut directories = envelope
1244        .payload
1245        .deltas
1246        .iter()
1247        .filter_map(|delta| match &delta.after {
1248            Some(DeltaState::Directory(value)) => Some(value.path.clone()),
1249            _ => None,
1250        })
1251        .collect::<Vec<_>>();
1252    directories.sort_by(|left, right| {
1253        left.split('/')
1254            .count()
1255            .cmp(&right.split('/').count())
1256            .then_with(|| left.as_bytes().cmp(right.as_bytes()))
1257    });
1258    for path in directories {
1259        let directory = resolve_portable(root, &path)?;
1260        let existed = fs::symlink_metadata(&directory).is_ok();
1261        fs::create_dir_all(directory).map_err(operational)?;
1262        if !existed {
1263            crash_after_first_mutation_if_requested();
1264        }
1265    }
1266
1267    for delta in &envelope.payload.deltas {
1268        let Some(after) = &delta.after else {
1269            continue;
1270        };
1271        match after {
1272            DeltaState::Directory(_) => {}
1273            DeltaState::RegularFile(value) => {
1274                let target = resolve_portable(root, &value.path)?;
1275                let moved = delta.before.as_ref().is_some_and(|before| {
1276                    before.path() != value.path && before.kind() == InventoryKind::RegularFile
1277                });
1278                let bytes_unchanged = matches!(value.content, ContentReference::ProjectionBase(_));
1279                if moved && bytes_unchanged {
1280                    verify_regular_digest(&target, value.bytes, &value.content_sha256)?;
1281                    set_executable(&target, value.executable)?;
1282                    crash_after_first_mutation_if_requested();
1283                } else if moved {
1284                    let source = work.regular_files.get(&delta.object_id).ok_or_else(|| {
1285                        operational_message("prepared regular-file replacement is missing")
1286                    })?;
1287                    mark_in_place_mutation(work, &delta.object_id, &envelope.change_set_sha256)?;
1288                    overwrite_regular_in_place(
1289                        source,
1290                        &target,
1291                        &value.content_sha256,
1292                        value.bytes,
1293                        value.executable,
1294                    )?;
1295                    clear_in_place_mutation(work, &delta.object_id)?;
1296                    crash_after_first_mutation_if_requested();
1297                } else {
1298                    let source = work.regular_files.get(&delta.object_id).ok_or_else(|| {
1299                        operational_message("prepared regular-file replacement is missing")
1300                    })?;
1301                    if install_regular_atomic(
1302                        source,
1303                        &target,
1304                        &value.content_sha256,
1305                        value.bytes,
1306                        value.executable,
1307                    )? {
1308                        crash_after_first_mutation_if_requested();
1309                    }
1310                }
1311            }
1312            DeltaState::Symlink(value) => {
1313                if ensure_symlink(root, &value.path, &value.target)? {
1314                    crash_after_first_mutation_if_requested();
1315                }
1316            }
1317        }
1318    }
1319    Ok(())
1320}
1321
1322fn in_place_mutation_marker(work: &PreparedChangeSetWork, object_id: &str) -> PathBuf {
1323    work.directory.join(format!("mutating-{object_id}"))
1324}
1325
1326fn mark_in_place_mutation(
1327    work: &PreparedChangeSetWork,
1328    object_id: &str,
1329    change_set_sha256: &str,
1330) -> Result<(), ChangeSetError> {
1331    let marker = in_place_mutation_marker(work, object_id);
1332    let expected = format!("{change_set_sha256}\n");
1333    match fs::symlink_metadata(&marker) {
1334        Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
1335            let mut contents = String::new();
1336            File::open(&marker)
1337                .and_then(|mut file| file.read_to_string(&mut contents))
1338                .map_err(operational)?;
1339            if contents != expected {
1340                return Err(operational_message(
1341                    "Change Set in-place recovery marker is invalid",
1342                ));
1343            }
1344        }
1345        Ok(_) => {
1346            return Err(operational_message(
1347                "Change Set in-place recovery marker is unsafe",
1348            ));
1349        }
1350        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1351            create_new_file(&marker, expected.as_bytes())?;
1352            sync_directory(marker.parent().expect("marker has parent"))?;
1353        }
1354        Err(error) => return Err(operational(error)),
1355    }
1356    Ok(())
1357}
1358
1359fn clear_in_place_mutation(
1360    work: &PreparedChangeSetWork,
1361    object_id: &str,
1362) -> Result<(), ChangeSetError> {
1363    let marker = in_place_mutation_marker(work, object_id);
1364    match fs::remove_file(&marker) {
1365        Ok(()) => sync_directory(marker.parent().expect("marker has parent")),
1366        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1367        Err(error) => Err(operational(error)),
1368    }
1369}
1370
1371fn overwrite_regular_in_place(
1372    source: &Path,
1373    target: &Path,
1374    expected_sha256: &str,
1375    expected_bytes: u64,
1376    executable: bool,
1377) -> Result<(), ChangeSetError> {
1378    let metadata = fs::symlink_metadata(target).map_err(operational)?;
1379    if !metadata.is_file() || metadata.file_type().is_symlink() {
1380        return Err(operational_message("moved regular-file target is unsafe"));
1381    }
1382    let mut input = File::open(source).map_err(operational)?;
1383    let mut output = OpenOptions::new()
1384        .write(true)
1385        .truncate(true)
1386        .open(target)
1387        .map_err(operational)?;
1388    if std::env::var_os("FOLDERBASE_CHANGE_SET_CONFORMANCE_CRASH_AFTER")
1389        .is_some_and(|value| value == "in-place-write")
1390    {
1391        let mut byte = [0_u8; 1];
1392        let read = input.read(&mut byte).map_err(operational)?;
1393        if read > 0 {
1394            output.write_all(&byte[..read]).map_err(operational)?;
1395        }
1396        output.sync_all().map_err(operational)?;
1397        std::process::exit(88);
1398    }
1399    std::io::copy(&mut input, &mut output).map_err(operational)?;
1400    output.sync_all().map_err(operational)?;
1401    verify_regular_digest(target, expected_bytes, expected_sha256)?;
1402    set_executable(target, executable)
1403}
1404
1405fn remove_workspace_path(path: &Path) -> Result<bool, ChangeSetError> {
1406    match fs::symlink_metadata(path) {
1407        Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {
1408            fs::remove_dir(path).map_err(operational)?;
1409            Ok(true)
1410        }
1411        Ok(_) => {
1412            fs::remove_file(path).map_err(operational)?;
1413            Ok(true)
1414        }
1415        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1416        Err(error) => Err(operational(error)),
1417    }
1418}
1419
1420fn install_regular_atomic(
1421    source: &Path,
1422    target: &Path,
1423    expected_sha256: &str,
1424    expected_bytes: u64,
1425    executable: bool,
1426) -> Result<bool, ChangeSetError> {
1427    match fs::symlink_metadata(target) {
1428        Ok(metadata)
1429            if metadata.is_file()
1430                && !metadata.file_type().is_symlink()
1431                && metadata.len() == expected_bytes
1432                && is_executable(&metadata) == executable
1433                && sha256_regular(target, expected_bytes)? == expected_sha256 =>
1434        {
1435            return Ok(false);
1436        }
1437        Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
1438            fs::remove_file(target).map_err(operational)?;
1439        }
1440        Ok(_) => {
1441            return Err(operational_message(
1442                "Change Set regular-file target is unsafe",
1443            ));
1444        }
1445        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1446        Err(error) => return Err(operational(error)),
1447    }
1448    let parent = target
1449        .parent()
1450        .ok_or_else(|| operational_message("regular-file target has no parent"))?;
1451    fs::create_dir_all(parent).map_err(operational)?;
1452    let temporary = parent.join(format!(".folderbase-change-set-{}.tmp", Uuid::now_v7()));
1453    copy_regular_verified(
1454        source,
1455        &temporary,
1456        expected_sha256,
1457        expected_bytes,
1458        executable,
1459    )?;
1460    fs::rename(&temporary, target).map_err(operational)?;
1461    Ok(true)
1462}
1463
1464fn ensure_symlink(root: &Path, path: &str, expected_target: &str) -> Result<bool, ChangeSetError> {
1465    let target = resolve_portable(root, path)?;
1466    match fs::symlink_metadata(&target) {
1467        Ok(metadata) if metadata.file_type().is_symlink() => {
1468            if fs::read_link(&target)
1469                .map_err(operational)?
1470                .to_string_lossy()
1471                == expected_target
1472            {
1473                return Ok(false);
1474            }
1475            fs::remove_file(&target).map_err(operational)?;
1476        }
1477        Ok(metadata) if metadata.is_file() => {
1478            fs::remove_file(&target).map_err(operational)?;
1479        }
1480        Ok(_) => {
1481            return Err(operational_message("Change Set symlink target is unsafe"));
1482        }
1483        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1484        Err(error) => return Err(operational(error)),
1485    }
1486    materialize_symlink(root, path, expected_target)?;
1487    Ok(true)
1488}
1489
1490fn crash_after_first_mutation_if_requested() {
1491    if std::env::var_os("FOLDERBASE_CHANGE_SET_CONFORMANCE_CRASH_AFTER")
1492        .is_some_and(|value| value == "first-mutation")
1493    {
1494        std::process::exit(87);
1495    }
1496}
1497
1498fn workspace_is_recoverable_transition(
1499    root: &Path,
1500    envelope: &ChangeSetEnvelope,
1501) -> Result<bool, ChangeSetError> {
1502    for delta in &envelope.payload.deltas {
1503        match (&delta.before, &delta.after) {
1504            (Some(before), Some(after)) if before.path() == after.path() => {
1505                let path = before.path();
1506                if path_exists_nofollow(root, path)?
1507                    && !workspace_state_matches(root, before)?
1508                    && !workspace_state_matches(root, after)?
1509                {
1510                    return Ok(false);
1511                }
1512            }
1513            (Some(before), Some(after)) => {
1514                let source_matches = workspace_state_matches(root, before)?;
1515                let source_absent = !path_exists_nofollow(root, before.path())?;
1516                let destination_absent = !path_exists_nofollow(root, after.path())?;
1517                let destination_matches_before =
1518                    workspace_state_matches_at(root, before, after.path())?;
1519                let destination_matches_after = workspace_state_matches(root, after)?;
1520                let interrupted_in_place = source_absent
1521                    && matches!(after, DeltaState::RegularFile(_))
1522                    && regular_file_exists_nofollow(root, after.path())?
1523                    && valid_in_place_mutation_marker(root, envelope, &delta.object_id)?;
1524                let valid = (source_matches && destination_absent)
1525                    || (source_absent
1526                        && (destination_matches_before
1527                            || destination_matches_after
1528                            || interrupted_in_place));
1529                if !valid {
1530                    return Ok(false);
1531                }
1532            }
1533            (Some(before), None) => {
1534                if path_exists_nofollow(root, before.path())?
1535                    && !workspace_state_matches(root, before)?
1536                {
1537                    return Ok(false);
1538                }
1539            }
1540            (None, Some(after)) => {
1541                if path_exists_nofollow(root, after.path())?
1542                    && !workspace_state_matches(root, after)?
1543                {
1544                    return Ok(false);
1545                }
1546            }
1547            (None, None) => return Ok(false),
1548        }
1549    }
1550    Ok(true)
1551}
1552
1553fn path_exists_nofollow(root: &Path, path: &str) -> Result<bool, ChangeSetError> {
1554    match fs::symlink_metadata(resolve_portable(root, path)?) {
1555        Ok(_) => Ok(true),
1556        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1557        Err(error) => Err(operational(error)),
1558    }
1559}
1560
1561fn regular_file_exists_nofollow(root: &Path, path: &str) -> Result<bool, ChangeSetError> {
1562    match fs::symlink_metadata(resolve_portable(root, path)?) {
1563        Ok(metadata) => Ok(metadata.is_file() && !metadata.file_type().is_symlink()),
1564        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1565        Err(error) => Err(operational(error)),
1566    }
1567}
1568
1569fn valid_in_place_mutation_marker(
1570    root: &Path,
1571    envelope: &ChangeSetEnvelope,
1572    object_id: &str,
1573) -> Result<bool, ChangeSetError> {
1574    let marker = change_set_work_directory(root, &envelope.change_set_sha256)
1575        .join(format!("mutating-{object_id}"));
1576    let metadata = match fs::symlink_metadata(&marker) {
1577        Ok(metadata) => metadata,
1578        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1579        Err(error) => return Err(operational(error)),
1580    };
1581    if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 65 {
1582        return Ok(false);
1583    }
1584    let mut contents = String::new();
1585    File::open(marker)
1586        .and_then(|mut file| file.read_to_string(&mut contents))
1587        .map_err(operational)?;
1588    Ok(contents == format!("{}\n", envelope.change_set_sha256))
1589}
1590
1591fn workspace_matches_after(
1592    root: &Path,
1593    envelope: &ChangeSetEnvelope,
1594) -> Result<bool, ChangeSetError> {
1595    for delta in &envelope.payload.deltas {
1596        match &delta.after {
1597            Some(after) if !workspace_state_matches(root, after)? => return Ok(false),
1598            None => {
1599                if let Some(before) = &delta.before
1600                    && fs::symlink_metadata(resolve_portable(root, before.path())?).is_ok()
1601                {
1602                    return Ok(false);
1603                }
1604            }
1605            _ => {}
1606        }
1607        if let (Some(before), Some(after)) = (&delta.before, &delta.after)
1608            && before.path() != after.path()
1609            && fs::symlink_metadata(resolve_portable(root, before.path())?).is_ok()
1610        {
1611            return Ok(false);
1612        }
1613    }
1614    Ok(true)
1615}
1616
1617fn workspace_state_matches(root: &Path, state: &DeltaState) -> Result<bool, ChangeSetError> {
1618    workspace_state_matches_at(root, state, state.path())
1619}
1620
1621fn workspace_state_matches_at(
1622    root: &Path,
1623    state: &DeltaState,
1624    path: &str,
1625) -> Result<bool, ChangeSetError> {
1626    let path = resolve_portable(root, path)?;
1627    let Ok(metadata) = fs::symlink_metadata(&path) else {
1628        return Ok(false);
1629    };
1630    Ok(match state {
1631        DeltaState::Directory(_) => metadata.is_dir() && !metadata.file_type().is_symlink(),
1632        DeltaState::RegularFile(value) => {
1633            metadata.is_file()
1634                && !metadata.file_type().is_symlink()
1635                && metadata.len() == value.bytes
1636                && is_executable(&metadata) == value.executable
1637                && sha256_regular(&path, value.bytes)? == value.content_sha256
1638        }
1639        DeltaState::Symlink(value) => {
1640            metadata.file_type().is_symlink()
1641                && fs::read_link(path).map_err(operational)?.to_string_lossy() == value.target
1642        }
1643    })
1644}
1645
1646fn attention(
1647    envelope: &ChangeSetEnvelope,
1648    code: &str,
1649    message: &str,
1650    retryable: bool,
1651    conflicts: Vec<ChangeSetConflict>,
1652) -> ChangeSetAttention {
1653    ChangeSetAttention {
1654        format: "folderbase-change-set-attention-v1".to_owned(),
1655        change_set_sha256: envelope.change_set_sha256.clone(),
1656        attention: ChangeSetAttentionDetail {
1657            code: code.to_owned(),
1658            message: message.to_owned(),
1659            retryable,
1660            conflicts,
1661        },
1662    }
1663}
1664
1665fn validate_change_set_envelope(envelope: &ChangeSetEnvelope) -> Result<(), ChangeSetError> {
1666    let payload = &envelope.payload;
1667    if envelope.format != "folderbase-change-set-v1"
1668        || payload.format != "folderbase-change-set-payload-v1"
1669        || !valid_prefixed_uuid(&payload.change_set_id, "changeset_")
1670        || !valid_prefixed_uuid(&payload.checkout_id, "checkout_")
1671        || !valid_prefixed_uuid(&payload.folderbase_id, "folderbase_")
1672        || !valid_prefixed_uuid(&payload.projection_id, "projection_")
1673        || !valid_prefixed_uuid(&payload.folder_scope_id, "folderscope_")
1674        || !is_sha256(&payload.scope_revision_sha256)
1675        || !is_sha256(&payload.projection_base_sha256)
1676        || payload.permission != "can_work"
1677        || payload.deltas.is_empty()
1678        || payload.deltas.len() > MAX_CHANGE_SET_ENTRIES
1679        || change_set_digest(payload)? != envelope.change_set_sha256
1680    {
1681        return Err(invalid(
1682            "invalid_change_set_input",
1683            "Change Set envelope violates the closed v1 contract",
1684        ));
1685    }
1686    let request = CheckoutRequest {
1687        format: "folderbase-checkout-request-v1".to_owned(),
1688        folderbase_id: payload.folderbase_id.clone(),
1689        projection_id: payload.projection_id.clone(),
1690        folder_scope_id: payload.folder_scope_id.clone(),
1691        scope_revision_sha256: payload.scope_revision_sha256.clone(),
1692        permission: payload.permission.clone(),
1693        authorized_paths: payload.authorized_paths.clone(),
1694    };
1695    validate_checkout_request(&request)?;
1696    let mut previous = None;
1697    let mut final_paths = Vec::new();
1698    for delta in &payload.deltas {
1699        if !valid_prefixed_uuid(&delta.object_id, "obj_")
1700            || previous.is_some_and(|prior: &str| prior.as_bytes() >= delta.object_id.as_bytes())
1701            || (delta.before.is_none() && delta.after.is_none())
1702            || delta.before == delta.after
1703        {
1704            return Err(invalid(
1705                "invalid_change_set_input",
1706                "Change Set deltas are not canonical",
1707            ));
1708        }
1709        previous = Some(delta.object_id.as_str());
1710        for state in [&delta.before, &delta.after].into_iter().flatten() {
1711            validate_delta_state(state, &payload.authorized_paths)?;
1712        }
1713        if let Some(after) = &delta.after {
1714            final_paths.push(after.path().to_owned());
1715            if delta.before.is_none()
1716                && matches!(
1717                    after,
1718                    DeltaState::RegularFile(DeltaRegularFile {
1719                        content: ContentReference::ProjectionBase(_),
1720                        ..
1721                    })
1722                )
1723            {
1724                return Err(invalid(
1725                    "invalid_change_set_input",
1726                    "created regular-file bytes must be staged",
1727                ));
1728            }
1729        }
1730    }
1731    reject_path_collisions(&final_paths, "invalid_change_set_input")?;
1732    Ok(())
1733}
1734
1735fn validate_delta_state(
1736    state: &DeltaState,
1737    authorized: &[AuthorizedPath],
1738) -> Result<(), ChangeSetError> {
1739    validate_portable_path(state.path())?;
1740    if !is_authorized(state.path(), authorized) {
1741        return Err(invalid(
1742            "invalid_change_set_input",
1743            "Change Set path exceeds the authorized Folder Scope",
1744        ));
1745    }
1746    match state {
1747        DeltaState::Directory(value) if value.kind == "directory" => Ok(()),
1748        DeltaState::RegularFile(value)
1749            if value.kind == "regular_file"
1750                && valid_prefixed_uuid(&value.object_version_id, "version_")
1751                && is_sha256(&value.content_sha256)
1752                && value.bytes <= MAX_OBJECT_BYTES =>
1753        {
1754            match &value.content {
1755                ContentReference::ProjectionBase(value) if value.source == "projection_base" => {
1756                    Ok(())
1757                }
1758                ContentReference::Staged(value)
1759                    if value.source == "staged"
1760                        && valid_prefixed_uuid(&value.staging_id, "staging_")
1761                        && is_sha256(&value.chunk_manifest_sha256) =>
1762                {
1763                    Ok(())
1764                }
1765                _ => Err(invalid(
1766                    "invalid_change_set_input",
1767                    "regular-file content reference is invalid",
1768                )),
1769            }
1770        }
1771        DeltaState::Symlink(value)
1772            if value.kind == "symlink"
1773                && valid_prefixed_uuid(&value.object_version_id, "version_")
1774                && value.target_safety == "relative-within-projection" =>
1775        {
1776            validate_safe_symlink_target(&value.path, &value.target)
1777        }
1778        _ => Err(invalid(
1779            "invalid_change_set_input",
1780            "delta state violates the closed v1 contract",
1781        )),
1782    }
1783}
1784
1785fn read_trusted_projection(
1786    root: &Path,
1787    projection_id: &str,
1788) -> Result<Option<TrustedProjection>, ChangeSetError> {
1789    let state = FolderbaseState::open_existing_read_only(root).map_err(operational)?;
1790    let relative = Path::new(PROJECTIONS_DIRECTORY).join(format!("{projection_id}.json"));
1791    let Some(bytes) = state
1792        .read_bounded_if_present(&relative, MAX_PROJECTION_RECORD_BYTES)
1793        .map_err(operational)?
1794    else {
1795        return Ok(None);
1796    };
1797    let trusted: TrustedProjection = serde_json::from_slice(&bytes)
1798        .map_err(|error| invalid("invalid_projection_receipt", error.to_string()))?;
1799    if trusted.format != "folderbase-trusted-projection-v1"
1800        || trusted.receipt.projection_id != projection_id
1801        || !valid_prefixed_uuid(&trusted.source_version_id, "fbversion_")
1802        || !is_sha256(&trusted.source_version_sha256)
1803    {
1804        return Err(invalid(
1805            "invalid_projection_receipt",
1806            "trusted projection mapping is invalid",
1807        ));
1808    }
1809    validate_receipt(&trusted.receipt)?;
1810    Ok(Some(trusted))
1811}
1812
1813fn payload_matches_projection(payload: &ChangeSetPayload, receipt: &CheckoutReceipt) -> bool {
1814    payload.checkout_id == receipt.checkout_id
1815        && payload.folderbase_id == receipt.folderbase_id
1816        && payload.projection_id == receipt.projection_id
1817        && payload.folder_scope_id == receipt.folder_scope_id
1818        && payload.scope_revision_sha256 == receipt.scope_revision_sha256
1819        && payload.permission == receipt.permission
1820        && payload.authorized_paths == receipt.authorized_paths
1821        && payload.projection_base_sha256 == receipt.projection_base_sha256
1822}
1823
1824fn inventory_source_scope(
1825    root: &Path,
1826    authorized: &[AuthorizedPath],
1827    exclusions: &[ProjectionExclusion],
1828) -> Result<Vec<InventoryEntry>, ChangeSetError> {
1829    let mut entries = Vec::new();
1830    let nested = exclusions
1831        .iter()
1832        .filter(|exclusion| exclusion.reason == "nested-folderbase-boundary")
1833        .map(|exclusion| exclusion.path.as_str())
1834        .collect::<BTreeSet<_>>();
1835    if authorized.len() == 1 && authorized[0].path_prefix.is_none() {
1836        inventory_scoped_directory(root, "", &nested, &mut entries)?;
1837    } else {
1838        for scope in authorized {
1839            let prefix = scope.path_prefix.as_deref().expect("non-root scope");
1840            let path = resolve_portable(root, prefix)?;
1841            let Ok(metadata) = fs::symlink_metadata(&path) else {
1842                continue;
1843            };
1844            if nested.contains(prefix) {
1845                continue;
1846            }
1847            inventory_scoped_node(root, prefix, &path, &metadata, &nested, &mut entries)?;
1848        }
1849    }
1850    entries.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
1851    reject_inventory_collisions(&entries)?;
1852    Ok(entries)
1853}
1854
1855fn inventory_version_scope(
1856    version: &FolderbaseVersion,
1857    authorized: &[AuthorizedPath],
1858    exclusions: &[ProjectionExclusion],
1859) -> Result<Vec<InventoryEntry>, ChangeSetError> {
1860    let nested = exclusions
1861        .iter()
1862        .filter(|exclusion| exclusion.reason == "nested-folderbase-boundary")
1863        .map(|exclusion| exclusion.path.as_str())
1864        .collect::<Vec<_>>();
1865    let mut entries = version
1866        .bindings()
1867        .iter()
1868        .filter(|binding| is_authorized(binding.path(), authorized))
1869        .filter(|binding| {
1870            !nested
1871                .iter()
1872                .any(|boundary| is_same_or_descendant(binding.path(), boundary))
1873        })
1874        .map(projected_entry)
1875        .collect::<Result<Vec<_>, _>>()?
1876        .iter()
1877        .map(InventoryEntry::from_projected)
1878        .collect::<Vec<_>>();
1879    entries.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
1880    reject_inventory_collisions(&entries)?;
1881    Ok(entries)
1882}
1883
1884fn inventory_scoped_directory(
1885    root: &Path,
1886    prefix: &str,
1887    nested: &BTreeSet<&str>,
1888    entries: &mut Vec<InventoryEntry>,
1889) -> Result<(), ChangeSetError> {
1890    let directory = if prefix.is_empty() {
1891        root.to_path_buf()
1892    } else {
1893        resolve_portable(root, prefix)?
1894    };
1895    let mut children = fs::read_dir(&directory)
1896        .map_err(operational)?
1897        .collect::<Result<Vec<_>, _>>()
1898        .map_err(operational)?;
1899    children.sort_by(|left, right| {
1900        left.file_name()
1901            .as_encoded_bytes()
1902            .cmp(right.file_name().as_encoded_bytes())
1903    });
1904    for child in children {
1905        let name = child
1906            .file_name()
1907            .into_string()
1908            .map_err(|_| invalid("invalid_change_set_input", "source path is not UTF-8"))?;
1909        let path = if prefix.is_empty() {
1910            name
1911        } else {
1912            format!("{prefix}/{name}")
1913        };
1914        if path == ".folderbase" || nested.contains(path.as_str()) {
1915            continue;
1916        }
1917        let metadata = fs::symlink_metadata(child.path()).map_err(operational)?;
1918        inventory_scoped_node(root, &path, &child.path(), &metadata, nested, entries)?;
1919    }
1920    Ok(())
1921}
1922
1923fn inventory_scoped_node(
1924    root: &Path,
1925    path: &str,
1926    absolute: &Path,
1927    metadata: &fs::Metadata,
1928    nested: &BTreeSet<&str>,
1929    entries: &mut Vec<InventoryEntry>,
1930) -> Result<(), ChangeSetError> {
1931    validate_portable_path(path)?;
1932    if entries.len() >= MAX_CHANGE_SET_ENTRIES {
1933        return Err(invalid(
1934            "invalid_change_set_input",
1935            "current scoped inventory exceeds the entry limit",
1936        ));
1937    }
1938    if metadata.is_dir() {
1939        entries.push(InventoryEntry {
1940            path: path.to_owned(),
1941            kind: InventoryKind::Directory,
1942            object_id: None,
1943            object_version_id: None,
1944            content_sha256: None,
1945            bytes: None,
1946            executable: None,
1947            target: None,
1948        });
1949        inventory_scoped_directory(root, path, nested, entries)
1950    } else if metadata.is_file() && !metadata.file_type().is_symlink() {
1951        entries.push(InventoryEntry {
1952            path: path.to_owned(),
1953            kind: InventoryKind::RegularFile,
1954            object_id: None,
1955            object_version_id: None,
1956            content_sha256: Some(sha256_regular(absolute, metadata.len())?),
1957            bytes: Some(metadata.len()),
1958            executable: Some(is_executable(metadata)),
1959            target: None,
1960        });
1961        Ok(())
1962    } else if metadata.file_type().is_symlink() {
1963        let target = fs::read_link(absolute).map_err(operational)?;
1964        let target = target
1965            .to_str()
1966            .ok_or_else(|| invalid("invalid_change_set_input", "symlink target is not UTF-8"))?;
1967        validate_safe_symlink_target(path, target)?;
1968        entries.push(InventoryEntry {
1969            path: path.to_owned(),
1970            kind: InventoryKind::Symlink,
1971            object_id: None,
1972            object_version_id: None,
1973            content_sha256: None,
1974            bytes: None,
1975            executable: None,
1976            target: Some(target.to_owned()),
1977        });
1978        Ok(())
1979    } else {
1980        Err(invalid(
1981            "invalid_change_set_input",
1982            format!("unsupported current source node: {path}"),
1983        ))
1984    }
1985}
1986
1987fn verify_staging(staging: &Path, envelope: &ChangeSetEnvelope) -> Result<(), ChangeSetError> {
1988    let metadata = fs::symlink_metadata(staging).map_err(operational)?;
1989    if !metadata.is_dir() || metadata.file_type().is_symlink() {
1990        return Err(invalid("invalid_staging", "staging root is unsafe"));
1991    }
1992    let index: StagingIndex = read_json_bounded_file(
1993        &staging.join("index.json"),
1994        MAX_CHANGE_SET_BYTES,
1995        "invalid_staging",
1996    )?;
1997    if index.format != "folderbase-change-set-staging-v1" {
1998        return Err(invalid(
1999            "invalid_staging",
2000            "staging index format is invalid",
2001        ));
2002    }
2003    let mut expected = Vec::new();
2004    for delta in &envelope.payload.deltas {
2005        for state in [&delta.before, &delta.after].into_iter().flatten() {
2006            if let DeltaState::RegularFile(DeltaRegularFile {
2007                content: ContentReference::Staged(reference),
2008                ..
2009            }) = state
2010            {
2011                expected.push(StagingObject {
2012                    staging_id: reference.staging_id.clone(),
2013                    chunk_manifest_sha256: reference.chunk_manifest_sha256.clone(),
2014                });
2015            }
2016        }
2017    }
2018    expected.sort_by(|left, right| left.staging_id.as_bytes().cmp(right.staging_id.as_bytes()));
2019    if index.objects != expected {
2020        return Err(invalid(
2021            "invalid_staging",
2022            "staging index does not exactly cover Change Set references",
2023        ));
2024    }
2025    let mut expected_files = BTreeSet::from(["index.json".to_owned()]);
2026    for object in &index.objects {
2027        if !valid_prefixed_uuid(&object.staging_id, "staging_")
2028            || !is_sha256(&object.chunk_manifest_sha256)
2029        {
2030            return Err(invalid("invalid_staging", "staging object is invalid"));
2031        }
2032        let relative = format!("manifests/{}.json", object.chunk_manifest_sha256);
2033        expected_files.insert(relative.clone());
2034        let manifest_path = staging.join(&relative);
2035        let manifest =
2036            ChunkManifest::decode_bounded(File::open(&manifest_path).map_err(operational)?)
2037                .map_err(|error| invalid("invalid_staging", error.to_string()))?;
2038        if manifest.canonical_digest().map_err(operational)? != object.chunk_manifest_sha256 {
2039            return Err(invalid("invalid_staging", "chunk manifest digest changed"));
2040        }
2041        let mut object_hasher = Sha256::new();
2042        let mut object_bytes = 0_u64;
2043        for chunk in &manifest.chunks {
2044            let chunk_relative = format!("chunks/{}", chunk.sha256);
2045            expected_files.insert(chunk_relative.clone());
2046            let chunk_path = staging.join(chunk_relative);
2047            verify_regular_digest(&chunk_path, chunk.bytes, &chunk.sha256)?;
2048            let mut file = File::open(&chunk_path).map_err(operational)?;
2049            let mut buffer = [0_u8; IO_BUFFER_BYTES];
2050            loop {
2051                let read = file.read(&mut buffer).map_err(operational)?;
2052                if read == 0 {
2053                    break;
2054                }
2055                object_hasher.update(&buffer[..read]);
2056                object_bytes += read as u64;
2057            }
2058        }
2059        if object_bytes != manifest.object_bytes
2060            || format!("{:x}", object_hasher.finalize()) != manifest.object_sha256
2061        {
2062            return Err(invalid("invalid_staging", "staged object digest changed"));
2063        }
2064    }
2065    let actual_files = staging_files(staging)?;
2066    if actual_files != expected_files {
2067        return Err(invalid(
2068            "invalid_staging",
2069            "staging contains aliases or extra files",
2070        ));
2071    }
2072    Ok(())
2073}
2074
2075fn staging_files(staging: &Path) -> Result<BTreeSet<String>, ChangeSetError> {
2076    fn visit(
2077        root: &Path,
2078        directory: &Path,
2079        files: &mut BTreeSet<String>,
2080    ) -> Result<(), ChangeSetError> {
2081        for child in fs::read_dir(directory).map_err(operational)? {
2082            let child = child.map_err(operational)?;
2083            let metadata = fs::symlink_metadata(child.path()).map_err(operational)?;
2084            if metadata.file_type().is_symlink() {
2085                return Err(invalid("invalid_staging", "staging symlinks are forbidden"));
2086            }
2087            if metadata.is_dir() {
2088                visit(root, &child.path(), files)?;
2089            } else if metadata.is_file() {
2090                let relative = child
2091                    .path()
2092                    .strip_prefix(root)
2093                    .map_err(operational)?
2094                    .components()
2095                    .map(|component| component.as_os_str().to_string_lossy())
2096                    .collect::<Vec<_>>()
2097                    .join("/");
2098                files.insert(relative);
2099            } else {
2100                return Err(invalid(
2101                    "invalid_staging",
2102                    "staging special node is forbidden",
2103                ));
2104            }
2105        }
2106        Ok(())
2107    }
2108    let mut files = BTreeSet::new();
2109    visit(staging, staging, &mut files)?;
2110    Ok(files)
2111}
2112
2113fn assess_conflicts(
2114    envelope: &ChangeSetEnvelope,
2115    receipt: &CheckoutReceipt,
2116    current: &[InventoryEntry],
2117) -> Vec<ChangeSetConflict> {
2118    let current_by_path = current
2119        .iter()
2120        .map(|entry| (entry.path.as_str(), entry))
2121        .collect::<BTreeMap<_, _>>();
2122    let nested = receipt
2123        .exclusions
2124        .iter()
2125        .filter(|exclusion| exclusion.reason == "nested-folderbase-boundary")
2126        .map(|exclusion| exclusion.path.as_str())
2127        .collect::<Vec<_>>();
2128    let mut conflicts = Vec::new();
2129    for delta in &envelope.payload.deltas {
2130        let touched = [&delta.before, &delta.after]
2131            .into_iter()
2132            .flatten()
2133            .map(DeltaState::path)
2134            .collect::<Vec<_>>();
2135        if let Some(path) = touched.iter().find(|path| {
2136            nested
2137                .iter()
2138                .any(|boundary| is_same_or_descendant(path, boundary))
2139        }) {
2140            conflicts.push(ChangeSetConflict {
2141                code: "nested_boundary".to_owned(),
2142                path: (*path).to_owned(),
2143                other_path: None,
2144                object_id: Some(delta.object_id.clone()),
2145            });
2146            continue;
2147        }
2148        match (&delta.before, &delta.after) {
2149            (None, Some(after)) => {
2150                if current_by_path.contains_key(after.path()) {
2151                    conflicts.push(conflict("create_create", after.path(), delta, None));
2152                } else if let Some(alias) = current.iter().find(|entry| {
2153                    entry.path != after.path()
2154                        && (collision_key(&entry.path) == collision_key(after.path())
2155                            || nfc_key(&entry.path) == nfc_key(after.path()))
2156                }) {
2157                    conflicts.push(conflict(
2158                        "path_alias",
2159                        after.path(),
2160                        delta,
2161                        Some(&alias.path),
2162                    ));
2163                }
2164            }
2165            (Some(before), after) => match current_by_path.get(before.path()) {
2166                Some(current_entry) => {
2167                    let base_entry = inventory_from_delta(before);
2168                    if !base_entry.same_opaque_content_or_metadata(current_entry) {
2169                        let code = if after.is_none() {
2170                            "delete_edit"
2171                        } else if after
2172                            .as_ref()
2173                            .is_some_and(|after| after.path() != before.path())
2174                        {
2175                            "move_edit"
2176                        } else {
2177                            "edit_edit"
2178                        };
2179                        conflicts.push(conflict(code, before.path(), delta, None));
2180                        continue;
2181                    }
2182                    if let Some(after) = after
2183                        && after.path() != before.path()
2184                    {
2185                        if current_by_path.contains_key(after.path()) {
2186                            conflicts.push(conflict(
2187                                "path_occupied",
2188                                after.path(),
2189                                delta,
2190                                Some(before.path()),
2191                            ));
2192                        } else if let Some(alias) = current.iter().find(|entry| {
2193                            entry.path != before.path()
2194                                && entry.path != after.path()
2195                                && (collision_key(&entry.path) == collision_key(after.path())
2196                                    || nfc_key(&entry.path) == nfc_key(after.path()))
2197                        }) {
2198                            conflicts.push(conflict(
2199                                "path_alias",
2200                                after.path(),
2201                                delta,
2202                                Some(&alias.path),
2203                            ));
2204                        }
2205                    }
2206                }
2207                None => {
2208                    if after.is_some() {
2209                        conflicts.push(conflict("edit_delete", before.path(), delta, None));
2210                    }
2211                }
2212            },
2213            (None, None) => unreachable!("validated delta"),
2214        }
2215    }
2216    conflicts.sort_by(|left, right| {
2217        left.path
2218            .as_bytes()
2219            .cmp(right.path.as_bytes())
2220            .then_with(|| left.code.as_bytes().cmp(right.code.as_bytes()))
2221    });
2222    conflicts
2223}
2224
2225impl InventoryEntry {
2226    fn same_opaque_content_or_metadata(&self, other: &Self) -> bool {
2227        self.kind == other.kind
2228            && self.content_sha256 == other.content_sha256
2229            && self.bytes == other.bytes
2230            && self.executable == other.executable
2231            && self.target == other.target
2232    }
2233}
2234
2235fn inventory_from_delta(state: &DeltaState) -> InventoryEntry {
2236    match state {
2237        DeltaState::Directory(value) => InventoryEntry {
2238            path: value.path.clone(),
2239            kind: InventoryKind::Directory,
2240            object_id: None,
2241            object_version_id: None,
2242            content_sha256: None,
2243            bytes: None,
2244            executable: None,
2245            target: None,
2246        },
2247        DeltaState::RegularFile(value) => InventoryEntry {
2248            path: value.path.clone(),
2249            kind: InventoryKind::RegularFile,
2250            object_id: None,
2251            object_version_id: Some(value.object_version_id.clone()),
2252            content_sha256: Some(value.content_sha256.clone()),
2253            bytes: Some(value.bytes),
2254            executable: Some(value.executable),
2255            target: None,
2256        },
2257        DeltaState::Symlink(value) => InventoryEntry {
2258            path: value.path.clone(),
2259            kind: InventoryKind::Symlink,
2260            object_id: None,
2261            object_version_id: Some(value.object_version_id.clone()),
2262            content_sha256: None,
2263            bytes: None,
2264            executable: None,
2265            target: Some(value.target.clone()),
2266        },
2267    }
2268}
2269
2270fn conflict(
2271    code: &str,
2272    path: &str,
2273    delta: &ObjectDelta,
2274    other_path: Option<&str>,
2275) -> ChangeSetConflict {
2276    ChangeSetConflict {
2277        code: code.to_owned(),
2278        path: path.to_owned(),
2279        other_path: other_path.map(ToOwned::to_owned),
2280        object_id: Some(delta.object_id.clone()),
2281    }
2282}
2283
2284fn scoped_inventory_digest(entries: &[InventoryEntry]) -> Result<String, ChangeSetError> {
2285    #[derive(Serialize)]
2286    struct DigestEntry<'a> {
2287        path: &'a str,
2288        kind: &'static str,
2289        content_sha256: Option<&'a str>,
2290        bytes: Option<u64>,
2291        executable: Option<bool>,
2292        target: Option<&'a str>,
2293    }
2294    let entries = entries
2295        .iter()
2296        .map(|entry| DigestEntry {
2297            path: &entry.path,
2298            kind: match entry.kind {
2299                InventoryKind::Directory => "directory",
2300                InventoryKind::RegularFile => "regular_file",
2301                InventoryKind::Symlink => "symlink",
2302            },
2303            content_sha256: entry.content_sha256.as_deref(),
2304            bytes: entry.bytes,
2305            executable: entry.executable,
2306            target: entry.target.as_deref(),
2307        })
2308        .collect::<Vec<_>>();
2309    let encoded = serde_json::to_vec(&entries).map_err(operational)?;
2310    let mut digest = Sha256::new();
2311    digest.update(b"folderbase-current-projection-v1\0");
2312    digest.update(encoded);
2313    Ok(format!("{:x}", digest.finalize()))
2314}
2315
2316fn reject_path_collisions(paths: &[String], code: &'static str) -> Result<(), ChangeSetError> {
2317    let mut exact = BTreeSet::new();
2318    let mut nfc = BTreeSet::new();
2319    let mut folded = BTreeSet::new();
2320    for path in paths {
2321        if !exact.insert(path.clone())
2322            || !nfc.insert(nfc_key(path))
2323            || !folded.insert(collision_key(path))
2324        {
2325            return Err(invalid(
2326                code,
2327                "paths collide under the portable path policy",
2328            ));
2329        }
2330    }
2331    Ok(())
2332}
2333
2334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2335enum InventoryKind {
2336    Directory,
2337    RegularFile,
2338    Symlink,
2339}
2340
2341#[derive(Debug, Clone, PartialEq, Eq)]
2342struct InventoryEntry {
2343    path: String,
2344    kind: InventoryKind,
2345    object_id: Option<String>,
2346    object_version_id: Option<String>,
2347    content_sha256: Option<String>,
2348    bytes: Option<u64>,
2349    executable: Option<bool>,
2350    target: Option<String>,
2351}
2352
2353impl InventoryEntry {
2354    fn from_projected(entry: &ProjectedEntry) -> Self {
2355        match entry {
2356            ProjectedEntry::Directory { path, object_id } => Self {
2357                path: path.clone(),
2358                kind: InventoryKind::Directory,
2359                object_id: Some(object_id.clone()),
2360                object_version_id: None,
2361                content_sha256: None,
2362                bytes: None,
2363                executable: None,
2364                target: None,
2365            },
2366            ProjectedEntry::RegularFile {
2367                path,
2368                object_id,
2369                object_version_id,
2370                content_sha256,
2371                bytes,
2372                executable,
2373            } => Self {
2374                path: path.clone(),
2375                kind: InventoryKind::RegularFile,
2376                object_id: Some(object_id.clone()),
2377                object_version_id: Some(object_version_id.clone()),
2378                content_sha256: Some(content_sha256.clone()),
2379                bytes: Some(*bytes),
2380                executable: Some(*executable),
2381                target: None,
2382            },
2383            ProjectedEntry::Symlink {
2384                path,
2385                object_id,
2386                object_version_id,
2387                target,
2388                ..
2389            } => Self {
2390                path: path.clone(),
2391                kind: InventoryKind::Symlink,
2392                object_id: Some(object_id.clone()),
2393                object_version_id: Some(object_version_id.clone()),
2394                content_sha256: None,
2395                bytes: None,
2396                executable: None,
2397                target: Some(target.clone()),
2398            },
2399        }
2400    }
2401
2402    fn same_state(&self, other: &Self) -> bool {
2403        self.path == other.path
2404            && self.kind == other.kind
2405            && self.content_sha256 == other.content_sha256
2406            && self.bytes == other.bytes
2407            && self.executable == other.executable
2408            && self.target == other.target
2409    }
2410
2411    fn same_opaque_content(&self, other: &Self) -> bool {
2412        self.kind == other.kind
2413            && match self.kind {
2414                InventoryKind::Directory => false,
2415                InventoryKind::RegularFile => {
2416                    self.content_sha256 == other.content_sha256
2417                        && self.bytes == other.bytes
2418                        && self.executable == other.executable
2419                }
2420                InventoryKind::Symlink => self.target == other.target,
2421            }
2422    }
2423}
2424
2425fn inventory_checkout(checkout: &Path) -> Result<Vec<InventoryEntry>, ChangeSetError> {
2426    let metadata = fs::symlink_metadata(checkout).map_err(operational)?;
2427    if !metadata.is_dir() || metadata.file_type().is_symlink() {
2428        return Err(invalid(
2429            "invalid_projection_receipt",
2430            "checkout root is not a no-follow directory",
2431        ));
2432    }
2433    let mut entries = Vec::new();
2434    inventory_directory(checkout, "", &mut entries)?;
2435    if entries.len() > MAX_CHANGE_SET_ENTRIES {
2436        return Err(invalid(
2437            "invalid_change_set_input",
2438            "checkout exceeds the Change Set entry limit",
2439        ));
2440    }
2441    entries.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
2442    reject_inventory_collisions(&entries)?;
2443    Ok(entries)
2444}
2445
2446fn inventory_directory(
2447    root: &Path,
2448    prefix: &str,
2449    entries: &mut Vec<InventoryEntry>,
2450) -> Result<(), ChangeSetError> {
2451    let directory = if prefix.is_empty() {
2452        root.to_path_buf()
2453    } else {
2454        resolve_portable(root, prefix)?
2455    };
2456    let mut names = fs::read_dir(&directory)
2457        .map_err(operational)?
2458        .collect::<Result<Vec<_>, _>>()
2459        .map_err(operational)?;
2460    names.sort_by(|left, right| {
2461        left.file_name()
2462            .as_encoded_bytes()
2463            .cmp(right.file_name().as_encoded_bytes())
2464    });
2465    for entry in names {
2466        let name = entry
2467            .file_name()
2468            .into_string()
2469            .map_err(|_| invalid("invalid_change_set_input", "checkout path is not UTF-8"))?;
2470        let path = if prefix.is_empty() {
2471            name
2472        } else {
2473            format!("{prefix}/{name}")
2474        };
2475        if path == ".folderbase" {
2476            continue;
2477        }
2478        validate_portable_path(&path)?;
2479        let metadata = fs::symlink_metadata(entry.path()).map_err(operational)?;
2480        if metadata.is_dir() {
2481            entries.push(InventoryEntry {
2482                path: path.clone(),
2483                kind: InventoryKind::Directory,
2484                object_id: None,
2485                object_version_id: None,
2486                content_sha256: None,
2487                bytes: None,
2488                executable: None,
2489                target: None,
2490            });
2491            inventory_directory(root, &path, entries)?;
2492        } else if metadata.is_file() && !metadata.file_type().is_symlink() {
2493            let digest = sha256_regular(&entry.path(), metadata.len())?;
2494            entries.push(InventoryEntry {
2495                path,
2496                kind: InventoryKind::RegularFile,
2497                object_id: None,
2498                object_version_id: None,
2499                content_sha256: Some(digest),
2500                bytes: Some(metadata.len()),
2501                executable: Some(is_executable(&metadata)),
2502                target: None,
2503            });
2504        } else if metadata.file_type().is_symlink() {
2505            let target = fs::read_link(entry.path()).map_err(operational)?;
2506            let target = target.to_str().ok_or_else(|| {
2507                invalid("invalid_change_set_input", "symlink target is not UTF-8")
2508            })?;
2509            validate_safe_symlink_target(&path, target)?;
2510            entries.push(InventoryEntry {
2511                path,
2512                kind: InventoryKind::Symlink,
2513                object_id: None,
2514                object_version_id: None,
2515                content_sha256: None,
2516                bytes: None,
2517                executable: None,
2518                target: Some(target.to_owned()),
2519            });
2520        } else {
2521            return Err(invalid(
2522                "invalid_change_set_input",
2523                format!("unsupported checkout node: {path}"),
2524            ));
2525        }
2526    }
2527    Ok(())
2528}
2529
2530fn match_inventory(base: &[InventoryEntry], current: &[InventoryEntry]) -> Vec<(usize, usize)> {
2531    let mut matched_base = BTreeSet::new();
2532    let mut matched_current = BTreeSet::new();
2533    let mut result = Vec::new();
2534    let base_by_path = base
2535        .iter()
2536        .enumerate()
2537        .map(|(index, entry)| (entry.path.as_str(), index))
2538        .collect::<BTreeMap<_, _>>();
2539    for (current_index, entry) in current.iter().enumerate() {
2540        if let Some(base_index) = base_by_path.get(entry.path.as_str()).copied()
2541            && base[base_index].kind == entry.kind
2542        {
2543            matched_base.insert(base_index);
2544            matched_current.insert(current_index);
2545            result.push((base_index, current_index));
2546        }
2547    }
2548
2549    // Exact opaque content is a deterministic rename proof.
2550    for (current_index, entry) in current.iter().enumerate() {
2551        if matched_current.contains(&current_index) {
2552            continue;
2553        }
2554        let candidates = base
2555            .iter()
2556            .enumerate()
2557            .filter(|(base_index, candidate)| {
2558                !matched_base.contains(base_index) && candidate.same_opaque_content(entry)
2559            })
2560            .map(|(index, _)| index)
2561            .collect::<Vec<_>>();
2562        if candidates.len() == 1 {
2563            let base_index = candidates[0];
2564            matched_base.insert(base_index);
2565            matched_current.insert(current_index);
2566            result.push((base_index, current_index));
2567        }
2568    }
2569
2570    // Move-plus-edit has no portable inode in the checkout receipt. Pair only
2571    // an unambiguous one-to-one remaining file of the same kind; ambiguity is
2572    // intentionally represented as delete plus create rather than guessed.
2573    for kind in [InventoryKind::RegularFile, InventoryKind::Symlink] {
2574        let remaining_base = base
2575            .iter()
2576            .enumerate()
2577            .filter(|(index, entry)| !matched_base.contains(index) && entry.kind == kind)
2578            .map(|(index, _)| index)
2579            .collect::<Vec<_>>();
2580        let remaining_current = current
2581            .iter()
2582            .enumerate()
2583            .filter(|(index, entry)| !matched_current.contains(index) && entry.kind == kind)
2584            .map(|(index, _)| index)
2585            .collect::<Vec<_>>();
2586        if remaining_base.len() == 1 && remaining_current.len() == 1 {
2587            matched_base.insert(remaining_base[0]);
2588            matched_current.insert(remaining_current[0]);
2589            result.push((remaining_base[0], remaining_current[0]));
2590        }
2591    }
2592    result.sort_unstable();
2593    result
2594}
2595
2596fn delta_state_from_base(entry: &InventoryEntry) -> DeltaState {
2597    match entry.kind {
2598        InventoryKind::Directory => DeltaState::Directory(DeltaDirectory {
2599            path: entry.path.clone(),
2600            kind: "directory".to_owned(),
2601        }),
2602        InventoryKind::RegularFile => DeltaState::RegularFile(DeltaRegularFile {
2603            path: entry.path.clone(),
2604            kind: "regular_file".to_owned(),
2605            object_version_id: entry
2606                .object_version_id
2607                .clone()
2608                .expect("trusted regular file has Object Version"),
2609            content_sha256: entry
2610                .content_sha256
2611                .clone()
2612                .expect("trusted regular file has digest"),
2613            bytes: entry.bytes.expect("trusted regular file has length"),
2614            executable: entry.executable.unwrap_or(false),
2615            content: ContentReference::ProjectionBase(ProjectionBaseContent {
2616                source: "projection_base".to_owned(),
2617            }),
2618        }),
2619        InventoryKind::Symlink => DeltaState::Symlink(DeltaSymlink {
2620            path: entry.path.clone(),
2621            kind: "symlink".to_owned(),
2622            object_version_id: entry
2623                .object_version_id
2624                .clone()
2625                .expect("trusted symlink has Object Version"),
2626            target: entry.target.clone().expect("trusted symlink has target"),
2627            target_safety: "relative-within-projection".to_owned(),
2628        }),
2629    }
2630}
2631
2632fn delta_state_from_current(
2633    checkout: &Path,
2634    staging: &Path,
2635    entry: &InventoryEntry,
2636    base: Option<&InventoryEntry>,
2637    staged_objects: &mut Vec<StagingObject>,
2638) -> Result<DeltaState, ChangeSetError> {
2639    Ok(match entry.kind {
2640        InventoryKind::Directory => DeltaState::Directory(DeltaDirectory {
2641            path: entry.path.clone(),
2642            kind: "directory".to_owned(),
2643        }),
2644        InventoryKind::RegularFile => {
2645            let reuses_base = base.is_some_and(|base| {
2646                base.content_sha256 == entry.content_sha256
2647                    && base.bytes == entry.bytes
2648                    && base.executable == entry.executable
2649            });
2650            let object_version_id = if reuses_base {
2651                base.and_then(|base| base.object_version_id.clone())
2652                    .expect("base regular file has Object Version")
2653            } else {
2654                format!("version_{}", Uuid::now_v7())
2655            };
2656            let content = if reuses_base {
2657                ContentReference::ProjectionBase(ProjectionBaseContent {
2658                    source: "projection_base".to_owned(),
2659                })
2660            } else {
2661                let staged = stage_regular_file(
2662                    &resolve_portable(checkout, &entry.path)?,
2663                    staging,
2664                    entry.bytes.expect("regular file has byte length"),
2665                )?;
2666                staged_objects.push(StagingObject {
2667                    staging_id: staged.staging_id.clone(),
2668                    chunk_manifest_sha256: staged.chunk_manifest_sha256.clone(),
2669                });
2670                ContentReference::Staged(staged)
2671            };
2672            DeltaState::RegularFile(DeltaRegularFile {
2673                path: entry.path.clone(),
2674                kind: "regular_file".to_owned(),
2675                object_version_id,
2676                content_sha256: entry
2677                    .content_sha256
2678                    .clone()
2679                    .expect("regular file has digest"),
2680                bytes: entry.bytes.expect("regular file has byte length"),
2681                executable: entry.executable.unwrap_or(false),
2682                content,
2683            })
2684        }
2685        InventoryKind::Symlink => {
2686            let reuses_base = base.is_some_and(|base| base.target == entry.target);
2687            DeltaState::Symlink(DeltaSymlink {
2688                path: entry.path.clone(),
2689                kind: "symlink".to_owned(),
2690                object_version_id: if reuses_base {
2691                    base.and_then(|base| base.object_version_id.clone())
2692                        .expect("base symlink has Object Version")
2693                } else {
2694                    format!("version_{}", Uuid::now_v7())
2695                },
2696                target: entry.target.clone().expect("symlink has target"),
2697                target_safety: "relative-within-projection".to_owned(),
2698            })
2699        }
2700    })
2701}
2702
2703fn stage_regular_file(
2704    source: &Path,
2705    staging: &Path,
2706    expected_bytes: u64,
2707) -> Result<StagedContent, ChangeSetError> {
2708    if expected_bytes > MAX_OBJECT_BYTES {
2709        return Err(invalid(
2710            "invalid_change_set_input",
2711            "regular file exceeds the 1 TiB object limit",
2712        ));
2713    }
2714    let profile = if expected_bytes >= LARGE_PROFILE_THRESHOLD_BYTES {
2715        LARGE_PROFILE_V1
2716    } else {
2717        STANDARD_PROFILE_V1
2718    };
2719    let mut file = File::open(source).map_err(operational)?;
2720    let manifest = plan_streamed_manifest(
2721        Read::by_ref(&mut file).take(expected_bytes.saturating_add(1)),
2722        profile,
2723    )
2724    .map_err(operational)?;
2725    if manifest.object_bytes != expected_bytes {
2726        return Err(invalid(
2727            "invalid_change_set_input",
2728            "checkout file changed while staging",
2729        ));
2730    }
2731    let manifest_sha256 = manifest.canonical_digest().map_err(operational)?;
2732    file.seek(SeekFrom::Start(0)).map_err(operational)?;
2733    for chunk in &manifest.chunks {
2734        file.seek(SeekFrom::Start(chunk.offset))
2735            .map_err(operational)?;
2736        install_staging_chunk(
2737            &mut file,
2738            &staging.join("chunks").join(&chunk.sha256),
2739            chunk.bytes,
2740            &chunk.sha256,
2741        )?;
2742    }
2743    let manifest_bytes = serde_json::to_vec(&manifest).map_err(operational)?;
2744    create_new_file(
2745        &staging
2746            .join("manifests")
2747            .join(format!("{manifest_sha256}.json")),
2748        &manifest_bytes,
2749    )?;
2750    Ok(StagedContent {
2751        source: "staged".to_owned(),
2752        staging_id: format!("staging_{}", Uuid::now_v7()),
2753        chunk_manifest_sha256: manifest_sha256,
2754    })
2755}
2756
2757fn install_staging_chunk(
2758    source: &mut File,
2759    target: &Path,
2760    expected_bytes: u64,
2761    expected_sha256: &str,
2762) -> Result<(), ChangeSetError> {
2763    let mut options = OpenOptions::new();
2764    options.write(true).create_new(true);
2765    let mut target_file = match options.open(target) {
2766        Ok(file) => file,
2767        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
2768            verify_regular_digest(target, expected_bytes, expected_sha256)?;
2769            return Ok(());
2770        }
2771        Err(error) => return Err(operational(error)),
2772    };
2773    let mut remaining = expected_bytes;
2774    let mut hasher = Sha256::new();
2775    let mut buffer = [0_u8; IO_BUFFER_BYTES];
2776    while remaining > 0 {
2777        let wanted = usize::try_from(remaining.min(buffer.len() as u64))
2778            .expect("bounded I/O length fits usize");
2779        let read = source.read(&mut buffer[..wanted]).map_err(operational)?;
2780        if read == 0 {
2781            return Err(invalid(
2782                "invalid_change_set_input",
2783                "checkout file shortened while staging",
2784            ));
2785        }
2786        hasher.update(&buffer[..read]);
2787        target_file
2788            .write_all(&buffer[..read])
2789            .map_err(operational)?;
2790        remaining -= read as u64;
2791    }
2792    target_file.sync_all().map_err(operational)?;
2793    if format!("{:x}", hasher.finalize()) != expected_sha256 {
2794        return Err(invalid(
2795            "invalid_change_set_input",
2796            "checkout file changed while staging",
2797        ));
2798    }
2799    Ok(())
2800}
2801
2802fn change_set_digest(payload: &ChangeSetPayload) -> Result<String, ChangeSetError> {
2803    let encoded = serde_json::to_vec(payload).map_err(operational)?;
2804    let mut digest = Sha256::new();
2805    digest.update(b"folderbase-change-set-v1\0");
2806    digest.update(encoded);
2807    Ok(format!("{:x}", digest.finalize()))
2808}
2809
2810fn validate_receipt(receipt: &CheckoutReceipt) -> Result<(), ChangeSetError> {
2811    if receipt.format != "folderbase-checkout-projection-v1"
2812        || !valid_prefixed_uuid(&receipt.checkout_id, "checkout_")
2813        || !valid_prefixed_uuid(&receipt.folderbase_id, "folderbase_")
2814        || !valid_prefixed_uuid(&receipt.projection_id, "projection_")
2815        || !valid_prefixed_uuid(&receipt.folder_scope_id, "folderscope_")
2816        || !is_sha256(&receipt.scope_revision_sha256)
2817        || !is_sha256(&receipt.projection_base_sha256)
2818        || receipt.permission != "can_work"
2819        || receipt.entries.len() > MAX_CHANGE_SET_ENTRIES
2820        || receipt.exclusions.len() > MAX_CHANGE_SET_ENTRIES
2821    {
2822        return Err(invalid(
2823            "invalid_projection_receipt",
2824            "checkout receipt violates the closed v1 contract",
2825        ));
2826    }
2827    let request = CheckoutRequest {
2828        format: "folderbase-checkout-request-v1".to_owned(),
2829        folderbase_id: receipt.folderbase_id.clone(),
2830        projection_id: receipt.projection_id.clone(),
2831        folder_scope_id: receipt.folder_scope_id.clone(),
2832        scope_revision_sha256: receipt.scope_revision_sha256.clone(),
2833        permission: receipt.permission.clone(),
2834        authorized_paths: receipt.authorized_paths.clone(),
2835    };
2836    validate_checkout_request(&request)?;
2837    if projection_digest(&request, &receipt.entries, &receipt.exclusions)?
2838        != receipt.projection_base_sha256
2839    {
2840        return Err(invalid(
2841            "invalid_projection_receipt",
2842            "checkout receipt digest does not match its scoped contents",
2843        ));
2844    }
2845    Ok(())
2846}
2847
2848fn read_json_bounded_file<T: for<'de> Deserialize<'de>>(
2849    path: &Path,
2850    maximum_bytes: u64,
2851    code: &'static str,
2852) -> Result<T, ChangeSetError> {
2853    let metadata = fs::symlink_metadata(path).map_err(operational)?;
2854    if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > maximum_bytes {
2855        return Err(invalid(code, "JSON record is unsafe or exceeds its bound"));
2856    }
2857    let mut bytes = Vec::new();
2858    File::open(path)
2859        .map_err(operational)?
2860        .take(maximum_bytes + 1)
2861        .read_to_end(&mut bytes)
2862        .map_err(operational)?;
2863    if bytes.len() as u64 > maximum_bytes {
2864        return Err(invalid(code, "JSON record exceeds its bound"));
2865    }
2866    serde_json::from_slice(&bytes).map_err(|error| invalid(code, error.to_string()))
2867}
2868
2869fn sha256_regular(path: &Path, expected_bytes: u64) -> Result<String, ChangeSetError> {
2870    let mut file = File::open(path).map_err(operational)?;
2871    let mut hasher = Sha256::new();
2872    let mut observed = 0_u64;
2873    let mut buffer = [0_u8; IO_BUFFER_BYTES];
2874    loop {
2875        let read = file.read(&mut buffer).map_err(operational)?;
2876        if read == 0 {
2877            break;
2878        }
2879        observed = observed
2880            .checked_add(read as u64)
2881            .ok_or_else(|| invalid("invalid_change_set_input", "file length overflowed"))?;
2882        if observed > expected_bytes {
2883            return Err(invalid(
2884                "invalid_change_set_input",
2885                "checkout file grew during observation",
2886            ));
2887        }
2888        hasher.update(&buffer[..read]);
2889    }
2890    if observed != expected_bytes {
2891        return Err(invalid(
2892            "invalid_change_set_input",
2893            "checkout file changed during observation",
2894        ));
2895    }
2896    Ok(format!("{:x}", hasher.finalize()))
2897}
2898
2899fn verify_regular_digest(
2900    path: &Path,
2901    expected_bytes: u64,
2902    expected_sha256: &str,
2903) -> Result<(), ChangeSetError> {
2904    let metadata = fs::symlink_metadata(path).map_err(operational)?;
2905    if !metadata.is_file()
2906        || metadata.file_type().is_symlink()
2907        || metadata.len() != expected_bytes
2908        || sha256_regular(path, expected_bytes)? != expected_sha256
2909    {
2910        return Err(invalid(
2911            "invalid_staging",
2912            "staged chunk failed verification",
2913        ));
2914    }
2915    Ok(())
2916}
2917
2918#[cfg(unix)]
2919fn is_executable(metadata: &fs::Metadata) -> bool {
2920    use std::os::unix::fs::PermissionsExt;
2921    metadata.permissions().mode() & 0o111 != 0
2922}
2923
2924#[cfg(not(unix))]
2925fn is_executable(_metadata: &fs::Metadata) -> bool {
2926    false
2927}
2928
2929fn validate_safe_symlink_target(path: &str, target: &str) -> Result<(), ChangeSetError> {
2930    if target.is_empty() || target.contains('\\') || Path::new(target).is_absolute() {
2931        return Err(invalid(
2932            "invalid_change_set_input",
2933            format!("unsafe symlink target at {path}"),
2934        ));
2935    }
2936    let mut depth = path.split('/').count().saturating_sub(1) as isize;
2937    for component in target.split('/') {
2938        match component {
2939            "" | "." => {}
2940            ".." => {
2941                depth -= 1;
2942                if depth < 0 {
2943                    return Err(invalid(
2944                        "invalid_change_set_input",
2945                        format!("symlink escapes checkout at {path}"),
2946                    ));
2947                }
2948            }
2949            _ => depth += 1,
2950        }
2951    }
2952    Ok(())
2953}
2954
2955fn reject_inventory_collisions(entries: &[InventoryEntry]) -> Result<(), ChangeSetError> {
2956    let mut exact = BTreeSet::new();
2957    let mut nfc = BTreeSet::new();
2958    let mut folded = BTreeSet::new();
2959    for entry in entries {
2960        if !exact.insert(entry.path.clone())
2961            || !nfc.insert(nfc_key(&entry.path))
2962            || !folded.insert(collision_key(&entry.path))
2963        {
2964            return Err(invalid(
2965                "invalid_change_set_input",
2966                "checkout paths collide under the portable path policy",
2967            ));
2968        }
2969    }
2970    Ok(())
2971}
2972
2973fn projected_entry(binding: &PathBinding) -> Result<ProjectedEntry, ChangeSetError> {
2974    Ok(match binding.kind() {
2975        PathBindingKind::Directory => ProjectedEntry::Directory {
2976            path: binding.path().to_owned(),
2977            object_id: binding.object_id().to_owned(),
2978        },
2979        PathBindingKind::RegularFile => ProjectedEntry::RegularFile {
2980            path: binding.path().to_owned(),
2981            object_id: binding.object_id().to_owned(),
2982            object_version_id: binding
2983                .object_version_id()
2984                .ok_or_else(|| operational_message("regular binding omitted Object Version"))?
2985                .to_owned(),
2986            content_sha256: binding
2987                .content_sha256()
2988                .ok_or_else(|| operational_message("regular binding omitted content digest"))?
2989                .to_owned(),
2990            bytes: binding
2991                .bytes()
2992                .ok_or_else(|| operational_message("regular binding omitted byte length"))?,
2993            executable: binding.executable().unwrap_or(false),
2994        },
2995        PathBindingKind::Symlink => ProjectedEntry::Symlink {
2996            path: binding.path().to_owned(),
2997            object_id: binding.object_id().to_owned(),
2998            object_version_id: binding
2999                .object_version_id()
3000                .ok_or_else(|| operational_message("symlink binding omitted Object Version"))?
3001                .to_owned(),
3002            target: binding
3003                .symlink_target()
3004                .ok_or_else(|| operational_message("symlink binding omitted target"))?
3005                .to_owned(),
3006            target_safety: "relative-within-projection".to_owned(),
3007        },
3008    })
3009}
3010
3011#[derive(Serialize)]
3012struct ProjectionDigest<'a> {
3013    format: &'static str,
3014    folderbase_id: &'a str,
3015    projection_id: &'a str,
3016    folder_scope_id: &'a str,
3017    scope_revision_sha256: &'a str,
3018    permission: &'a str,
3019    authorized_paths: &'a [AuthorizedPath],
3020    entries: &'a [ProjectedEntry],
3021    exclusions: &'a [ProjectionExclusion],
3022}
3023
3024fn projection_digest(
3025    request: &CheckoutRequest,
3026    entries: &[ProjectedEntry],
3027    exclusions: &[ProjectionExclusion],
3028) -> Result<String, ChangeSetError> {
3029    let encoded = serde_json::to_vec(&ProjectionDigest {
3030        format: "folderbase-projection-base-v1",
3031        folderbase_id: &request.folderbase_id,
3032        projection_id: &request.projection_id,
3033        folder_scope_id: &request.folder_scope_id,
3034        scope_revision_sha256: &request.scope_revision_sha256,
3035        permission: &request.permission,
3036        authorized_paths: &request.authorized_paths,
3037        entries,
3038        exclusions,
3039    })
3040    .map_err(operational)?;
3041    let mut digest = Sha256::new();
3042    digest.update(b"folderbase-projection-base-v1\0");
3043    digest.update(encoded);
3044    Ok(format!("{:x}", digest.finalize()))
3045}
3046
3047fn materialize_checkout(
3048    root: &Path,
3049    destination: &Path,
3050    receipt: &CheckoutReceipt,
3051) -> Result<(), ChangeSetError> {
3052    fs::create_dir(destination).map_err(operational)?;
3053    fs::create_dir(destination.join(".folderbase")).map_err(operational)?;
3054
3055    for entry in &receipt.entries {
3056        if matches!(entry, ProjectedEntry::Directory { .. }) {
3057            fs::create_dir_all(resolve_portable(destination, entry.path())?)
3058                .map_err(operational)?;
3059        }
3060    }
3061    for entry in &receipt.entries {
3062        match entry {
3063            ProjectedEntry::Directory { .. } => {}
3064            ProjectedEntry::RegularFile {
3065                path,
3066                content_sha256,
3067                bytes,
3068                executable,
3069                ..
3070            } => {
3071                let source = resolve_portable(root, path)?;
3072                let target = resolve_portable(destination, path)?;
3073                if let Some(parent) = target.parent() {
3074                    fs::create_dir_all(parent).map_err(operational)?;
3075                }
3076                copy_regular_verified(&source, &target, content_sha256, *bytes, *executable)?;
3077            }
3078            ProjectedEntry::Symlink { path, target, .. } => {
3079                materialize_symlink(destination, path, target)?;
3080            }
3081        }
3082    }
3083
3084    let encoded = encode_pretty_bounded(receipt, MAX_PROJECTION_RECORD_BYTES)?;
3085    create_new_file(&destination.join(".folderbase/checkout.json"), &encoded)?;
3086    Ok(())
3087}
3088
3089fn install_trusted_projection(
3090    root: &Path,
3091    trusted: &TrustedProjection,
3092) -> Result<(), ChangeSetError> {
3093    let state = FolderbaseState::open_existing(root).map_err(operational)?;
3094    state
3095        .ensure_private_dir(Path::new(PROJECTIONS_DIRECTORY))
3096        .map_err(operational)?;
3097    let relative =
3098        Path::new(PROJECTIONS_DIRECTORY).join(format!("{}.json", trusted.receipt.projection_id));
3099    let encoded = encode_pretty_bounded(trusted, MAX_PROJECTION_RECORD_BYTES)?;
3100    state.publish_new(&relative, &encoded).map_err(operational)
3101}
3102
3103fn validate_checkout_request(request: &CheckoutRequest) -> Result<(), ChangeSetError> {
3104    if request.format != "folderbase-checkout-request-v1"
3105        || request.permission != "can_work"
3106        || !valid_prefixed_uuid(&request.folderbase_id, "folderbase_")
3107        || !valid_prefixed_uuid(&request.projection_id, "projection_")
3108        || !valid_prefixed_uuid(&request.folder_scope_id, "folderscope_")
3109        || !is_sha256(&request.scope_revision_sha256)
3110        || request.authorized_paths.is_empty()
3111        || request.authorized_paths.len() > 256
3112    {
3113        return Err(invalid(
3114            "invalid_checkout_request",
3115            "checkout request violates the closed v1 contract",
3116        ));
3117    }
3118    let mut previous: Option<&str> = None;
3119    for path in &request.authorized_paths {
3120        if let Some(prefix) = path.path_prefix.as_deref() {
3121            validate_portable_path(prefix)?;
3122            if prefix == ".folderbase" || prefix.starts_with(".folderbase/") {
3123                return Err(invalid(
3124                    "invalid_checkout_request",
3125                    "protocol state cannot be authorized as ordinary content",
3126                ));
3127            }
3128            if previous.is_some_and(|prior| prior.as_bytes() >= prefix.as_bytes()) {
3129                return Err(invalid(
3130                    "invalid_checkout_request",
3131                    "authorized paths must be strictly byte-sorted",
3132                ));
3133            }
3134            previous = Some(prefix);
3135        } else if request.authorized_paths.len() != 1 {
3136            return Err(invalid(
3137                "invalid_checkout_request",
3138                "complete-root authority cannot overlap another prefix",
3139            ));
3140        }
3141    }
3142    for (index, left) in request.authorized_paths.iter().enumerate() {
3143        for right in request.authorized_paths.iter().skip(index + 1) {
3144            let (Some(left), Some(right)) =
3145                (left.path_prefix.as_deref(), right.path_prefix.as_deref())
3146            else {
3147                continue;
3148            };
3149            if is_same_or_descendant(right, left)
3150                || collision_key(left) == collision_key(right)
3151                || nfc_key(left) == nfc_key(right)
3152            {
3153                return Err(invalid(
3154                    "invalid_checkout_request",
3155                    "authorized paths overlap or collide",
3156                ));
3157            }
3158        }
3159    }
3160    Ok(())
3161}
3162
3163fn is_authorized(path: &str, authorized: &[AuthorizedPath]) -> bool {
3164    authorized.iter().any(|scope| {
3165        scope
3166            .path_prefix
3167            .as_deref()
3168            .is_none_or(|prefix| is_same_or_descendant(path, prefix))
3169    }) && path != ".folderbase"
3170        && !path.starts_with(".folderbase/")
3171}
3172
3173fn is_same_or_descendant(path: &str, prefix: &str) -> bool {
3174    path == prefix
3175        || path
3176            .strip_prefix(prefix)
3177            .is_some_and(|suffix| suffix.starts_with('/'))
3178}
3179
3180fn require_new_destination(destination: &Path) -> Result<(), ChangeSetError> {
3181    if destination.as_os_str().is_empty() || destination.exists() {
3182        return Err(invalid(
3183            "invalid_checkout_request",
3184            "checkout destination must be new and absent",
3185        ));
3186    }
3187    let parent = destination.parent().ok_or_else(|| {
3188        invalid(
3189            "invalid_checkout_request",
3190            "checkout destination has no parent",
3191        )
3192    })?;
3193    let metadata = fs::symlink_metadata(parent).map_err(operational)?;
3194    if !metadata.is_dir() || metadata.file_type().is_symlink() {
3195        return Err(invalid(
3196            "invalid_checkout_request",
3197            "checkout parent must be a no-follow directory",
3198        ));
3199    }
3200    Ok(())
3201}
3202
3203fn copy_regular_verified(
3204    source: &Path,
3205    target: &Path,
3206    expected_sha256: &str,
3207    expected_bytes: u64,
3208    executable: bool,
3209) -> Result<(), ChangeSetError> {
3210    let source_metadata = fs::symlink_metadata(source).map_err(operational)?;
3211    if !source_metadata.is_file()
3212        || source_metadata.file_type().is_symlink()
3213        || source_metadata.len() != expected_bytes
3214    {
3215        return Err(operational_message(
3216            "source changed before checkout materialization",
3217        ));
3218    }
3219    let mut input = File::open(source).map_err(operational)?;
3220    let mut options = OpenOptions::new();
3221    options.write(true).create_new(true);
3222    let mut output = options.open(target).map_err(operational)?;
3223    let mut hasher = Sha256::new();
3224    let mut observed = 0_u64;
3225    let mut buffer = [0_u8; IO_BUFFER_BYTES];
3226    loop {
3227        let read = input.read(&mut buffer).map_err(operational)?;
3228        if read == 0 {
3229            break;
3230        }
3231        observed = observed
3232            .checked_add(read as u64)
3233            .ok_or_else(|| operational_message("source byte length overflowed"))?;
3234        if observed > expected_bytes {
3235            return Err(operational_message(
3236                "source grew during checkout materialization",
3237            ));
3238        }
3239        hasher.update(&buffer[..read]);
3240        output.write_all(&buffer[..read]).map_err(operational)?;
3241    }
3242    output.sync_all().map_err(operational)?;
3243    if observed != expected_bytes || format!("{:x}", hasher.finalize()) != expected_sha256 {
3244        return Err(operational_message(
3245            "source changed during checkout materialization",
3246        ));
3247    }
3248    set_executable(target, executable)?;
3249    Ok(())
3250}
3251
3252#[cfg(unix)]
3253fn set_executable(path: &Path, executable: bool) -> Result<(), ChangeSetError> {
3254    use std::os::unix::fs::PermissionsExt;
3255    let mode = if executable { 0o700 } else { 0o600 };
3256    fs::set_permissions(path, fs::Permissions::from_mode(mode)).map_err(operational)
3257}
3258
3259#[cfg(not(unix))]
3260fn set_executable(_path: &Path, _executable: bool) -> Result<(), ChangeSetError> {
3261    Ok(())
3262}
3263
3264#[cfg(unix)]
3265fn materialize_symlink(destination: &Path, path: &str, target: &str) -> Result<(), ChangeSetError> {
3266    use std::os::unix::fs::symlink;
3267    let link = resolve_portable(destination, path)?;
3268    if let Some(parent) = link.parent() {
3269        fs::create_dir_all(parent).map_err(operational)?;
3270    }
3271    symlink(target, link).map_err(operational)
3272}
3273
3274#[cfg(windows)]
3275fn materialize_symlink(destination: &Path, path: &str, target: &str) -> Result<(), ChangeSetError> {
3276    use std::os::windows::fs::symlink_file;
3277    let link = resolve_portable(destination, path)?;
3278    if let Some(parent) = link.parent() {
3279        fs::create_dir_all(parent).map_err(operational)?;
3280    }
3281    symlink_file(target, link).map_err(operational)
3282}
3283
3284fn create_new_file(path: &Path, bytes: &[u8]) -> Result<(), ChangeSetError> {
3285    let mut options = OpenOptions::new();
3286    options.write(true).create_new(true);
3287    let mut file = options.open(path).map_err(operational)?;
3288    file.write_all(bytes).map_err(operational)?;
3289    file.sync_all().map_err(operational)
3290}
3291
3292#[cfg(not(windows))]
3293fn sync_directory(path: &Path) -> Result<(), ChangeSetError> {
3294    File::open(path)
3295        .and_then(|directory| directory.sync_all())
3296        .map_err(operational)
3297}
3298
3299#[cfg(windows)]
3300fn sync_directory(_path: &Path) -> Result<(), ChangeSetError> {
3301    Ok(())
3302}
3303
3304fn encode_pretty_bounded(value: &impl Serialize, maximum: u64) -> Result<Vec<u8>, ChangeSetError> {
3305    let mut encoded = serde_json::to_vec_pretty(value).map_err(operational)?;
3306    encoded.push(b'\n');
3307    if encoded.len() as u64 > maximum {
3308        return Err(operational_message(
3309            "encoded Change Set record exceeds its bound",
3310        ));
3311    }
3312    Ok(encoded)
3313}
3314
3315fn resolve_portable(root: &Path, path: &str) -> Result<PathBuf, ChangeSetError> {
3316    validate_portable_path(path)?;
3317    let mut resolved = root.to_path_buf();
3318    for component in Path::new(path).components() {
3319        let Component::Normal(component) = component else {
3320            return Err(invalid(
3321                "invalid_projection_receipt",
3322                "path is not portable",
3323            ));
3324        };
3325        resolved.push(component);
3326    }
3327    Ok(resolved)
3328}
3329
3330fn validate_portable_path(path: &str) -> Result<(), ChangeSetError> {
3331    validate_capture_path(path)
3332        .map_err(|_| invalid("invalid_projection_receipt", "path is not portable"))
3333}
3334
3335fn collision_key(path: &str) -> String {
3336    path.chars().case_fold().collect::<String>().nfc().collect()
3337}
3338
3339fn nfc_key(path: &str) -> String {
3340    path.nfc().collect()
3341}
3342
3343fn valid_prefixed_uuid(value: &str, prefix: &str) -> bool {
3344    value
3345        .strip_prefix(prefix)
3346        .and_then(|suffix| Uuid::parse_str(suffix).ok())
3347        .is_some()
3348}
3349
3350fn is_sha256(value: &str) -> bool {
3351    value.len() == 64
3352        && value
3353            .bytes()
3354            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
3355}
3356
3357fn invalid(code: &'static str, message: impl Into<String>) -> ChangeSetError {
3358    ChangeSetError::Invalid {
3359        code,
3360        message: message.into(),
3361    }
3362}
3363
3364fn operational(error: impl std::fmt::Display) -> ChangeSetError {
3365    ChangeSetError::Operational {
3366        code: "change_set_operational_error",
3367        message: error.to_string(),
3368    }
3369}
3370
3371fn operational_message(message: impl Into<String>) -> ChangeSetError {
3372    ChangeSetError::Operational {
3373        code: "change_set_operational_error",
3374        message: message.into(),
3375    }
3376}
3377
3378fn capture_operational(error: FolderbaseCaptureError) -> ChangeSetError {
3379    operational(error)
3380}