Skip to main content

dort_core/
environment.rs

1//! Ordered environment reviews, execution, and local run records.
2use crate::{
3    Error, Manifest, Result, adoption,
4    context::HostContext,
5    journal,
6    local::LocalConfig,
7    model::Provider,
8    observation::{self, Entry, Kind},
9    planner, profiles,
10    state::{PrivateDir, WriterLock},
11    tools::{VersionMatch, VersionPolicy, binaries, inspection, install, planning},
12};
13mod run;
14pub use run::{AbandonApproval, AbandonPreview, Approval, Run};
15use serde::{Deserialize, Serialize};
16use std::{
17    collections::{BTreeMap, BTreeSet},
18    path::{Path, PathBuf},
19    time::{SystemTime, UNIX_EPOCH},
20};
21
22const CHECK_MAX_AGE: u64 = 600;
23const MAX_STEPS: usize = 128;
24
25fn invalid(reason: impl Into<String>) -> Error {
26    Error::Invalid(reason.into())
27}
28fn digest(data: &impl Serialize) -> Result<String> {
29    Ok(journal::digest(adoption::canonical(data)?.as_bytes()))
30}
31fn now() -> u64 {
32    SystemTime::now()
33        .duration_since(UNIX_EPOCH)
34        .unwrap_or_default()
35        .as_secs()
36}
37
38#[derive(Clone, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40struct Catalog {
41    scope: install::npm::Catalog,
42    programs: Vec<Entry>,
43    observation: inspection::Observation,
44}
45
46#[derive(Clone, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48struct Check {
49    input: String,
50    generation: String,
51    when: u64,
52    dirs: Vec<PathBuf>,
53    catalogs: Vec<Catalog>,
54}
55
56struct Inputs {
57    manifest: Manifest,
58    files: planner::Snapshot,
59    stamp: String,
60    repository_id: String,
61}
62impl Inputs {
63    fn read(host: &HostContext, root: &Path, temporary: &[String]) -> Result<Self> {
64        let (config, local) = LocalConfig::load_bound(host)?;
65        let repository_id = config
66            .repositories
67            .iter()
68            .find(|(_, record)| record.root == root)
69            .map(|(id, _)| id.clone())
70            .ok_or_else(|| invalid("Choose a registered repository."))?;
71        let files = planner::observe_environment(host, root, temporary)?;
72        let (manifest, entry) = observation::read_manifest(&root.join("dort.toml"))?;
73        if !same(&entry, &files.manifest)
74            || !adoption::same(&local, &LocalConfig::load_bound(host)?.1, true)
75        {
76            return Err(invalid(
77                "Manifest or profile choices changed. Review again.",
78            ));
79        }
80        let stamp = digest(&(
81            host,
82            &repository_id,
83            entry.stable_parents(),
84            local.stable_parents(),
85            &files.profiles,
86            temporary,
87        ))?;
88        Ok(Self {
89            manifest,
90            files,
91            stamp,
92            repository_id,
93        })
94    }
95}
96fn same(a: &Entry, b: &Entry) -> bool {
97    a.path == b.path
98        && adoption::same(a, b, true)
99        && a.parents.len() == b.parents.len()
100        && a.parents.iter().zip(&b.parents).all(|(a, b)| {
101            a.path == b.path && adoption::parent_identity(&a.fingerprint, &b.fingerprint)
102        })
103}
104fn directory(host: &HostContext, id: &str, create: bool) -> Result<Option<PrivateDir>> {
105    let path = crate::local::repository_state_path(host, id)?.join("environment");
106    PrivateDir::open(&path, create)
107}
108fn read<T: for<'a> Deserialize<'a>>(dir: &PrivateDir, name: &str) -> Result<Option<T>> {
109    if observation::inspect(&dir.path.join(name), false)?.kind == Kind::Missing {
110        return Ok(None);
111    }
112    let bytes = journal::read_bytes(dir, name)?;
113    serde_json::from_slice(&bytes)
114        .map(Some)
115        .map_err(|_| invalid("Cannot read the saved environment record."))
116}
117fn save(dir: &PrivateDir, name: &str, value: &impl Serialize) -> Result<()> {
118    let text = journal::encode(value)?;
119    if text.len() > 4 * 1024 * 1024 {
120        return Err(invalid(
121            "Environment record is too large. Choose fewer profiles.",
122        ));
123    }
124    dir.replace(name, &text)
125}
126fn programs(scope: &install::npm::Catalog) -> Result<Vec<Entry>> {
127    std::iter::once(&scope.executable)
128        .chain(scope.npm_binding.as_ref().map(|n| &n.npm_cli))
129        .map(|p| observation::inspect(p, false).map(Entry::stable_parents))
130        .collect()
131}
132impl Catalog {
133    fn current(&self) -> bool {
134        programs(&self.scope).is_ok_and(|now| {
135            now.len() == self.programs.len()
136                && now.iter().zip(&self.programs).all(|(a, b)| same(a, b))
137        })
138    }
139    fn report(&self, home: &Path) -> Result<inspection::Report> {
140        Ok(inspection::Report {
141            description: self.scope.preview(home)?.description().clone(),
142            observation: self.observation.clone(),
143        })
144    }
145}
146
147/// Supplies only observed package metadata, not an executable approval.
148pub fn save_check(
149    host: &HostContext,
150    root: &Path,
151    temporary: &[String],
152    dirs: Vec<PathBuf>,
153    reports: impl IntoIterator<Item = (BTreeSet<String>, inspection::Report)>,
154    still_current: impl FnOnce() -> Result<()>,
155) -> Result<()> {
156    let lock = WriterLock::acquire(host)?;
157    lock.check_context(host)?;
158    still_current()?;
159    let input = Inputs::read(host, root, temporary)?;
160    binaries::validate(&input.manifest, &input.files.active_profiles, &dirs)?;
161    let mut catalogs = vec![];
162    for (tools, report) in reports {
163        let d = report.description;
164        if d.home != host.home || tools.is_empty() || catalogs.len() >= 16 {
165            return Err(invalid("Invalid environment check scope."));
166        }
167        let scope = install::npm::Catalog {
168            query: d.query,
169            executable: d.executable,
170            search_dirs: d.trusted_search_path,
171            npm_binding: d.npm_binding,
172            tools,
173        };
174        scope.preview(&host.home)?;
175        catalogs.push(Catalog {
176            programs: programs(&scope)?,
177            scope,
178            observation: report.observation,
179        });
180    }
181    let dir = directory(host, &input.repository_id, true)?.expect("created environment directory");
182    save(
183        &dir,
184        "check.json",
185        &Check {
186            input: input.stamp,
187            generation: adoption::transaction_id(),
188            when: now(),
189            dirs,
190            catalogs,
191        },
192    )
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
197pub enum Item {
198    Tool(String),
199    File(String),
200}
201impl Item {
202    fn id(&self) -> &str {
203        match self {
204            Self::Tool(id) | Self::File(id) => id,
205        }
206    }
207}
208
209#[derive(Serialize)]
210#[serde(tag = "kind", rename_all = "snake_case")]
211enum Detail {
212    Tool {
213        provider: Provider,
214        package: String,
215        destination: Option<PathBuf>,
216        version: Option<String>,
217        command: Option<Vec<String>>,
218    },
219    File {
220        source: PathBuf,
221        destination: PathBuf,
222        effects: Vec<planner::Effect>,
223    },
224}
225#[derive(Serialize)]
226struct Row {
227    item: Item,
228    requires: Vec<String>,
229    detail: Detail,
230    status: &'static str,
231    blockers: Vec<String>,
232}
233struct PreparedRow {
234    row: Row,
235    install: Option<install::Preview>,
236    proof: Option<String>,
237    file: Option<planner::FileSnapshot>,
238}
239struct Plan {
240    rows: Vec<PreparedRow>,
241    check: Option<Check>,
242    input: Inputs,
243}
244impl Plan {
245    fn prepare(host: &HostContext, root: &Path, temporary: &[String]) -> Result<Self> {
246        let input = Inputs::read(host, root, temporary)?;
247        let check = directory(host, &input.repository_id, false)?
248            .map(|dir| read::<Check>(&dir, "check.json"))
249            .transpose()?
250            .flatten()
251            .filter(|check| {
252                check.input == input.stamp
253                    && now()
254                        .checked_sub(check.when)
255                        .is_some_and(|age| age <= CHECK_MAX_AGE)
256            });
257        Self::from_check(host, input, check)
258    }
259
260    fn from_check(host: &HostContext, input: Inputs, check: Option<Check>) -> Result<Self> {
261        let active = &input.files.active_profiles;
262        let mut reports = vec![];
263        let mut catalogs = BTreeMap::new();
264        let mut observed = planning::Observations::default();
265        if let Some(check) = &check {
266            for catalog in check.catalogs.iter().filter(|c| c.current()) {
267                let report = catalog.report(&host.home)?;
268                catalogs.extend(
269                    catalog
270                        .scope
271                        .tools
272                        .iter()
273                        .cloned()
274                        .map(|id| (id, reports.len())),
275                );
276                reports.push((catalog, report));
277            }
278            observed.catalogs = catalogs
279                .iter()
280                .map(|(id, idx)| (id.clone(), &reports[*idx].1))
281                .collect();
282            observed.binaries = binaries::observe(&input.manifest, active, &check.dirs)?
283                .tools
284                .into_iter()
285                .map(|(id, tool)| (id, tool.observation))
286                .collect();
287        }
288        let mut rows: Vec<PreparedRow> = vec![];
289        let tool_plan = planning::plan(&input.manifest, host.platform, active, &observed)?;
290        for tool in &tool_plan.rows {
291            let declaration = tool.declaration.as_ref().expect("declared tool");
292            let scope = catalogs.get(&tool.id).map(|idx| &reports[*idx].0.scope);
293            let destination = scope.and_then(|scope| match &scope.npm_binding {
294                Some(npm) => Some(npm.prefix.clone()),
295                None => install::brew::prefix_hint(&scope.executable),
296            });
297            let mut row = Row {
298                item: Item::Tool(tool.id.clone()),
299                requires: tool.dependencies.clone(),
300                detail: Detail::Tool {
301                    provider: declaration.provider,
302                    package: declaration.package.clone(),
303                    destination,
304                    version: None,
305                    command: None,
306                },
307                status: "Blocked",
308                blockers: vec![],
309            };
310            for dependency in &tool.dependencies {
311                let advice = dependency_block(&rows, &input.manifest, dependency);
312                row.blockers.extend(advice);
313            }
314            let mut installation = None;
315            let mut proof = None;
316            if row.blockers.is_empty() {
317                match &tool.package {
318                    planning::PackageFinding::NotObserved | planning::PackageFinding::Unavailable { .. } => {
319                        row.status = "Unknown";
320                        row.blockers.push("Run Environment check again.".into());
321                    }
322                    planning::PackageFinding::Present { versions } => {
323                        let matching: Vec<_> = versions.iter().filter(|v| v.policy_match == VersionMatch::Satisfied).map(|v| v.version.as_str()).collect();
324                        if matching.is_empty() { row.blockers.push("Installed version differs or cannot be verified. Use the package manager outside Dort to select the declared version, or correct the declaration, then run Environment check.".into()); }
325                        else if let Some(proven) = scope.and_then(|scope| proof_of_tool(tool, scope, &matching).ok().flatten()) {
326                            row.status = "Already correct";
327                            if let Detail::Tool { version, .. } = &mut row.detail { *version = Some(matching.join(", ")); }
328                            proof = Some(proven);
329                        } else { row.blockers.push("The command does not resolve to the checked package. Fix the command or tool search paths outside this run, then run Environment check.".into()); }
330                    }
331                    planning::PackageFinding::Absent => match prepare_install(host, &input, check.as_ref(), &tool_plan.rows, tool, &reports, &catalogs) {
332                        Ok(p) => {
333                            row.status = "Install";
334                            if let Detail::Tool { command, version, .. } = &mut row.detail {
335                                let review = p.review();
336                                *command = Some(std::iter::once(review.installer.display().to_string()).chain(review.arguments).collect());
337                                *version = Some(review.scope.version.clone());
338                            }
339                            installation = Some(p);
340                        }
341                        Err(error) => row.blockers.push(error.to_string()),
342                    },
343                    _ => row.blockers.push("Package identity is unverified. Check the declaration and run Environment check.".into()),
344                }
345            }
346            rows.push(PreparedRow {
347                row,
348                install: installation,
349                proof,
350                file: None,
351            });
352        }
353        let files = planner::plan_environment(input.files.clone());
354        for (file, proposed) in files.inputs.files.into_iter().zip(files.files) {
355            let mut blockers = proposed.blockers;
356            for dependency in &file.mapping.requires {
357                blockers.extend(dependency_block(&rows, &input.manifest, dependency));
358            }
359            let status = if !blockers.is_empty() {
360                "Blocked"
361            } else if matches!(proposed.outcome, planner::Outcome::NoOp) {
362                "Already correct"
363            } else {
364                "Link"
365            };
366            let proof = if status == "Already correct" {
367                Some(digest(&(
368                    file.source.clone().map(Entry::stable_parents),
369                    file.destination.clone().map(Entry::stable_parents),
370                ))?)
371            } else {
372                None
373            };
374            rows.push(PreparedRow {
375                row: Row {
376                    item: Item::File(file.mapping.id.clone()),
377                    requires: file.mapping.requires.clone(),
378                    detail: Detail::File {
379                        source: file.source_path.clone(),
380                        destination: file.target_path.clone(),
381                        effects: proposed.effects,
382                    },
383                    status,
384                    blockers,
385                },
386                install: None,
387                proof,
388                file: Some(file),
389            });
390        }
391        if rows.len() > MAX_STEPS {
392            return Err(invalid(
393                "Too many environment steps. Choose fewer profiles.",
394            ));
395        }
396        Ok(Self { rows, check, input })
397    }
398}
399
400fn dependency_block(rows: &[PreparedRow], manifest: &Manifest, tool: &str) -> Option<String> {
401    match rows.iter().find(|r| r.row.item == Item::Tool(tool.into())) {
402        Some(row) if row.row.blockers.is_empty() => None,
403        Some(_) => Some(format!("Required tool {tool} is blocked.")),
404        None => Some(format!(
405            "Required tool {tool} is off. Enable one of: {}.",
406            manifest
407                .tools
408                .iter()
409                .find(|t| t.id == tool)
410                .map(|t| t.profiles.join(", "))
411                .unwrap_or_default()
412        )),
413    }
414}
415
416fn proof_of_tool(
417    tool: &planning::Row,
418    scope: &install::npm::Catalog,
419    versions: &[&str],
420) -> Result<Option<String>> {
421    let planning::BinaryObservation::Candidates { paths } = &tool.binary_observation else {
422        return Ok(None);
423    };
424    let Some(command) = paths.first() else {
425        return Ok(None);
426    };
427    let Some(d) = &tool.declaration else {
428        return Ok(None);
429    };
430    let physical = match command.canonicalize() {
431        Ok(p) => p,
432        Err(_) => return Ok(None),
433    };
434    let attributed = if let Some(npm) = &scope.npm_binding {
435        command == &npm.prefix.join("bin").join(&tool.binary)
436            && physical.starts_with(npm.prefix.join("lib/node_modules").join(&d.package))
437    } else {
438        install::brew::prefix_hint(&scope.executable).is_some_and(|prefix| {
439            versions.iter().any(|v| {
440                physical.starts_with(prefix.join("Cellar").join(&d.package).join(v).join("bin"))
441            })
442        })
443    };
444    if !attributed {
445        return Ok(None);
446    }
447    let entry = observation::inspect(&physical, false)?;
448    if entry.kind != Kind::Regular
449        || entry
450            .fingerprint
451            .as_ref()
452            .is_none_or(|f| f.mode & 0o111 == 0)
453    {
454        return Ok(None);
455    }
456    Ok(Some(digest(&(versions, entry.stable_parents()))?))
457}
458
459fn prepare_install(
460    host: &HostContext,
461    input: &Inputs,
462    check: Option<&Check>,
463    rows: &[planning::Row],
464    tool: &planning::Row,
465    reports: &[(&Catalog, inspection::Report)],
466    bindings: &BTreeMap<String, usize>,
467) -> Result<install::Preview> {
468    let check = check.ok_or_else(|| invalid("Run Environment check first."))?;
469    let mut ids = BTreeSet::new();
470    let mut pending = vec![tool.id.clone()];
471    let mut groups = BTreeMap::<usize, BTreeSet<String>>::new();
472    while let Some(id) = pending.pop() {
473        if !ids.insert(id.clone()) {
474            continue;
475        }
476        let row = rows
477            .iter()
478            .find(|r| r.id == id)
479            .ok_or_else(|| invalid("A required tool is off."))?;
480        pending.extend(row.dependencies.clone());
481        groups
482            .entry(
483                *bindings
484                    .get(&id)
485                    .ok_or_else(|| invalid("Run Environment check for all required tools."))?,
486            )
487            .or_default()
488            .insert(id);
489    }
490    let own = &reports[bindings[&tool.id]].0.scope;
491    let request = install::Request {
492        repository: input.files.repository.clone(),
493        profiles: input.files.temporary_profiles.clone(),
494        tool: tool.id.clone(),
495        executable: own.executable.clone(),
496        search_dirs: own.search_dirs.clone(),
497        tool_search_dirs: check.dirs.clone(),
498        bound_tools: ids,
499    };
500    let catalogs = groups
501        .iter()
502        .map(|(idx, ids)| {
503            let mut scope = reports[*idx].0.scope.clone();
504            scope.tools = ids.clone();
505            scope
506        })
507        .collect::<Vec<_>>();
508    let observations = groups
509        .keys()
510        .map(|idx| &reports[*idx].1)
511        .collect::<Vec<_>>();
512    if let Some(binding) = &own.npm_binding {
513        install::npm::prepare_environment(
514            host,
515            request,
516            install::npm::Scope {
517                binding: binding.clone(),
518                catalogs,
519            },
520            &observations,
521        )
522    } else {
523        let prefix = install::brew::prefix_hint(&own.executable)
524            .ok_or_else(|| invalid("Unknown Homebrew install destination."))?;
525        let repository = own
526            .executable
527            .parent()
528            .and_then(Path::parent)
529            .ok_or_else(|| invalid("Unknown Homebrew install destination."))?
530            .to_owned();
531        let policy: VersionPolicy = tool
532            .declaration
533            .as_ref()
534            .expect("declared tool")
535            .policy
536            .clone();
537        install::brew::prepare_environment(
538            host,
539            request,
540            install::brew::Scope {
541                repository,
542                cellar: prefix.join("Cellar"),
543                prefix,
544                policy,
545                catalogs,
546            },
547            &observations,
548        )
549    }
550}
551
552pub struct Preview {
553    plan: Plan,
554    previous: Option<Run>,
555    resume: bool,
556    blockers: Vec<String>,
557}
558
559#[derive(Serialize)]
560pub struct Review<'a> {
561    repository: &'a Path,
562    profiles: &'a [profiles::Row],
563    rows: Vec<&'a Row>,
564    inactive_links: &'a [planner::InactiveLink],
565    last_run: Option<&'a Run>,
566    resume: bool,
567    blockers: &'a [String],
568    checks: Vec<inspection::Description>,
569    warning: &'static str,
570}
571
572const WARNING: &str = "Package managers may change caches and install dependencies. Dort stops on failure and does not roll back packages.";
573
574impl Preview {
575    pub fn prepare(
576        host: &HostContext,
577        root: &Path,
578        temporary: &[String],
579        resume: bool,
580    ) -> Result<Self> {
581        let plan = Plan::prepare(host, root, temporary)?;
582        let previous = directory(host, &plan.input.repository_id, false)?
583            .map(|dir| read::<Run>(&dir, "run.json"))
584            .transpose()?
585            .flatten();
586        let mut blockers = vec![];
587        if plan.rows.iter().any(|row| row.install.is_some())
588            && install::diagnose(host)?
589                .iter()
590                .any(|attempt| attempt.unresolved)
591        {
592            blockers.push("An earlier install is unresolved. Review its record in Tools History before installing another package.".into());
593        }
594        match (&previous, resume) {
595            (None, true) => {
596                blockers.push("No run to resume. Review a new environment plan.".into())
597            }
598            (Some(run), true) => blockers.extend(run.review_resume(&plan)),
599            (Some(run), false) if !run.complete() && !run.abandoned => {
600                blockers.push("An unfinished run exists. Review Resume or Abandon environment run before starting another run.".into());
601            }
602            _ => (),
603        }
604        if plan
605            .rows
606            .iter()
607            .any(|row| matches!(row.row.item, Item::Tool(_)))
608            && previous
609                .as_ref()
610                .and_then(|run| run.stale_check.as_ref())
611                .is_some_and(|stale| {
612                    plan.check
613                        .as_ref()
614                        .is_none_or(|check| check.generation == *stale)
615                })
616        {
617            blockers.push("Run a fresh Environment check after abandonment before reviewing tools in a new plan.".into());
618        }
619        Ok(Self {
620            plan,
621            previous,
622            resume,
623            blockers,
624        })
625    }
626
627    pub fn scope(&self) -> (&Path, &BTreeSet<String>) {
628        (
629            &self.plan.input.files.repository,
630            &self.plan.input.files.active_profiles,
631        )
632    }
633
634    pub fn is_resume(&self) -> bool {
635        self.resume
636    }
637
638    pub fn has_tools(&self) -> bool {
639        self.plan
640            .rows
641            .iter()
642            .any(|row| matches!(row.row.item, Item::Tool(_)))
643    }
644
645    pub fn blocked(&self) -> bool {
646        !self.blockers.is_empty() || self.plan.rows.iter().any(|r| !r.row.blockers.is_empty())
647    }
648
649    pub fn review(&self) -> Review<'_> {
650        Review {
651            repository: &self.plan.input.files.repository,
652            profiles: &self.plan.input.files.profiles,
653            rows: self.plan.rows.iter().map(|r| &r.row).collect(),
654            inactive_links: &self.plan.input.files.inactive_links,
655            last_run: self.previous.as_ref(),
656            resume: self.resume,
657            blockers: &self.blockers,
658            checks: self
659                .plan
660                .check
661                .iter()
662                .flat_map(|check| &check.catalogs)
663                .filter_map(|catalog| {
664                    catalog
665                        .report(&self.plan.input.files.host.home)
666                        .ok()
667                        .map(|r| r.description)
668                })
669                .collect(),
670            warning: WARNING,
671        }
672    }
673
674    pub fn human(&self) -> String {
675        use std::fmt::Write;
676        let mut text = format!(
677            "{}\nRepository: {:?}\n",
678            if self.resume {
679                "Review environment resume"
680            } else {
681                "Environment plan"
682            },
683            self.plan.input.files.repository
684        );
685        for profile in &self.plan.input.files.profiles {
686            let _ = writeln!(text, "Profile {}", profile.label());
687        }
688        for (i, row) in self.plan.rows.iter().map(|p| &p.row).enumerate() {
689            let _ = writeln!(text, "\n{}. {}: {}", i + 1, row.item.id(), row.status);
690            if !row.requires.is_empty() {
691                let _ = writeln!(text, "   Requires: {}", row.requires.join(", "));
692            }
693            match &row.detail {
694                Detail::Tool {
695                    provider,
696                    package,
697                    destination,
698                    version,
699                    command,
700                } => {
701                    let _ = writeln!(
702                        text,
703                        "   {provider:?} package: {package}\n   Destination: {}",
704                        destination
705                            .as_ref()
706                            .map_or("Unknown".into(), |p| format!("{p:?}"))
707                    );
708                    if let Some(version) = version {
709                        let _ = writeln!(text, "   Version: {version}");
710                    }
711                    if let Some(args) = command {
712                        let _ = writeln!(text, "   Run: {args:?}");
713                    }
714                }
715                Detail::File {
716                    source,
717                    destination,
718                    effects,
719                } => {
720                    let _ = writeln!(text, "   Source: {source:?}\n   Target: {destination:?}");
721                    for effect in effects {
722                        let _ = writeln!(text, "   {effect:?}");
723                    }
724                }
725            }
726            for blocker in &row.blockers {
727                let _ = writeln!(text, "   Blocked: {blocker}");
728            }
729        }
730        for link in &self.plan.input.files.inactive_links {
731            let _ = writeln!(
732                text,
733                "\n{}: No longer selected. Keep {:?} in place.",
734                link.id, link.target
735            );
736        }
737        for blocker in &self.blockers {
738            let _ = writeln!(text, "\nBlocked: {blocker}");
739        }
740        if let Some(run) = &self.previous {
741            let _ = writeln!(text, "\n{}", run.human());
742        }
743        if !self.review().checks.is_empty() {
744            let _ = writeln!(text, "\nFresh checks before continuing:");
745            for check in self.review().checks {
746                let _ = writeln!(text, "   {:?} {:?}", check.executable, check.arguments);
747            }
748            let _ = writeln!(text, "\n{WARNING}");
749        }
750        text
751    }
752
753    pub fn approve(self) -> Result<Approval> {
754        if self.blocked() {
755            return Err(invalid("Fix the blocked rows and review again."));
756        }
757        Ok(Approval::new(self))
758    }
759
760    fn binding(&self) -> Result<String> {
761        digest(&(
762            &self.plan.input.stamp,
763            &self.previous,
764            &self.plan.check,
765            self.plan
766                .rows
767                .iter()
768                .map(PreparedRow::step)
769                .collect::<Result<Vec<_>>>()?,
770        ))
771    }
772}