Skip to main content

dort_core/tools/
install.rs

1//! Homebrew and npm installs with reviewed previews.
2use super::{VersionMatch, VersionPolicy, binaries, inspection, planning};
3use crate::{
4    Error, Manifest, Result, adoption,
5    context::HostContext,
6    journal,
7    local::LocalConfig,
8    model::Provider,
9    observation::{self, Entry, Kind},
10    state::WriterLock,
11};
12use serde::{Deserialize, Serialize};
13use std::{collections::BTreeSet, path::PathBuf};
14
15mod attempts;
16pub mod brew;
17mod closure;
18pub mod npm;
19mod outcomes;
20mod process;
21pub use attempts::{Attempt, Problem, diagnose};
22pub use closure::{CloseApproval, ClosePreview, CloseRequest, CloseReview, close, prepare_close};
23pub use outcomes::{NextStep, Status, Summary};
24
25pub const TIMEOUT_SECONDS: u64 = 600;
26/// Bound on the metadata a plan records for one install.
27///
28/// Every program and directory entry carries its own chain of ancestor
29/// fingerprints, so one npm tool with a backed-up runtime measures about 49 KB
30/// from a nine-deep temporary HOME. Keep the bound well above that.
31const METADATA_LIMIT: usize = 256 * 1024;
32
33#[derive(Clone)]
34pub struct Request {
35    pub repository: PathBuf,
36    pub profiles: Vec<String>,
37    pub tool: String,
38    pub executable: PathBuf,
39    pub search_dirs: Vec<PathBuf>,
40    pub tool_search_dirs: Vec<PathBuf>,
41    /// Explicit selected tools with independent catalog groups, never merged.
42    pub bound_tools: BTreeSet<String>,
43}
44#[derive(Clone, Serialize, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct Scope {
47    pub platform: crate::platform::Platform,
48    pub architecture: crate::platform::Architecture,
49    pub repository: PathBuf,
50    pub repository_id: String,
51    pub profiles: BTreeSet<String>,
52    pub tool: String,
53    pub binary: String,
54    pub package: String,
55    pub version: String,
56    pub executable: PathBuf,
57    pub home: PathBuf,
58    pub search_dirs: Vec<PathBuf>,
59    pub tool_search_dirs: Vec<PathBuf>,
60    pub bound_tools: BTreeSet<String>,
61    /// Present only for npm; other provider records omit it.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub npm: Option<npm::Scope>,
64    /// Schema 3 only. Provider-current selection is not an exact pin.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub brew: Option<brew::Scope>,
67}
68#[derive(Serialize)]
69pub struct Review<'a> {
70    pub operation: &'static str,
71    pub scope: &'a Scope,
72    pub arguments: Vec<String>,
73    /// The selected provider installer.
74    pub installer: &'a std::path::Path,
75    pub fresh_inspections: Vec<inspection::Description>,
76    pub timeout_seconds: u64,
77    pub warning: &'static str,
78    pub fresh_probes: Vec<Vec<String>>,
79}
80#[derive(Clone, Serialize, Deserialize)]
81#[serde(deny_unknown_fields)]
82struct Sources {
83    manifest: Entry,
84    local_config: Entry,
85    executable: Entry,
86    host_sha256: String,
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    npm: Option<npm::Sources>,
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    brew: Option<brew::Sources>,
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    brew_probe: Option<brew::Probe>,
93}
94pub struct Preview {
95    request: Request,
96    scope: Scope,
97    sources: Sources,
98}
99pub struct Approval(Preview);
100impl Preview {
101    /// Compare session provenance with the independently captured core manifest.
102    pub fn manifest_matches(&self, entry: &Entry) -> bool {
103        same_source(&self.sources.manifest, entry)
104    }
105    pub fn review(&self) -> Review<'_> {
106        Review {
107            operation: "Freshly inspect the displayed scopes, conditionally install this still-missing package, then inspect again. No intentional other top-level upgrade request.",
108            scope: &self.scope,
109            arguments: arguments(&self.scope),
110            installer: &self.scope.executable,
111            fresh_inspections: self
112                .scope
113                .brew
114                .as_ref()
115                .map(|b| &b.catalogs)
116                .or_else(|| self.scope.npm.as_ref().map(|n| &n.catalogs))
117                .expect("validated provider catalogs")
118                .iter()
119                .map(|c| {
120                    c.preview(&self.scope.home)
121                        .expect("validated catalog")
122                        .description()
123                        .clone()
124                })
125                .collect(),
126            fresh_probes: self
127                .scope
128                .brew
129                .as_ref()
130                .map(|_| brew::probe_arguments(&self.scope.package))
131                .unwrap_or_default(),
132            timeout_seconds: TIMEOUT_SECONDS,
133            warning: if self.scope.brew.is_some() {
134                brew::WARNING
135            } else {
136                npm::WARNING
137            },
138        }
139    }
140    pub fn approve(self) -> Approval {
141        Approval(self)
142    }
143}
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum ProcessOutcome {
147    Success,
148    Failed,
149    Unavailable,
150    Pipe,
151    Wait,
152    Timeout,
153}
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "snake_case")]
156pub enum PackageState {
157    ExactPresent,
158    ProviderCurrentPresent,
159    Absent,
160    Conflict,
161    Unavailable,
162}
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
164#[serde(rename_all = "snake_case")]
165pub enum BinaryState {
166    Missing,
167    Candidates,
168    Unavailable,
169}
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(deny_unknown_fields)]
172pub struct Outcome {
173    pub process: ProcessOutcome,
174    pub package: PackageState,
175    pub binary: BinaryState,
176}
177pub struct Report {
178    pub scope: Scope,
179    pub attempt_id: Option<String>,
180    pub no_op: bool,
181    pub outcome: Option<Outcome>,
182    pub observed_versions: Vec<String>,
183    pub possible_partial_effects: bool,
184    pub readiness_verified: bool,
185}
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum Event {
188    FreshValidation,
189    FreshInspection,
190    IntentDurable,
191    Installing,
192    PostInspection,
193    OutcomeDurable,
194}
195fn invalid(message: &'static str) -> Error {
196    Error::Invalid(message.into())
197}
198/// Static messages stay the default; reviewed scope paths may be named exactly so
199/// the user can fix them. Provider payloads never pass through this helper.
200fn scope_invalid(message: impl Into<String>) -> Error {
201    Error::Invalid(message.into())
202}
203fn arguments(scope: &Scope) -> Vec<String> {
204    if scope.brew.is_some() {
205        brew::arguments(&scope.package)
206    } else {
207        npm::arguments(scope)
208    }
209}
210fn same_source(a: &Entry, b: &Entry) -> bool {
211    a.path == b.path
212        && adoption::same(a, b, true)
213        && a.parents.len() == b.parents.len()
214        && a.parents.iter().zip(&b.parents).all(|(a, b)| {
215            a.path == b.path && adoption::parent_identity(&a.fingerprint, &b.fingerprint)
216        })
217}
218fn sources(
219    host: &HostContext,
220    request: &Request,
221    npm: Option<&npm::Scope>,
222    brew: Option<&brew::Scope>,
223) -> Result<(Manifest, Scope, Sources)> {
224    if [npm.is_some(), brew.is_some()]
225        .into_iter()
226        .filter(|p| *p)
227        .count()
228        != 1
229    {
230        return Err(invalid("installation requires one supported provider"));
231    }
232    let (local, local_config) = LocalConfig::load_bound(host)?;
233    let repository_id = local
234        .repositories
235        .iter()
236        .find(|(_, r)| r.root == request.repository)
237        .map(|(id, _)| id.clone())
238        .ok_or_else(|| invalid("tool installation requires a registered repository"))?;
239    let (manifest, entry) = observation::read_manifest(&request.repository.join("dort.toml"))
240        .map_err(|_| {
241            invalid("installation manifest unavailable, unsafe or invalid; contents withheld")
242        })?;
243    let rows = local.profile_rows(
244        &manifest.profiles,
245        host.platform,
246        Some(&request.repository),
247        &request.profiles,
248    )?;
249    let active = crate::profiles::active(&rows);
250    let tool = manifest
251        .tools
252        .iter()
253        .find(|t| t.id == request.tool && crate::profiles::selected(&t.profiles, &active))
254        .ok_or_else(|| invalid("selected tool is not active in this scope"))?;
255    let spec = &tool.install;
256    let provider = if brew.is_some() {
257        Provider::Brew
258    } else {
259        Provider::Npm
260    };
261    if spec.provider != provider {
262        return Err(invalid("unsupported installation provider"));
263    }
264    let policy = VersionPolicy::parse(spec.provider, spec.version.as_deref())
265        .map_err(|_| invalid("unsupported installation policy"))?;
266    let current_policy = brew.map(|b| &b.policy);
267    let version = match (&policy, current_policy) {
268        (VersionPolicy::ProviderDefault {}, Some(p)) if p == &policy => {
269            "provider_default".to_owned()
270        }
271        (VersionPolicy::Latest {}, Some(p)) if p == &policy => "latest".to_owned(),
272        (VersionPolicy::Exact { version }, None) => version.clone(),
273        _ => {
274            return Err(invalid(
275                "npm requires an exact version; brew requires provider-current policy",
276            ));
277        }
278    };
279    if request.bound_tools.is_empty()
280        || request.bound_tools.len() > 256
281        || !request.bound_tools.contains(&request.tool)
282        || request.bound_tools.iter().any(|id| {
283            !manifest
284                .tools
285                .iter()
286                .any(|t| &t.id == id && crate::profiles::selected(&t.profiles, &active))
287        })
288    {
289        return Err(invalid(
290            "installation requires bounded explicit active tool bindings",
291        ));
292    }
293    if let Some(npm) = npm {
294        if spec.runtime_tool.as_ref() != Some(&npm.binding.runtime_tool)
295            || request.executable != npm.binding.node
296        {
297            return Err(invalid(
298                "npm installation runtime binding differs from declaration",
299            ));
300        }
301        inspection::Preview::npm(
302            &manifest,
303            npm.binding.clone(),
304            host.home.clone(),
305            request.search_dirs.clone(),
306        )
307        .map_err(|_| invalid("invalid explicit npm installation binding"))?;
308    } else if brew.is_some() {
309        inspection::Preview::new(
310            inspection::Query::BrewFormulae,
311            request.executable.clone(),
312            host.home.clone(),
313            request.search_dirs.clone(),
314        )
315        .map_err(|_| invalid("invalid explicit Homebrew scope"))?;
316    } else {
317        return Err(invalid("unsupported installation provider"));
318    }
319    binaries::validate(&manifest, &active, &request.tool_search_dirs)?;
320    let executable = observation::inspect(&request.executable, false)?;
321    if executable.kind != Kind::Regular
322        || executable
323            .fingerprint
324            .as_ref()
325            .is_none_or(|f| f.mode & 0o111 == 0 || f.links != 1)
326    {
327        return Err(invalid(
328            "installation needs a regular executable at the explicit canonical path",
329        ));
330    }
331    let scope = Scope {
332        platform: host.platform,
333        architecture: host.architecture,
334        repository: request.repository.clone(),
335        repository_id,
336        profiles: active,
337        tool: tool.id.clone(),
338        binary: tool.binary.clone(),
339        package: spec.package.clone(),
340        version,
341        executable: request.executable.clone(),
342        home: host.home.clone(),
343        search_dirs: request.search_dirs.clone(),
344        tool_search_dirs: request.tool_search_dirs.clone(),
345        bound_tools: request.bound_tools.clone(),
346        npm: npm.cloned(),
347        brew: brew.cloned(),
348    };
349    if !attempts::valid_scope(&scope) {
350        return Err(invalid("installation scope exceeds supported bounds"));
351    }
352    let sources = Sources {
353        manifest: entry,
354        local_config,
355        executable,
356        host_sha256: journal::digest(journal::encode(host)?.as_bytes()),
357        brew_probe: None,
358        brew: if scope.brew.is_some() {
359            Some(brew::sources(&scope)?)
360        } else {
361            None
362        },
363        npm: if scope.npm.is_some() {
364            Some(npm::sources(&scope)?)
365        } else {
366            None
367        },
368    };
369    Ok((manifest, scope, sources))
370}
371fn bounded_metadata(scope: &Scope, sources: &Sources) -> Result<()> {
372    let size = journal::encode(&(scope, sources))?.len();
373    if size > METADATA_LIMIT {
374        return Err(scope_invalid(format!(
375            "installation metadata is {size} bytes, over the {METADATA_LIMIT} byte limit"
376        )));
377    }
378    Ok(())
379}
380fn evaluate_catalogs(
381    host: &HostContext,
382    manifest: &Manifest,
383    scope: &Scope,
384    reports: &[&inspection::Report],
385) -> Result<planning::Row> {
386    let binary_report = binaries::observe(manifest, &scope.profiles, &scope.tool_search_dirs)?;
387    let catalogs = if let Some(brew) = &scope.brew {
388        brew::catalogs(scope, brew, reports)?
389    } else if let Some(npm) = &scope.npm {
390        npm::catalogs(scope, npm, reports)?
391    } else {
392        return Err(invalid("installation requires supported provider catalogs"));
393    };
394    let observed = planning::Observations {
395        catalogs,
396        binaries: binary_report
397            .tools
398            .into_iter()
399            .map(|(id, t)| (id, t.observation))
400            .collect(),
401    };
402    planning::plan(manifest, host.platform, &scope.profiles, &observed)?
403        .rows
404        .into_iter()
405        .find(|r| r.id == scope.tool)
406        .ok_or_else(|| invalid("selected installation row disappeared"))
407}
408fn reviewable(row: &planning::Row, environment: bool) -> bool {
409    matches!(row.package, planning::PackageFinding::Absent)
410        && row.blockers.iter().all(|blocker| {
411            environment
412                && matches!(
413                    blocker,
414                    planning::Blocker::DependencyNeedsReview { .. }
415                        | planning::Blocker::DependencyBlocked { .. }
416                )
417        })
418}
419
420pub(crate) fn preview_binding(preview: &Preview) -> Result<String> {
421    let sources = &preview.sources;
422    let brew = sources.brew.as_ref().map(brew::effect_sources);
423    let npm = sources.npm.as_ref().map(npm::effect_sources);
424    Ok(journal::digest(
425        adoption::canonical(&(
426            &preview.scope,
427            sources.manifest.clone().stable_parents(),
428            sources.local_config.clone().stable_parents(),
429            sources.executable.clone().stable_parents(),
430            &sources.host_sha256,
431            brew,
432            npm,
433        ))?
434        .as_bytes(),
435    ))
436}
437
438fn row_versions(row: &planning::Row) -> Vec<String> {
439    match &row.package {
440        planning::PackageFinding::Present { versions } => {
441            versions.iter().map(|v| v.version.clone()).collect()
442        }
443        _ => Vec::new(),
444    }
445}
446fn observe(
447    host: &HostContext,
448    manifest: &Manifest,
449    scope: &Scope,
450    reports: &[&inspection::Report],
451) -> (PackageState, BinaryState, Vec<String>) {
452    match evaluate_catalogs(host, manifest, scope, reports) {
453        Ok(row) => {
454            let versions = if scope.brew.is_some() {
455                row_versions(&row)
456            } else {
457                Vec::new()
458            };
459            let package = match row.package {
460                planning::PackageFinding::Present { versions }
461                    if versions
462                        .iter()
463                        .any(|v| v.policy_match == VersionMatch::Satisfied) =>
464                {
465                    if scope.brew.is_some() {
466                        PackageState::ProviderCurrentPresent
467                    } else {
468                        PackageState::ExactPresent
469                    }
470                }
471                planning::PackageFinding::Absent => PackageState::Absent,
472                planning::PackageFinding::Unavailable { .. }
473                | planning::PackageFinding::NotObserved => PackageState::Unavailable,
474                _ => PackageState::Conflict,
475            };
476            let binary = match row.binary_observation {
477                planning::BinaryObservation::Missing => BinaryState::Missing,
478                planning::BinaryObservation::Candidates { .. } => BinaryState::Candidates,
479                _ => BinaryState::Unavailable,
480            };
481            (package, binary, versions)
482        }
483        Err(_) => (
484            PackageState::Unavailable,
485            BinaryState::Unavailable,
486            Vec::new(),
487        ),
488    }
489}
490fn collect(host: &HostContext, old: &Preview) -> Result<Vec<inspection::Report>> {
491    let (manifest, scope, _) = revalidate(host, old)?;
492    if let Some(catalogs) = scope
493        .brew
494        .as_ref()
495        .map(|b| &b.catalogs)
496        .or_else(|| scope.npm.as_ref().map(|n| &n.catalogs))
497    {
498        catalogs
499            .iter()
500            .map(|c| {
501                revalidate(host, old)?;
502                if let Some(b) = &c.npm_binding {
503                    inspection::Preview::npm(
504                        &manifest,
505                        b.clone(),
506                        scope.home.clone(),
507                        c.search_dirs.clone(),
508                    )
509                    .map_err(|_| invalid("installation catalog runtime no longer declared"))?;
510                }
511                let report = c.preview(&scope.home)?.approve().inspect();
512                revalidate(host, old)?;
513                Ok(report)
514            })
515            .collect()
516    } else {
517        Err(invalid("installation requires supported provider catalogs"))
518    }
519}
520fn revalidate(host: &HostContext, old: &Preview) -> Result<(Manifest, Scope, Sources)> {
521    let (manifest, scope, fresh) = sources(
522        host,
523        &old.request,
524        old.scope.npm.as_ref(),
525        old.scope.brew.as_ref(),
526    )?;
527    if journal::encode(&scope)? != journal::encode(&old.scope)?
528        || fresh.host_sha256 != old.sources.host_sha256
529        || !same_source(&fresh.manifest, &old.sources.manifest)
530        || !same_source(&fresh.local_config, &old.sources.local_config)
531        || !same_source(&fresh.executable, &old.sources.executable)
532        || match (&fresh.brew, &old.sources.brew) {
533            (Some(a), Some(b)) => !brew::same(a, b),
534            (None, None) => false,
535            _ => true,
536        }
537        || match (&fresh.npm, &old.sources.npm) {
538            (Some(a), Some(b)) => !npm::same(a, b),
539            (None, None) => false,
540            _ => true,
541        }
542    {
543        return Err(invalid(
544            "installation scope changed; request a fresh review",
545        ));
546    }
547    Ok((manifest, scope, fresh))
548}
549/// Call only under the application writer lock after consuming a real preview.
550pub fn execute(
551    host: &HostContext,
552    lock: &WriterLock,
553    approval: Approval,
554    mut observer: impl FnMut(Event),
555) -> Result<Report> {
556    lock.check_context(host)?;
557    journal::ensure_writable(host)?;
558    attempts::ensure_clear(host)?;
559    let mut old = approval.0;
560    observer(Event::FreshValidation);
561    let (manifest, scope, mut fresh) = revalidate(host, &old)?;
562    observer(Event::FreshInspection);
563    let brew_probe = if scope.brew.is_some() {
564        Some(brew::probe(&scope, || revalidate(host, &old).map(|_| ()))?)
565    } else {
566        None
567    };
568    let before = collect(host, &old)?;
569    let before_refs = before.iter().collect::<Vec<_>>();
570    let row = evaluate_catalogs(host, &manifest, &scope, &before_refs)?;
571    revalidate(host, &old)?;
572    if let Some(probe) = &brew_probe
573        && row_versions(&row) != probe.installed_versions
574    {
575        return Err(invalid(
576            "Homebrew target and installed catalog observations disagree; inspect again",
577        ));
578    }
579    if row.action == planning::PackageAction::NoChange {
580        let observed_versions = brew_probe
581            .as_ref()
582            .map(|p| p.installed_versions.clone())
583            .unwrap_or_default();
584        return Ok(Report {
585            scope,
586            attempt_id: None,
587            no_op: true,
588            outcome: None,
589            observed_versions,
590            possible_partial_effects: false,
591            readiness_verified: false,
592        });
593    }
594    if row.action != planning::PackageAction::ReviewMissingPackage || !row.blockers.is_empty() {
595        return Err(invalid(
596            "fresh inspection refused installation; inspect current scope and review again",
597        ));
598    }
599    fresh.brew_probe = brew_probe;
600    bounded_metadata(&scope, &fresh)?;
601    let attempt = attempts::begin(host, lock, scope.clone(), fresh)?;
602    observer(Event::IntentDurable);
603    // Fail closed if source bindings changed while intent was made durable.
604    revalidate(host, &old)?;
605    revalidate(host, &old)?;
606    journal::ensure_writable(host)?;
607    attempts::verify_pending(host, &attempt)?;
608    let ready = evaluate_catalogs(host, &manifest, &scope, &before_refs)?;
609    if ready.action != planning::PackageAction::ReviewMissingPackage || !ready.blockers.is_empty() {
610        return Err(invalid(
611            "binary or prerequisite scope changed before installation; inspect and close the pending attempt",
612        ));
613    }
614    if let Some(bound) = &old.sources.npm {
615        old.sources.npm = Some(npm::create_directories(&scope, bound)?);
616        revalidate(host, &old)?;
617        journal::ensure_writable(host)?;
618        attempts::verify_pending(host, &attempt)?;
619    }
620    observer(Event::Installing);
621    revalidate(host, &old)?;
622    journal::ensure_writable(host)?;
623    attempts::verify_pending(host, &attempt)?;
624    let ready = evaluate_catalogs(host, &manifest, &scope, &before_refs)?;
625    if ready.action != planning::PackageAction::ReviewMissingPackage || !ready.blockers.is_empty() {
626        return Err(invalid(
627            "binary or prerequisite scope changed before spawn; inspect the pending attempt",
628        ));
629    }
630    let process = process::run(&scope, std::time::Duration::from_secs(TIMEOUT_SECONDS));
631    observer(Event::PostInspection);
632    let (mut package, mut binary, mut observed_versions) = if revalidate(host, &old).is_ok() {
633        match collect(host, &old) {
634            Ok(after) => observe(host, &manifest, &scope, &after.iter().collect::<Vec<_>>()),
635            Err(_) => (
636                PackageState::Unavailable,
637                BinaryState::Unavailable,
638                Vec::new(),
639            ),
640        }
641    } else {
642        // Do not run a provider whose binding changed during installation.
643        (
644            PackageState::Unavailable,
645            BinaryState::Unavailable,
646            Vec::new(),
647        )
648    };
649    if revalidate(host, &old).is_err() {
650        package = PackageState::Unavailable;
651        binary = BinaryState::Unavailable;
652        observed_versions.clear();
653    }
654    if scope.brew.is_some() && revalidate(host, &old).is_ok() {
655        match brew::formula_info(&scope) {
656            Ok((_, versions)) if revalidate(host, &old).is_ok() => {
657                let expected = if versions.is_empty() {
658                    PackageState::Absent
659                } else {
660                    PackageState::ProviderCurrentPresent
661                };
662                if package != expected || observed_versions != versions {
663                    package = PackageState::Unavailable;
664                    observed_versions.clear();
665                }
666            }
667            _ => {
668                package = PackageState::Unavailable;
669                binary = BinaryState::Unavailable;
670                observed_versions.clear();
671            }
672        }
673    }
674    let outcome = Outcome {
675        process,
676        package,
677        binary,
678    };
679    attempts::finish(host, lock, &attempt, outcome, observed_versions.clone()).map_err(|_| crate::Error::Invalid(format!(
680        "Tools attempt {} has no durable outcome; inspect and close it before retrying (possible partial effects)", attempt.id
681    )))?;
682    observer(Event::OutcomeDurable);
683    Ok(Report {
684        scope,
685        attempt_id: Some(attempt.id),
686        no_op: false,
687        outcome: Some(outcome),
688        observed_versions,
689        possible_partial_effects: process != ProcessOutcome::Success
690            || !matches!(
691                package,
692                PackageState::ExactPresent | PackageState::ProviderCurrentPresent
693            ),
694        readiness_verified: false,
695    })
696}