Skip to main content

dort_core/
adoption.rs

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