Skip to main content

dort_core/
adoption.rs

1//! Recoverable one-file adoption. Apply and unmanage live in lifecycle.
2use crate::{
3    Error, Manifest, Result,
4    context::HostContext,
5    error::io_error,
6    journal::{self, Header, Journal, Operation, Phase, Progress, Role},
7    model::ManagedFile,
8    observation::{self, Entry, Fingerprint, Kind, Parent},
9    planner::{self, Plan, Request},
10    state::WriterLock,
11};
12use rustix::fs::{self, Mode, OFlags, RenameFlags};
13use serde::Serialize;
14use std::{
15    collections::BTreeMap,
16    fs::File,
17    path::{Path, PathBuf},
18    sync::atomic::{AtomicU64, Ordering},
19    time::{SystemTime, UNIX_EPOCH},
20};
21
22/// Not deserializable. A preview JSON document can never be passed directly to execution.
23pub struct Approval {
24    plan: Plan,
25    digest: String,
26}
27
28impl Approval {
29    /// An explicit caller approval boundary, not an interactive prompt. The caller must
30    /// privately review the destination content and present the preview before calling.
31    pub fn from_plan(plan: Plan) -> Result<Self> {
32        if !matches!(plan.inputs.request, Request::Adopt { .. })
33            || plan.files.len() != 1
34            || plan.has_blockers()
35            || canonical(&plan)? != canonical(&planner::plan(plan.inputs.clone()))?
36        {
37            return Err(Error::Invalid(
38                "approval requires an unmodified, unblocked one-file adoption plan".into(),
39            ));
40        }
41        let digest = journal::digest(canonical(&plan)?.as_bytes());
42        Ok(Self { plan, digest })
43    }
44    pub fn sha256(&self) -> &str {
45        &self.digest
46    }
47}
48
49// Directory timestamps/link counts change when state or siblings are created. Bind their
50// identities, ownership and permissions, not unrelated directory churn.
51pub(crate) fn canonical(plan: &impl Serialize) -> Result<String> {
52    let mut value =
53        serde_json::to_value(plan).map_err(|_| Error::Invalid("cannot encode approval".into()))?;
54    fn normalize(value: &mut serde_json::Value) {
55        match value {
56            serde_json::Value::Object(map) => {
57                for (key, value) in map {
58                    if key == "parents" {
59                        if let Some(parents) = value.as_array_mut() {
60                            for parent in parents {
61                                if let Some(fp) = parent
62                                    .get_mut("fingerprint")
63                                    .and_then(|f| f.as_object_mut())
64                                {
65                                    for field in ["size", "modified", "changed", "links"] {
66                                        fp.remove(field);
67                                    }
68                                }
69                            }
70                        }
71                    } else {
72                        normalize(value);
73                    }
74                }
75            }
76            serde_json::Value::Array(values) => values.iter_mut().for_each(normalize),
77            _ => {}
78        }
79    }
80    normalize(&mut value);
81    journal::encode(&value)
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum Boundary {
86    Checkpoint,
87    Mutation,
88}
89
90/// Progress callbacks also support deterministic error/crash testing without environment
91/// switches in production code. Errors leave durable intent; nothing auto-rolls back.
92#[derive(Debug)]
93pub struct Event {
94    pub transaction_id: String,
95    pub boundary: Boundary,
96    pub sequence: usize,
97}
98
99fn notify(
100    journal: &Journal,
101    boundary: Boundary,
102    observer: &mut impl FnMut(&Event) -> Result<()>,
103) -> Result<()> {
104    observer(&Event {
105        transaction_id: journal.record.header.transaction_id.clone(),
106        boundary,
107        sequence: journal.record.sequence,
108    })
109}
110fn checkpoint(
111    journal: &mut Journal,
112    observer: &mut impl FnMut(&Event) -> Result<()>,
113) -> Result<()> {
114    journal.save()?;
115    notify(journal, Boundary::Checkpoint, observer)
116}
117
118pub(crate) fn transaction_id() -> String {
119    static NEXT: AtomicU64 = AtomicU64::new(0);
120    journal::digest(
121        format!(
122            "{}-{}-{}",
123            std::process::id(),
124            SystemTime::now()
125                .duration_since(UNIX_EPOCH)
126                .unwrap_or_default()
127                .as_nanos(),
128            NEXT.fetch_add(1, Ordering::Relaxed)
129        )
130        .as_bytes(),
131    )
132}
133
134pub(crate) fn parent_identity(a: &Fingerprint, b: &Fingerprint) -> bool {
135    a.device == b.device
136        && a.inode == b.inode
137        && a.mode == b.mode
138        && a.uid == b.uid
139        && a.gid == b.gid
140}
141
142pub(crate) fn same(a: &Entry, b: &Entry, strict: bool) -> bool {
143    if a.kind != b.kind || a.link_target != b.link_target || a.sha256 != b.sha256 {
144        return false;
145    }
146    match (&a.fingerprint, &b.fingerprint) {
147        (None, None) => true,
148        (Some(a), Some(b)) if a.mode & 0o170000 == 0o040000 => parent_identity(a, b),
149        (Some(a), Some(b)) => {
150            let mut a = a.clone();
151            let mut b = b.clone();
152            if !strict {
153                a.changed = (0, 0);
154                b.changed = (0, 0);
155            }
156            a == b
157        }
158        _ => false,
159    }
160}
161
162fn inspect(path: &Path, role: Role) -> Result<Entry> {
163    if role == Role::Manifest && observation::inspect(path, false)?.kind == Kind::Regular {
164        observation::read_manifest(path).map(|(_, entry)| entry)
165    } else {
166        observation::inspect(path, true)
167    }
168}
169
170pub(crate) fn checked_bytes(entry: &Entry) -> Result<Vec<u8>> {
171    let handle = observation::parent_handle(&entry.path)?;
172    let bytes = observation::read_checked(
173        &handle,
174        &entry.path,
175        entry
176            .fingerprint
177            .as_ref()
178            .ok_or_else(|| Error::Invalid("missing regular-file fingerprint".into()))?,
179    )?;
180    if entry.sha256.as_deref() != Some(&journal::digest(&bytes)) {
181        return Err(Error::Invalid("approved content changed".into()));
182    }
183    Ok(bytes)
184}
185
186fn stage_name(id: usize) -> String {
187    format!("op-{id:04}")
188}
189fn stage_path(journal: &Journal, id: usize) -> PathBuf {
190    journal.directory.path.join(stage_name(id))
191}
192
193fn stage_file(journal: &Journal, id: usize, bytes: &[u8], mode: u32, gid: u32) -> Result<()> {
194    let name = stage_name(id);
195    journal.directory.create(&name, bytes)?;
196    let file = File::from(
197        fs::openat(
198            &journal.directory.file,
199            name.as_str(),
200            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
201            Mode::empty(),
202        )
203        .map_err(|e| io_error("open prepared file", &journal.directory.path, e))?,
204    );
205    fs::fchown(&file, None, Some(rustix::process::Gid::from_raw(gid)))
206        .map_err(|e| io_error("preserve prepared file group", &journal.directory.path, e))?;
207    fs::fchmod(&file, Mode::from_bits_truncate(mode as _))
208        .map_err(|e| io_error("set prepared file permissions", &journal.directory.path, e))?;
209    file.sync_all()
210        .map_err(|e| io_error("sync prepared file", &journal.directory.path, e))?;
211    journal.directory.sync()
212}
213
214pub(crate) fn anchors(entries: &[&Entry]) -> Vec<Parent> {
215    let mut all = BTreeMap::new();
216    for entry in entries {
217        for parent in &entry.parents {
218            all.insert(parent.path.clone(), parent.clone());
219        }
220    }
221    all.into_values().collect()
222}
223
224fn check_parents(journal: &Journal, entry: &Entry) -> Result<()> {
225    for actual in &entry.parents {
226        let expected = journal
227            .record
228            .header
229            .anchors
230            .iter()
231            .find(|p| p.path == actual.path)
232            .map(|p| &p.fingerprint)
233            .or_else(|| {
234                journal
235                    .record
236                    .operations
237                    .iter()
238                    .find(|op| op.role == Role::Directory && op.before.path == actual.path)
239                    .and_then(|op| op.staged.fingerprint.as_ref())
240            });
241        if expected.is_none_or(|expected| !parent_identity(expected, &actual.fingerprint)) {
242            return Err(Error::Invalid(
243                "parent identity/permissions changed; transaction refused".into(),
244            ));
245        }
246    }
247    Ok(())
248}
249
250fn check_configuration(host: &HostContext, journal: &Journal) -> Result<()> {
251    journal::registered_root(
252        host,
253        &journal.record.header.repository_id,
254        &journal.record.header.repository,
255    )?;
256    let current = observation::inspect(&host.local_config_path(), false)?;
257    if !same(&journal.record.header.local_config, &current, true) {
258        return Err(Error::Invalid(
259            "local configuration changed since approval".into(),
260        ));
261    }
262    check_parents(journal, &current)
263}
264
265/// Requires a registered repository and the application lock. Only a freshly revalidated,
266/// explicitly approved adoption is accepted. Returns a retained transaction ID.
267pub fn execute(
268    host: &HostContext,
269    lock: &WriterLock,
270    approval: Approval,
271    mut observer: impl FnMut(&Event) -> Result<()>,
272) -> Result<String> {
273    lock.check_context(host)?;
274    journal::ensure_writable(host)?;
275    let inputs = &approval.plan.inputs;
276    if journal::encode(host)? != journal::encode(&inputs.host)? {
277        return Err(Error::Invalid(
278            "approval belongs to another host context".into(),
279        ));
280    }
281    let profiles: Vec<_> = inputs.active_profiles.iter().cloned().collect();
282    let fresh = planner::plan(planner::observe(
283        host,
284        &inputs.repository,
285        &inputs.temporary_profiles,
286        inputs.request.clone(),
287    )?);
288    if fresh.has_blockers() || journal::digest(canonical(&fresh)?.as_bytes()) != approval.digest {
289        return Err(Error::Invalid(
290            "stale or substituted adoption plan; observe and approve again".into(),
291        ));
292    }
293    let local = crate::local::LocalConfig::load(host)?;
294    let repository_id = local
295        .repositories
296        .iter()
297        .find(|(_, record)| record.root == inputs.repository)
298        .map(|(id, _)| id.clone())
299        .ok_or_else(|| Error::Invalid("adoption requires a registered repository".into()))?;
300    let file = &fresh.inputs.files[0];
301    let source = file
302        .source
303        .as_ref()
304        .ok_or_else(|| Error::Invalid("missing adoption source".into()))?;
305    let destination = file
306        .destination
307        .as_ref()
308        .ok_or_else(|| Error::Invalid("missing adoption destination".into()))?;
309    if fresh
310        .inputs
311        .manifest
312        .fingerprint
313        .as_ref()
314        .is_none_or(|f| f.mode & 0o7000 != 0)
315    {
316        return Err(Error::Invalid(
317            "manifest must not have special permission bits".into(),
318        ));
319    }
320    let manifest_bytes = checked_bytes(&fresh.inputs.manifest)?;
321    let destination_bytes = checked_bytes(destination)?;
322    #[derive(Serialize)]
323    struct Addition<'a> {
324        files: Vec<&'a ManagedFile>,
325    }
326    let addition = toml::to_string(&Addition {
327        files: vec![&file.mapping],
328    })
329    .map_err(|_| Error::Invalid("cannot encode adoption mapping".into()))?;
330    let new_manifest = format!(
331        "{}\n{}",
332        std::str::from_utf8(&manifest_bytes)
333            .map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?,
334        addition
335    );
336    Manifest::parse(&new_manifest)?.validate_selection(
337        host,
338        &inputs.active_profiles,
339        Some(&inputs.repository),
340    )?;
341    let header = Header {
342        repository_id,
343        repository: inputs.repository.clone(),
344        transaction_id: transaction_id(),
345        approved_plan_sha256: approval.digest,
346        mapping: file.mapping.clone(),
347        profiles,
348        manifest: fresh.inputs.manifest.clone(),
349        destination: destination.clone(),
350        source: source.clone(),
351        local_config: fresh.inputs.local_config.clone(),
352        anchors: anchors(&[
353            &fresh.inputs.manifest,
354            destination,
355            source,
356            &fresh.inputs.local_config,
357        ]),
358        manifest_backup_sha256: journal::digest(&manifest_bytes),
359        destination_backup_sha256: journal::digest(&destination_bytes),
360    };
361    let mut journal = Journal::begin(host, header)?;
362    notify(&journal, Boundary::Checkpoint, &mut observer)?;
363    journal
364        .directory
365        .create("manifest.backup", &manifest_bytes)?;
366    journal
367        .directory
368        .create("destination.backup", &destination_bytes)?;
369    journal.verify_backups()?;
370    let device = Fingerprint::from_stat(
371        &fs::fstat(&journal.directory.file)
372            .map_err(|e| io_error("inspect transaction filesystem", &journal.directory.path, e))?,
373    )
374    .device;
375    // No cross-filesystem fallback: every publication/inverse must be an atomic rename.
376    for entry in [&fresh.inputs.manifest, destination, source] {
377        if entry
378            .parents
379            .last()
380            .is_none_or(|p| p.fingerprint.device != device)
381            || entry
382                .fingerprint
383                .as_ref()
384                .is_some_and(|f| f.device != device)
385        {
386            return Err(Error::Invalid(
387                "adoption requires repository, destination and transaction state on one filesystem"
388                    .into(),
389            ));
390        }
391        if entry
392            .parents
393            .last()
394            .is_none_or(|p| p.fingerprint.uid != fresh.inputs.user_id)
395        {
396            return Err(Error::Invalid(
397                "live file parents must be owned by this user".into(),
398            ));
399        }
400    }
401    let mut directories = vec![];
402    let mut parent = file
403        .source_path
404        .parent()
405        .ok_or_else(|| Error::Invalid("missing source parent directory".into()))?;
406    while observation::inspect(parent, false)?.kind == Kind::Missing {
407        directories.push(parent.to_owned());
408        parent = parent
409            .parent()
410            .ok_or_else(|| Error::Invalid("missing repository root".into()))?;
411    }
412    directories.reverse();
413    let mut roles: Vec<_> = directories
414        .into_iter()
415        .map(|path| (Role::Directory, path))
416        .collect();
417    roles.extend([
418        (Role::Source, file.source_path.clone()),
419        (Role::Manifest, inputs.manifest.path.clone()),
420        (Role::Destination, file.target_path.clone()),
421    ]);
422    let destination_fingerprint = destination
423        .fingerprint
424        .as_ref()
425        .ok_or_else(|| Error::Invalid("missing destination fingerprint".into()))?;
426    let manifest_fingerprint = inputs
427        .manifest
428        .fingerprint
429        .as_ref()
430        .ok_or_else(|| Error::Invalid("missing manifest fingerprint".into()))?;
431    for (id, (role, path)) in roles.into_iter().enumerate() {
432        let name = stage_name(id);
433        match role {
434            Role::Directory => {
435                fs::mkdirat(
436                    &journal.directory.file,
437                    name.as_str(),
438                    Mode::RUSR | Mode::WUSR | Mode::XUSR,
439                )
440                .map_err(|e| io_error("prepare source parent", &journal.directory.path, e))?;
441                let fd = File::from(
442                    fs::openat(
443                        &journal.directory.file,
444                        name.as_str(),
445                        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
446                        Mode::empty(),
447                    )
448                    .map_err(|e| io_error("open prepared directory", &journal.directory.path, e))?,
449                );
450                fd.sync_all()
451                    .map_err(|e| io_error("sync prepared directory", &journal.directory.path, e))?;
452            }
453            Role::Source => stage_file(
454                &journal,
455                id,
456                &destination_bytes,
457                destination_fingerprint.mode & 0o777,
458                destination_fingerprint.gid,
459            )?,
460            Role::Manifest => stage_file(
461                &journal,
462                id,
463                new_manifest.as_bytes(),
464                manifest_fingerprint.mode & 0o777,
465                manifest_fingerprint.gid,
466            )?,
467            Role::Destination => {
468                fs::symlinkat(&file.source_path, &journal.directory.file, name.as_str())
469                    .map_err(|e| io_error("prepare destination link", &journal.directory.path, e))?
470            }
471        }
472        journal.directory.sync()?;
473        let before = match role {
474            Role::Source => journal.record.header.source.clone(),
475            Role::Manifest => journal.record.header.manifest.clone(),
476            Role::Destination => journal.record.header.destination.clone(),
477            Role::Directory => inspect(&path, role)?,
478        };
479        let staged = inspect(&stage_path(&journal, id), role)?;
480        journal.record.operations.push(Operation {
481            id,
482            role,
483            before,
484            staged,
485            after: None,
486            progress: Progress::Pending,
487        });
488    }
489    journal.record.phase = Phase::Running;
490    checkpoint(&mut journal, &mut observer)?;
491    validate_layout(host, &journal)?;
492    for id in 0..journal.record.operations.len() {
493        check_configuration(host, &journal)?;
494        validate_layout(host, &journal)?;
495        journal.verify_backups()?;
496        journal.record.operations[id].progress = Progress::Intent;
497        checkpoint(&mut journal, &mut observer)?;
498        validate_layout(host, &journal)?;
499        journal.verify_backups()?;
500        mutate(&journal, id, false)?;
501        notify(&journal, Boundary::Mutation, &mut observer)?;
502        let after = inspect(
503            &journal.record.operations[id].before.path,
504            journal.record.operations[id].role,
505        )?;
506        if !same(&journal.record.operations[id].staged, &after, false) {
507            return Err(Error::Invalid("adoption postcondition mismatch".into()));
508        }
509        journal.record.operations[id].after = Some(after);
510        journal.record.operations[id].progress = Progress::Done;
511        checkpoint(&mut journal, &mut observer)?;
512    }
513    journal.record.phase = Phase::Verifying;
514    checkpoint(&mut journal, &mut observer)?;
515    validate_layout(host, &journal)?;
516    journal.verify_backups()?;
517    journal.record.phase = Phase::Completed;
518    checkpoint(&mut journal, &mut observer)?;
519    Ok(journal.record.header.transaction_id)
520}
521
522// Resolve an intent interrupted immediately before/after its atomic rename. Inode,
523// content, mode and mtime must match; ctime alone changes as a consequence of rename.
524fn applied(journal: &Journal, op: &Operation) -> Result<bool> {
525    let live = inspect(&op.before.path, op.role)?;
526    check_parents(journal, &live)?;
527    let stage = inspect(&stage_path(journal, op.id), op.role)?;
528    let before = same(&op.before, &live, op.progress == Progress::Pending)
529        && same(&op.staged, &stage, op.progress == Progress::Pending);
530    let after = same(&op.staged, &live, false)
531        && if matches!(op.role, Role::Directory | Role::Source) {
532            stage.kind == Kind::Missing
533        } else {
534            same(&op.before, &stage, false)
535        };
536    match op.progress {
537        Progress::Pending if before => Ok(false),
538        Progress::Intent | Progress::UndoIntent if before => Ok(false),
539        Progress::Intent | Progress::UndoIntent if after => Ok(true),
540        Progress::Done
541            if after
542                && op
543                    .after
544                    .as_ref()
545                    .is_some_and(|expected| same(expected, &live, true)) =>
546        {
547            Ok(true)
548        }
549        Progress::Undone if before => Ok(false),
550        _ => Err(Error::Invalid(
551            "transaction guard mismatch (file, source, stage or parent edited); recovery refused"
552                .into(),
553        )),
554    }
555}
556
557fn validate_layout(host: &HostContext, journal: &Journal) -> Result<()> {
558    check_configuration(host, journal)?;
559    let states: Vec<_> = journal
560        .record
561        .operations
562        .iter()
563        .map(|op| applied(journal, op))
564        .collect::<Result<_>>()?;
565    for op in &journal.record.operations {
566        if op.role != Role::Directory {
567            continue;
568        }
569        let path = if states[op.id] {
570            op.before.path.clone()
571        } else {
572            stage_path(journal, op.id)
573        };
574        let mut expected: Vec<_> = journal
575            .record
576            .operations
577            .iter()
578            .filter(|child| {
579                states[op.id]
580                    && states[child.id]
581                    && child.before.path.parent() == Some(op.before.path.as_path())
582            })
583            .map(|child| {
584                child
585                    .before
586                    .path
587                    .file_name()
588                    .map(|name| name.to_owned())
589                    .ok_or_else(|| Error::Invalid("missing source directory entry name".into()))
590            })
591            .collect::<Result<Vec<_>>>()?;
592        expected.sort();
593        if observation::names(&path, 4096)? != expected {
594            return Err(Error::Invalid(
595                "created/prepared source directory contains unapproved entries; recovery refused"
596                    .into(),
597            ));
598        }
599    }
600    Ok(())
601}
602
603fn mutate(journal: &Journal, id: usize, undo: bool) -> Result<()> {
604    let op = &journal.record.operations[id];
605    let live = observation::parent_handle(&op.before.path)?;
606    if live.missing {
607        return Err(Error::Invalid("operation parent is missing".into()));
608    }
609    let current = inspect(&op.before.path, op.role)?;
610    check_parents(journal, &current)?;
611    // Re-opened descriptors must refer to the same parents just validated by name.
612    if live.parents.len() != current.parents.len() {
613        return Err(Error::Invalid(
614            "parent disappeared during transaction".into(),
615        ));
616    }
617    for (a, b) in live.parents.iter().zip(&current.parents) {
618        if a.path != b.path || !parent_identity(&a.fingerprint, &b.fingerprint) {
619            return Err(Error::Invalid(
620                "parent substituted during transaction".into(),
621            ));
622        }
623    }
624    let is_applied = applied(journal, op)?;
625    if is_applied != undo {
626        return Err(Error::Invalid(
627            "operation is not at the expected precondition".into(),
628        ));
629    }
630    let name = stage_name(id);
631    let created = matches!(op.role, Role::Directory | Role::Source);
632    if undo && op.role == Role::Directory && !observation::names(&op.before.path, 1)?.is_empty() {
633        return Err(Error::Invalid(
634            "created source directory is no longer empty".into(),
635        ));
636    }
637    let flags = if created {
638        RenameFlags::NOREPLACE
639    } else {
640        RenameFlags::EXCHANGE
641    };
642    let result = if undo && created {
643        fs::renameat_with(
644            &live.directory,
645            &live.name,
646            &journal.directory.file,
647            name.as_str(),
648            flags,
649        )
650    } else {
651        fs::renameat_with(
652            &journal.directory.file,
653            name.as_str(),
654            &live.directory,
655            &live.name,
656            flags,
657        )
658    };
659    result.map_err(|e| {
660        io_error(
661            "publish/invert journalled rename (no unsafe fallback)",
662            &op.before.path,
663            e,
664        )
665    })?;
666    live.directory
667        .sync_all()
668        .map_err(|e| io_error("sync live parent", &op.before.path, e))?;
669    journal.directory.sync()
670}
671
672/// Read-only preflight and conservative inverse paths for the head-bound recovery service.
673pub(crate) fn rollback_preview(
674    host: &HostContext,
675    repository_id: &str,
676    transaction_id: &str,
677) -> Result<(String, Vec<PathBuf>)> {
678    let j = Journal::open(host, repository_id, transaction_id)?;
679    validate_record(host, &j)?;
680    if !matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
681        j.verify_backups()?;
682        validate_layout(host, &j)?;
683    }
684    let effects = if matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
685        vec![]
686    } else {
687        j.record
688            .operations
689            .iter()
690            .rev()
691            .filter(|o| o.progress != Progress::Undone)
692            .map(|o| o.before.path.clone())
693            .collect()
694    };
695    Ok((
696        journal::digest(journal::encode(&j.record)?.as_bytes()),
697        effects,
698    ))
699}
700
701/// Explicit guarded rollback, never startup replay. Can also undo a completed adoption.
702/// Preflight ALL guards (including linked-source content) before changing anything.
703pub fn rollback(
704    host: &HostContext,
705    lock: &WriterLock,
706    repository_id: &str,
707    transaction_id: &str,
708    mut observer: impl FnMut(&Event) -> Result<()>,
709) -> Result<()> {
710    lock.check_context(host)?;
711    let mut journal = Journal::open(host, repository_id, transaction_id)?;
712    validate_record(host, &journal)?;
713    if journal.record.phase == Phase::RolledBack {
714        return Ok(());
715    }
716    if journal.record.phase == Phase::Preparing {
717        // Only private staging/backups may exist; no live effects can precede Running.
718        journal.record.phase = Phase::RolledBack;
719        return checkpoint(&mut journal, &mut observer);
720    }
721    journal.verify_backups()?;
722    validate_layout(host, &journal)?;
723    if journal.record.phase != Phase::RollingBack {
724        journal.record.phase = Phase::RollingBack;
725        checkpoint(&mut journal, &mut observer)?;
726    }
727    for id in (0..journal.record.operations.len()).rev() {
728        if journal.record.operations[id].progress == Progress::Undone {
729            continue;
730        }
731        validate_layout(host, &journal)?;
732        let was_applied = applied(&journal, &journal.record.operations[id])?;
733        journal.record.operations[id].progress = Progress::UndoIntent;
734        checkpoint(&mut journal, &mut observer)?;
735        validate_layout(host, &journal)?;
736        journal.verify_backups()?;
737        if was_applied {
738            mutate(&journal, id, true)?;
739            notify(&journal, Boundary::Mutation, &mut observer)?;
740        }
741        journal.record.operations[id].progress = Progress::Undone;
742        checkpoint(&mut journal, &mut observer)?;
743    }
744    validate_layout(host, &journal)?;
745    journal.record.phase = Phase::RolledBack;
746    checkpoint(&mut journal, &mut observer)
747}
748
749// Check scope independently of checksums. Journal strings are never arbitrary write paths.
750fn validate_record(host: &HostContext, journal: &Journal) -> Result<()> {
751    let h = &journal.record.header;
752    journal::registered_root(host, &h.repository_id, &h.repository)?;
753    observation::validate_output_path(&h.repository)?;
754    if h.source.path != h.repository.join(&h.mapping.source)
755        || h.destination.path != host.target_path(&h.mapping.target, Some(&h.repository))?
756        || h.manifest.path != h.repository.join("dort.toml")
757        || h.local_config.path != host.local_config_path()
758    {
759        return Err(Error::Invalid(
760            "journal paths do not match adoption scope".into(),
761        ));
762    }
763    let mut minimal = Manifest::parse("schema=1\n")?;
764    minimal.files.push(h.mapping.clone());
765    minimal.profiles.available = h
766        .profiles
767        .iter()
768        .chain(&h.mapping.profiles)
769        .filter(|p| p.as_str() != "base")
770        .cloned()
771        .collect::<std::collections::BTreeSet<_>>()
772        .into_iter()
773        .collect();
774    minimal.validate_for_host(host, &h.profiles, Some(&h.repository))?;
775    if h.mapping.mode != crate::model::FileMode::Link
776        || !h.mapping.requires.is_empty()
777        || !h.mapping.overrides.is_empty()
778    {
779        return Err(Error::Invalid("unsupported journal mapping".into()));
780    }
781    if journal.record.phase != Phase::Preparing
782        && !(journal.record.phase == Phase::RolledBack && journal.record.operations.is_empty())
783    {
784        let n = journal.record.operations.len();
785        if n < 3 {
786            return Err(Error::Invalid("incomplete adoption operation set".into()));
787        }
788        let mut previous_dir: Option<&Path> = None;
789        for (id, op) in journal.record.operations.iter().enumerate() {
790            let (role, path) = if id == n - 3 {
791                (Role::Source, &h.source.path)
792            } else if id == n - 2 {
793                (Role::Manifest, &h.manifest.path)
794            } else if id == n - 1 {
795                (Role::Destination, &h.destination.path)
796            } else {
797                let source_parent = h
798                    .source
799                    .path
800                    .parent()
801                    .ok_or_else(|| Error::Invalid("missing source parent directory".into()))?;
802                if !op.before.path.starts_with(&h.repository)
803                    || op.before.path == h.repository
804                    || !source_parent.starts_with(&op.before.path)
805                    || previous_dir.is_some_and(|p| op.before.path.parent() != Some(p))
806                {
807                    return Err(Error::Invalid("invalid source parent operation".into()));
808                }
809                previous_dir = Some(op.before.path.as_path());
810                (Role::Directory, &op.before.path)
811            };
812            if op.id != id
813                || op.role != role
814                || &op.before.path != path
815                || op.staged.path != stage_path(journal, id)
816            {
817                return Err(Error::Invalid(
818                    "invalid journal operation ID/path/order".into(),
819                ));
820            }
821        }
822    }
823    Ok(())
824}