Skip to main content

dort_core/
lifecycle.rs

1//! File apply and unmanage with rollback records.
2pub use crate::adoption::{Boundary, Event};
3use crate::{
4    Error, Manifest, Result,
5    adoption::{self, anchors, canonical, checked_bytes, parent_identity, same},
6    context::HostContext,
7    error::io_error,
8    journal::{self, Phase, Progress},
9    lifecycle_journal::{self as wire, Action, Header, Journal, Mutation, Operation, Role, Watch},
10    observation::{self, Entry, Fingerprint, Kind},
11    planner::{self, Outcome, Plan, Request, UnmanageMode},
12    profiles::selected,
13    state::WriterLock,
14};
15use rustix::fs::{self, Mode, OFlags, RenameFlags};
16use std::{
17    fs::File,
18    path::{Path, PathBuf},
19};
20
21/// Separate caller confirmation, not preview deserialization or a generic approval flag.
22pub struct RemovalAcknowledgement {
23    id: String,
24}
25impl RemovalAcknowledgement {
26    /// Call only after separately presenting/confirming deletion of this mapping's link.
27    pub fn confirm(id: impl Into<String>) -> Self {
28        Self { id: id.into() }
29    }
30}
31/// Opaque and not deserializable. The caller must present and explicitly approve the plan.
32pub struct Approval {
33    plan: Plan,
34    digest: String,
35}
36impl Approval {
37    pub fn from_plan(plan: Plan) -> Result<Self> {
38        Self::approve(plan, None)
39    }
40    pub fn from_removal_plan(plan: Plan, acknowledgement: RemovalAcknowledgement) -> Result<Self> {
41        Self::approve(plan, Some(acknowledgement))
42    }
43    fn approve(plan: Plan, ack: Option<RemovalAcknowledgement>) -> Result<Self> {
44        let valid = match (&plan.inputs.request, ack) {
45            (
46                Request::Apply
47                | Request::Unmanage {
48                    mode: UnmanageMode::Keep,
49                    ..
50                },
51                None,
52            ) => true,
53            (
54                Request::Unmanage {
55                    id,
56                    mode: UnmanageMode::Remove,
57                },
58                Some(ack),
59            ) => *id == ack.id,
60            _ => false,
61        };
62        if !valid
63            || plan.has_blockers()
64            || plan.inputs.files.len() > 128
65            || canonical(&plan)? != canonical(&planner::plan(plan.inputs.clone()))?
66        {
67            return Err(Error::Invalid("approval requires an unmodified, unblocked lifecycle plan; removal needs separate matching acknowledgement".into()));
68        }
69        let digest = journal::digest(canonical(&plan)?.as_bytes());
70        Ok(Self { plan, digest })
71    }
72    pub fn sha256(&self) -> &str {
73        &self.digest
74    }
75}
76fn stage_name(id: usize) -> String {
77    format!("op-{id:04}")
78}
79fn stage_path(j: &Journal, id: usize) -> PathBuf {
80    j.directory.path.join(stage_name(id))
81}
82fn inspect(path: &Path, role: Role) -> Result<Entry> {
83    if role == Role::Manifest && observation::inspect(path, false)?.kind == Kind::Regular {
84        observation::read_manifest(path).map(|(_, e)| e)
85    } else {
86        observation::inspect(path, true)
87    }
88}
89fn notify(
90    j: &Journal,
91    boundary: Boundary,
92    observer: &mut impl FnMut(&Event) -> Result<()>,
93) -> Result<()> {
94    observer(&Event {
95        transaction_id: j.record.header.transaction_id.clone(),
96        boundary,
97        sequence: j.record.sequence,
98    })
99}
100fn checkpoint(j: &mut Journal, observer: &mut impl FnMut(&Event) -> Result<()>) -> Result<()> {
101    j.save()?;
102    notify(j, Boundary::Checkpoint, observer)
103}
104fn stage_file(j: &Journal, id: usize, bytes: &[u8], fp: &Fingerprint) -> Result<()> {
105    let name = stage_name(id);
106    j.directory.create(&name, bytes)?;
107    let file = File::from(
108        fs::openat(
109            &j.directory.file,
110            name.as_str(),
111            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
112            Mode::empty(),
113        )
114        .map_err(|e| io_error("open lifecycle preparation", &j.directory.path, e))?,
115    );
116    fs::fchown(&file, None, Some(rustix::process::Gid::from_raw(fp.gid)))
117        .map_err(|e| io_error("preserve prepared group", &j.directory.path, e))?;
118    fs::fchmod(&file, Mode::from_bits_truncate((fp.mode & 0o777) as _))
119        .map_err(|e| io_error("preserve prepared permissions", &j.directory.path, e))?;
120    file.sync_all()
121        .map_err(|e| io_error("sync lifecycle preparation", &j.directory.path, e))?;
122    j.directory.sync()
123}
124
125pub(crate) fn remove_mapping(
126    bytes: &[u8],
127    id: &str,
128    host: &HostContext,
129    repo: &Path,
130    profiles: &[String],
131) -> Result<Vec<u8>> {
132    let text =
133        std::str::from_utf8(bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
134    let mut old = Manifest::parse(text)?;
135    let index = old
136        .files
137        .iter()
138        .position(|f| f.id == id)
139        .ok_or_else(|| Error::Invalid("missing unmanage mapping".into()))?;
140    let mut doc = text
141        .parse::<toml_edit::DocumentMut>()
142        .map_err(|_| Error::Invalid("cannot edit manifest".into()))?;
143    if let Some(array) = doc["files"].as_array_of_tables_mut() {
144        array.remove(index);
145    } else if let Some(array) = doc["files"].as_array_mut() {
146        // Leading array comments are attached to the first value, not the '['.
147        // Carry its prefix forward rather than deleting an unrelated array comment.
148        let removed = array.remove(index);
149        let prefix = removed
150            .decor()
151            .prefix()
152            .and_then(|s| s.as_str())
153            .unwrap_or_default();
154        if let Some(next) = array.get_mut(index) {
155            let next_prefix = next
156                .decor()
157                .prefix()
158                .and_then(|s| s.as_str())
159                .unwrap_or_default();
160            let combined = format!("{prefix}{next_prefix}");
161            next.decor_mut().set_prefix(combined);
162        } else {
163            let trailing = array.trailing().as_str().unwrap_or_default();
164            array.set_trailing(format!("{prefix}{trailing}"));
165        }
166    } else {
167        return Err(Error::Invalid(
168            "unsupported manifest files representation".into(),
169        ));
170    }
171    let new = doc.to_string();
172    let parsed = Manifest::parse(&new)?;
173    parsed.validate_selection(host, &profiles.iter().cloned().collect(), Some(repo))?;
174    old.files.remove(index);
175    if journal::encode(&old)? != journal::encode(&parsed)? {
176        return Err(Error::Invalid(
177            "manifest removal changed unrelated declarations".into(),
178        ));
179    }
180    Ok(new.into_bytes())
181}
182
183/// Returns None on an entirely correct/empty apply; no transaction/backups are created.
184/// One approved request is one transaction. Atomic publications are NOT global atomicity.
185pub fn execute(
186    host: &HostContext,
187    lock: &WriterLock,
188    approval: Approval,
189    observer: impl FnMut(&Event) -> Result<()>,
190) -> Result<Option<String>> {
191    execute_inner(host, lock, approval, None, observer)
192}
193
194pub(crate) fn execute_environment(
195    host: &HostContext,
196    lock: &WriterLock,
197    plan: Plan,
198    id: &str,
199    observer: impl FnMut(&Event) -> Result<()>,
200) -> Result<Option<String>> {
201    let digest = journal::digest(canonical(&plan)?.as_bytes());
202    execute_inner(host, lock, Approval { plan, digest }, Some(id), observer)
203}
204
205fn execute_inner(
206    host: &HostContext,
207    lock: &WriterLock,
208    approval: Approval,
209    environment_id: Option<&str>,
210    mut observer: impl FnMut(&Event) -> Result<()>,
211) -> Result<Option<String>> {
212    lock.check_context(host)?;
213    journal::ensure_writable(host)?;
214    let inputs = &approval.plan.inputs;
215    if journal::encode(host)? != journal::encode(&inputs.host)? {
216        return Err(Error::Invalid("approval belongs to another host".into()));
217    }
218    let profiles: Vec<_> = inputs.active_profiles.iter().cloned().collect();
219    let fresh = if let Some(id) = environment_id {
220        let mut snapshot =
221            planner::observe_environment(host, &inputs.repository, &inputs.temporary_profiles)?;
222        snapshot.files.retain(|file| file.mapping.id == id);
223        planner::plan_environment(snapshot)
224    } else {
225        planner::plan(planner::observe(
226            host,
227            &inputs.repository,
228            &inputs.temporary_profiles,
229            inputs.request.clone(),
230        )?)
231    };
232    if fresh.has_blockers() || journal::digest(canonical(&fresh)?.as_bytes()) != approval.digest {
233        return Err(Error::Invalid(
234            "stale or substituted lifecycle plan; observe and approve again".into(),
235        ));
236    }
237    let local = crate::local::LocalConfig::load(host)?;
238    let repo_id = local
239        .repositories
240        .iter()
241        .find(|(_, r)| r.root == inputs.repository)
242        .map(|(id, _)| id.clone())
243        .ok_or_else(|| {
244            Error::Invalid("lifecycle execution requires a registered repository".into())
245        })?;
246    if fresh
247        .files
248        .iter()
249        .all(|f| matches!(f.outcome, Outcome::NoOp))
250    {
251        return Ok(None);
252    }
253    let action = match inputs.request {
254        Request::Apply => Action::Apply,
255        Request::Unmanage {
256            mode: UnmanageMode::Keep,
257            ..
258        } => Action::Keep,
259        Request::Unmanage {
260            mode: UnmanageMode::Remove,
261            ..
262        } => Action::Remove,
263        _ => return Err(Error::Invalid("unsupported lifecycle request".into())),
264    };
265    let watches: Vec<_> = fresh
266        .inputs
267        .files
268        .iter()
269        .map(|f| {
270            Ok(Watch {
271                mapping: f.mapping.clone(),
272                source: f
273                    .source
274                    .clone()
275                    .ok_or_else(|| Error::Invalid("missing lifecycle source snapshot".into()))?,
276                destination: f.destination.clone().ok_or_else(|| {
277                    Error::Invalid("missing lifecycle destination snapshot".into())
278                })?,
279            })
280        })
281        .collect::<Result<Vec<_>>>()?;
282    let mut entries = vec![&fresh.inputs.manifest, &fresh.inputs.local_config];
283    for w in &watches {
284        entries.extend([&w.source, &w.destination]);
285    }
286    let mut h = Header {
287        repository_id: repo_id,
288        repository: inputs.repository.clone(),
289        transaction_id: adoption::transaction_id(),
290        approved_plan_sha256: approval.digest,
291        action,
292        removal_acknowledged: action == Action::Remove,
293        environment_file: environment_id.map(str::to_owned),
294        profiles,
295        anchors: anchors(&entries),
296        watches,
297        manifest: fresh.inputs.manifest.clone(),
298        local_config: fresh.inputs.local_config.clone(),
299        backups: vec![],
300    };
301    if h.manifest
302        .fingerprint
303        .as_ref()
304        .is_none_or(|f| f.mode & 0o7000 != 0)
305    {
306        return Err(Error::Invalid(
307            "manifest special permission bits refused".into(),
308        ));
309    }
310    h.backups = wire::backup_specs(&h)?;
311    let expected = wire::expected(&h)?;
312    // Read bytes and construct/revalidate the focused edit before allocating a transaction.
313    let manifest_bytes = checked_bytes(&h.manifest)?;
314    let new_manifest = if action != Action::Apply {
315        Some(remove_mapping(
316            &manifest_bytes,
317            &h.watches[0].mapping.id,
318            host,
319            &h.repository,
320            &h.profiles,
321        )?)
322    } else {
323        None
324    };
325    let mut backup_bytes = vec![];
326    for b in &h.backups {
327        let e = if b.path == h.manifest.path {
328            &h.manifest
329        } else {
330            &h.watches
331                .iter()
332                .find(|w| w.destination.path == b.path)
333                .ok_or_else(|| Error::Invalid("missing backup destination".into()))?
334                .destination
335        };
336        let bytes = if e.kind == Kind::Symlink {
337            e.link_target
338                .as_ref()
339                .ok_or_else(|| Error::Invalid("missing backup link target".into()))?
340                .to_str()
341                .ok_or_else(|| Error::Invalid("backup link target must be UTF-8".into()))?
342                .as_bytes()
343                .to_vec()
344        } else {
345            checked_bytes(e)?
346        };
347        if journal::digest(&bytes) != b.sha256 {
348            return Err(Error::Invalid("backup input changed".into()));
349        }
350        backup_bytes.push(bytes);
351    }
352    let keep_bytes = if action == Action::Keep {
353        Some(checked_bytes(&h.watches[0].source)?)
354    } else {
355        None
356    };
357    let mut j = Journal::begin(host, h)?;
358    notify(&j, Boundary::Checkpoint, &mut observer)?;
359    for (backup, bytes) in j.record.header.backups.iter().zip(&backup_bytes) {
360        j.directory.create(&backup.name, bytes)?;
361    }
362    j.verify_backups()?;
363    let device = Fingerprint::from_stat(
364        &fs::fstat(&j.directory.file)
365            .map_err(|e| io_error("inspect transaction filesystem", &j.directory.path, e))?,
366    )
367    .device;
368    // Even watched sources stay on this device: consistent with the reviewed constraint.
369    for entry in std::iter::once(&j.record.header.manifest).chain(
370        j.record
371            .header
372            .watches
373            .iter()
374            .flat_map(|w| [&w.source, &w.destination]),
375    ) {
376        if entry.parents.last().is_none_or(|p| {
377            p.fingerprint.device != device || p.fingerprint.uid != fresh.inputs.user_id
378        }) || entry
379            .fingerprint
380            .as_ref()
381            .is_some_and(|f| f.device != device)
382        {
383            return Err(Error::Invalid(
384                "lifecycle requires owned parents and one filesystem; no cross-device fallback"
385                    .into(),
386            ));
387        }
388    }
389    for (id, (role, mutation, path)) in expected.into_iter().enumerate() {
390        let before = match role {
391            Role::Directory => inspect(&path, role)?,
392            Role::Manifest => j.record.header.manifest.clone(),
393            Role::Destination => j
394                .record
395                .header
396                .watches
397                .iter()
398                .find(|w| w.destination.path == path)
399                .ok_or_else(|| Error::Invalid("missing watched destination".into()))?
400                .destination
401                .clone(),
402        };
403        match role {
404            Role::Directory => {
405                fs::mkdirat(
406                    &j.directory.file,
407                    stage_name(id).as_str(),
408                    Mode::from_raw_mode(0o700),
409                )
410                .map_err(|e| io_error("prepare destination parent", &path, e))?;
411                let dir = File::from(
412                    fs::openat(
413                        &j.directory.file,
414                        stage_name(id).as_str(),
415                        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
416                        Mode::empty(),
417                    )
418                    .map_err(|e| io_error("open prepared parent", &path, e))?,
419                );
420                dir.sync_all()
421                    .map_err(|e| io_error("sync prepared parent", &path, e))?;
422            }
423            Role::Manifest => stage_file(
424                &j,
425                id,
426                new_manifest
427                    .as_ref()
428                    .ok_or_else(|| Error::Invalid("missing edited manifest".into()))?,
429                before
430                    .fingerprint
431                    .as_ref()
432                    .ok_or_else(|| Error::Invalid("missing manifest fingerprint".into()))?,
433            )?,
434            Role::Destination => match action {
435                Action::Apply => {
436                    let w = j
437                        .record
438                        .header
439                        .watches
440                        .iter()
441                        .find(|w| w.destination.path == path)
442                        .ok_or_else(|| Error::Invalid("missing watched destination".into()))?;
443                    fs::symlinkat(&w.source.path, &j.directory.file, stage_name(id).as_str())
444                        .map_err(|e| io_error("prepare managed link", &path, e))?;
445                }
446                Action::Keep => stage_file(
447                    &j,
448                    id,
449                    keep_bytes
450                        .as_ref()
451                        .ok_or_else(|| Error::Invalid("missing kept mapping bytes".into()))?,
452                    j.record.header.watches[0]
453                        .source
454                        .fingerprint
455                        .as_ref()
456                        .ok_or_else(|| Error::Invalid("missing source fingerprint".into()))?,
457                )?,
458                Action::Remove => {}
459            },
460        }
461        j.directory.sync()?;
462        let staged = inspect(&stage_path(&j, id), role)?;
463        j.record.operations.push(Operation {
464            id,
465            role,
466            mutation,
467            before,
468            staged,
469            after: None,
470            progress: Progress::Pending,
471        });
472    }
473    j.record.phase = Phase::Running;
474    checkpoint(&mut j, &mut observer)?;
475    validate_scope(host, &j)?;
476    for id in 0..j.record.operations.len() {
477        validate_layout(host, &j)?;
478        j.record.operations[id].progress = Progress::Intent;
479        checkpoint(&mut j, &mut observer)?;
480        validate_layout(host, &j)?;
481        mutate(&j, id, false)?;
482        notify(&j, Boundary::Mutation, &mut observer)?;
483        let op = &j.record.operations[id];
484        let after = inspect(&op.before.path, op.role)?;
485        let ok = if op.mutation == Mutation::Withdraw {
486            after.kind == Kind::Missing
487        } else {
488            same(&op.staged, &after, false)
489        };
490        if !ok {
491            return Err(Error::Invalid("lifecycle postcondition mismatch".into()));
492        }
493        j.record.operations[id].after = Some(after);
494        j.record.operations[id].progress = Progress::Done;
495        checkpoint(&mut j, &mut observer)?;
496    }
497    j.record.phase = Phase::Verifying;
498    checkpoint(&mut j, &mut observer)?;
499    validate_layout(host, &j)?;
500    j.record.phase = Phase::Completed;
501    checkpoint(&mut j, &mut observer)?;
502    Ok(Some(j.record.header.transaction_id))
503}
504
505fn check_parents(j: &Journal, entry: &Entry) -> Result<()> {
506    for p in &entry.parents {
507        let expected = j
508            .record
509            .header
510            .anchors
511            .iter()
512            .find(|e| e.path == p.path)
513            .map(|e| &e.fingerprint)
514            .or_else(|| {
515                j.record
516                    .operations
517                    .iter()
518                    .find(|o| o.role == Role::Directory && o.before.path == p.path)
519                    .and_then(|o| o.staged.fingerprint.as_ref())
520            });
521        if expected.is_none_or(|e| !parent_identity(e, &p.fingerprint)) {
522            return Err(Error::Invalid(
523                "parent identity/permissions changed; lifecycle refused".into(),
524            ));
525        }
526    }
527    Ok(())
528}
529fn applied(j: &Journal, op: &Operation) -> Result<bool> {
530    let live = inspect(&op.before.path, op.role)?;
531    check_parents(j, &live)?;
532    let stage = inspect(&stage_path(j, op.id), op.role)?;
533    let strict = op.progress == Progress::Pending;
534    let before = same(&op.before, &live, strict) && same(&op.staged, &stage, strict);
535    let after = match op.mutation {
536        Mutation::Publish => same(&op.staged, &live, false) && stage.kind == Kind::Missing,
537        Mutation::Exchange => same(&op.staged, &live, false) && same(&op.before, &stage, false),
538        Mutation::Withdraw => live.kind == Kind::Missing && same(&op.before, &stage, false),
539    };
540    match op.progress {
541        Progress::Pending if before => Ok(false),
542        Progress::Intent | Progress::UndoIntent if before => Ok(false),
543        Progress::Intent | Progress::UndoIntent if after => Ok(true),
544        Progress::Done if after && op.after.as_ref().is_some_and(|e| same(e, &live, true)) => {
545            Ok(true)
546        }
547        Progress::Undone if before => Ok(false),
548        _ => Err(Error::Invalid(
549            "lifecycle guard mismatch (file, stage or parent edited); recovery refused".into(),
550        )),
551    }
552}
553fn validate_layout(host: &HostContext, j: &Journal) -> Result<()> {
554    let h = &j.record.header;
555    journal::registered_root(host, &h.repository_id, &h.repository)?;
556    j.verify_backups()?;
557    let config = observation::inspect(&host.local_config_path(), false)?;
558    if !same(&h.local_config, &config, true) {
559        return Err(Error::Invalid(
560            "local configuration changed since approval".into(),
561        ));
562    }
563    check_parents(j, &config)?;
564    for w in &h.watches {
565        let source = observation::inspect(&w.source.path, true)?;
566        if !same(&w.source, &source, true) {
567            return Err(Error::Invalid(
568                "repository source edited; lifecycle/recovery refused".into(),
569            ));
570        }
571        check_parents(j, &source)?;
572        if !wire::changed(h, w) {
573            let current = observation::inspect(&w.destination.path, true)?;
574            if !same(&w.destination, &current, true) {
575                return Err(Error::Invalid("unchanged mapping drifted".into()));
576            }
577            check_parents(j, &current)?;
578        }
579    }
580    if h.action == Action::Apply {
581        let manifest = observation::read_manifest(&h.manifest.path)?.1;
582        if !same(&h.manifest, &manifest, true) {
583            return Err(Error::Invalid("manifest edited since approval".into()));
584        }
585        check_parents(j, &manifest)?;
586    }
587    let states: Vec<_> = j
588        .record
589        .operations
590        .iter()
591        .map(|o| applied(j, o))
592        .collect::<Result<_>>()?;
593    for op in j
594        .record
595        .operations
596        .iter()
597        .filter(|o| o.role == Role::Directory)
598    {
599        let path = if states[op.id] {
600            op.before.path.clone()
601        } else {
602            stage_path(j, op.id)
603        };
604        let mut expected: Vec<_> = j
605            .record
606            .operations
607            .iter()
608            .filter(|child| {
609                states[op.id]
610                    && states[child.id]
611                    && child.before.path.parent() == Some(op.before.path.as_path())
612            })
613            .map(|o| {
614                o.before
615                    .path
616                    .file_name()
617                    .map(|name| name.to_owned())
618                    .ok_or_else(|| Error::Invalid("missing managed file name".into()))
619            })
620            .collect::<Result<Vec<_>>>()?;
621        expected.sort();
622        if observation::names(&path, 4096)? != expected {
623            return Err(Error::Invalid(
624                "created/prepared destination directory contains unapproved entries".into(),
625            ));
626        }
627    }
628    Ok(())
629}
630fn mutate(j: &Journal, id: usize, undo: bool) -> Result<()> {
631    let op = &j.record.operations[id];
632    let live = observation::parent_handle(&op.before.path)?;
633    if live.missing {
634        return Err(Error::Invalid("operation parent is missing".into()));
635    }
636    let current = inspect(&op.before.path, op.role)?;
637    check_parents(j, &current)?;
638    if live.parents.len() != current.parents.len()
639        || live
640            .parents
641            .iter()
642            .zip(&current.parents)
643            .any(|(a, b)| a.path != b.path || !parent_identity(&a.fingerprint, &b.fingerprint))
644    {
645        return Err(Error::Invalid(
646            "parent substituted during lifecycle mutation".into(),
647        ));
648    }
649    if applied(j, op)? != undo {
650        return Err(Error::Invalid("lifecycle precondition changed".into()));
651    }
652    if undo && op.role == Role::Directory && !observation::names(&op.before.path, 1)?.is_empty() {
653        return Err(Error::Invalid(
654            "created destination parent is not empty".into(),
655        ));
656    }
657    let into_private = match op.mutation {
658        Mutation::Publish => undo,
659        Mutation::Exchange => false,
660        Mutation::Withdraw => !undo,
661    };
662    let flags = if op.mutation == Mutation::Exchange {
663        RenameFlags::EXCHANGE
664    } else {
665        RenameFlags::NOREPLACE
666    };
667    let result = if into_private {
668        fs::renameat_with(
669            &live.directory,
670            &live.name,
671            &j.directory.file,
672            stage_name(id).as_str(),
673            flags,
674        )
675    } else {
676        fs::renameat_with(
677            &j.directory.file,
678            stage_name(id).as_str(),
679            &live.directory,
680            &live.name,
681            flags,
682        )
683    };
684    result.map_err(|e| {
685        io_error(
686            "publish/invert lifecycle rename (no unsafe fallback)",
687            &op.before.path,
688            e,
689        )
690    })?;
691    live.directory
692        .sync_all()
693        .map_err(|e| io_error("sync lifecycle parent", &op.before.path, e))?;
694    j.directory.sync()
695}
696
697// Independently bind journal paths to a validated original manifest and host protections.
698fn validate_scope(host: &HostContext, j: &Journal) -> Result<()> {
699    let h = &j.record.header;
700    journal::registered_root(host, &h.repository_id, &h.repository)?;
701    observation::validate_output_path(&h.repository)?;
702    if h.manifest.path != h.repository.join("dort.toml")
703        || h.local_config.path != host.local_config_path()
704    {
705        return Err(Error::Invalid("lifecycle journal scope mismatch".into()));
706    }
707    // Preparing can only create private artifacts, including incomplete backups.
708    if j.record.operations.is_empty() {
709        return Ok(());
710    }
711    j.verify_backups()?;
712    let bytes = if h.action == Action::Apply {
713        checked_bytes(&h.manifest)?
714    } else {
715        let b = h
716            .backups
717            .iter()
718            .find(|b| b.path == h.manifest.path)
719            .ok_or_else(|| Error::Invalid("missing manifest backup".into()))?;
720        journal::read_bytes(&j.directory, &b.name)?
721    };
722    let manifest = Manifest::parse(
723        std::str::from_utf8(&bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?,
724    )?;
725    let active = h.profiles.iter().cloned().collect();
726    if h.environment_file.is_some() {
727        if h.action != Action::Apply {
728            return Err(Error::Invalid("invalid environment file record".into()));
729        }
730        manifest.validate_file_targets(host, &active, Some(&h.repository), None)?;
731    } else {
732        manifest.validate_selection(host, &active, Some(&h.repository))?;
733    }
734    let mut mappings: Vec<_> = manifest
735        .files
736        .iter()
737        .filter(|m| {
738            if h.action == Action::Apply {
739                selected(&m.profiles, &active)
740                    && h.environment_file.as_ref().is_none_or(|id| *id == m.id)
741            } else {
742                m.id == h.watches[0].mapping.id
743            }
744        })
745        .cloned()
746        .collect();
747    mappings.sort_by(|a, b| a.id.cmp(&b.id));
748    if journal::encode(&mappings)?
749        != journal::encode(&h.watches.iter().map(|w| &w.mapping).collect::<Vec<_>>())?
750    {
751        return Err(Error::Invalid(
752            "journal watches do not match original manifest".into(),
753        ));
754    }
755    for w in &h.watches {
756        let source = h.repository.join(
757            w.mapping
758                .overrides
759                .get(&host.platform)
760                .unwrap_or(&w.mapping.source),
761        );
762        if w.source.path != source
763            || w.destination.path != host.target_path(&w.mapping.target, Some(&h.repository))?
764        {
765            return Err(Error::Invalid("journal mapping scope mismatch".into()));
766        }
767    }
768    let snapshot = planner::Snapshot {
769        user_id: rustix::process::geteuid().as_raw(),
770        host: host.clone(),
771        repository: h.repository.clone(),
772        manifest: h.manifest.clone(),
773        local_config: h.local_config.clone(),
774        active_profiles: active,
775        temporary_profiles: vec![],
776        profiles: vec![],
777        inactive_links: vec![],
778        request: match h.action {
779            Action::Apply => Request::Apply,
780            Action::Keep | Action::Remove => Request::Unmanage {
781                id: h.watches[0].mapping.id.clone(),
782                mode: if h.action == Action::Keep {
783                    UnmanageMode::Keep
784                } else {
785                    UnmanageMode::Remove
786                },
787            },
788        },
789        files: h
790            .watches
791            .iter()
792            .map(|w| planner::FileSnapshot {
793                mapping: w.mapping.clone(),
794                source_path: w.source.path.clone(),
795                target_path: w.destination.path.clone(),
796                source: Some(w.source.clone()),
797                destination: Some(w.destination.clone()),
798                blockers: vec![],
799            })
800            .collect(),
801    };
802    let plan = if h.environment_file.is_some() {
803        planner::plan_environment(snapshot)
804    } else {
805        planner::plan(snapshot)
806    };
807    if plan.has_blockers() {
808        return Err(Error::Invalid("unsafe lifecycle journal inputs".into()));
809    }
810    let expected = wire::expected(h)?;
811    if j.record.operations.len() != expected.len() {
812        return Err(Error::Invalid("lifecycle operation scope mismatch".into()));
813    }
814    for (op, (role, mutation, path)) in j.record.operations.iter().zip(expected) {
815        if op.role != role
816            || op.mutation != mutation
817            || op.before.path != path
818            || op.staged.path != stage_path(j, op.id)
819        {
820            return Err(Error::Invalid(
821                "lifecycle operation path/order mismatch".into(),
822            ));
823        }
824    }
825    Ok(())
826}
827
828/// Read-only preflight and conservative inverse paths for the head-bound recovery service.
829pub(crate) fn rollback_preview(
830    host: &HostContext,
831    repository_id: &str,
832    transaction_id: &str,
833) -> Result<(String, Vec<PathBuf>)> {
834    let j = Journal::open(host, repository_id, transaction_id)?;
835    validate_scope(host, &j)?;
836    if !matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
837        validate_layout(host, &j)?;
838    }
839    let effects = if matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
840        vec![]
841    } else {
842        j.record
843            .operations
844            .iter()
845            .rev()
846            .filter(|o| o.progress != Progress::Undone)
847            .map(|o| o.before.path.clone())
848            .collect()
849    };
850    Ok((
851        journal::digest(journal::encode(&j.record)?.as_bytes()),
852        effects,
853    ))
854}
855
856/// Explicit/restartable guarded rollback, including completed schema-2 transactions.
857/// Schema-1 adoption transactions remain recoverable using adoption::rollback.
858pub fn rollback(
859    host: &HostContext,
860    lock: &WriterLock,
861    repository_id: &str,
862    transaction_id: &str,
863    mut observer: impl FnMut(&Event) -> Result<()>,
864) -> Result<()> {
865    lock.check_context(host)?;
866    let mut j = Journal::open(host, repository_id, transaction_id)?;
867    validate_scope(host, &j)?;
868    if j.record.phase == Phase::RolledBack {
869        return Ok(());
870    }
871    if j.record.phase == Phase::Preparing {
872        j.record.phase = Phase::RolledBack;
873        return checkpoint(&mut j, &mut observer);
874    }
875    validate_layout(host, &j)?;
876    if j.record.phase != Phase::RollingBack {
877        j.record.phase = Phase::RollingBack;
878        checkpoint(&mut j, &mut observer)?;
879    }
880    for id in (0..j.record.operations.len()).rev() {
881        if j.record.operations[id].progress == Progress::Undone {
882            continue;
883        }
884        validate_layout(host, &j)?;
885        let was_applied = applied(&j, &j.record.operations[id])?;
886        j.record.operations[id].progress = Progress::UndoIntent;
887        checkpoint(&mut j, &mut observer)?;
888        validate_layout(host, &j)?;
889        if was_applied {
890            mutate(&j, id, true)?;
891            notify(&j, Boundary::Mutation, &mut observer)?;
892        }
893        j.record.operations[id].progress = Progress::Undone;
894        checkpoint(&mut j, &mut observer)?;
895    }
896    validate_layout(host, &j)?;
897    j.record.phase = Phase::RolledBack;
898    checkpoint(&mut j, &mut observer)
899}
900
901/// Content-free retained history/diagnosis across schema-1 and schema-2 transactions.
902/// This reads private metadata/backups only, never live source content; it creates nothing.
903pub fn history(host: &HostContext) -> Result<Vec<journal::Diagnosis>> {
904    journal::diagnose(host)
905}