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 mut profiles = local.active_profiles;
244    for profile in &request.profiles {
245        if !profiles.contains(profile) {
246            profiles.push(profile.clone());
247        }
248    }
249    let active = manifest.profiles.resolve(host.platform, &profiles)?;
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 row_versions(row: &planning::Row) -> Vec<String> {
409    match &row.package {
410        planning::PackageFinding::Present { versions } => {
411            versions.iter().map(|v| v.version.clone()).collect()
412        }
413        _ => Vec::new(),
414    }
415}
416fn observe(
417    host: &HostContext,
418    manifest: &Manifest,
419    scope: &Scope,
420    reports: &[&inspection::Report],
421) -> (PackageState, BinaryState, Vec<String>) {
422    match evaluate_catalogs(host, manifest, scope, reports) {
423        Ok(row) => {
424            let versions = if scope.brew.is_some() {
425                row_versions(&row)
426            } else {
427                Vec::new()
428            };
429            let package = match row.package {
430                planning::PackageFinding::Present { versions }
431                    if versions
432                        .iter()
433                        .any(|v| v.policy_match == VersionMatch::Satisfied) =>
434                {
435                    if scope.brew.is_some() {
436                        PackageState::ProviderCurrentPresent
437                    } else {
438                        PackageState::ExactPresent
439                    }
440                }
441                planning::PackageFinding::Absent => PackageState::Absent,
442                planning::PackageFinding::Unavailable { .. }
443                | planning::PackageFinding::NotObserved => PackageState::Unavailable,
444                _ => PackageState::Conflict,
445            };
446            let binary = match row.binary_observation {
447                planning::BinaryObservation::Missing => BinaryState::Missing,
448                planning::BinaryObservation::Candidates { .. } => BinaryState::Candidates,
449                _ => BinaryState::Unavailable,
450            };
451            (package, binary, versions)
452        }
453        Err(_) => (
454            PackageState::Unavailable,
455            BinaryState::Unavailable,
456            Vec::new(),
457        ),
458    }
459}
460fn collect(host: &HostContext, old: &Preview) -> Result<Vec<inspection::Report>> {
461    let (manifest, scope, _) = revalidate(host, old)?;
462    if let Some(catalogs) = scope
463        .brew
464        .as_ref()
465        .map(|b| &b.catalogs)
466        .or_else(|| scope.npm.as_ref().map(|n| &n.catalogs))
467    {
468        catalogs
469            .iter()
470            .map(|c| {
471                revalidate(host, old)?;
472                if let Some(b) = &c.npm_binding {
473                    inspection::Preview::npm(
474                        &manifest,
475                        b.clone(),
476                        scope.home.clone(),
477                        c.search_dirs.clone(),
478                    )
479                    .map_err(|_| invalid("installation catalog runtime no longer declared"))?;
480                }
481                let report = c.preview(&scope.home)?.approve().inspect();
482                revalidate(host, old)?;
483                Ok(report)
484            })
485            .collect()
486    } else {
487        Err(invalid("installation requires supported provider catalogs"))
488    }
489}
490fn revalidate(host: &HostContext, old: &Preview) -> Result<(Manifest, Scope, Sources)> {
491    let (manifest, scope, fresh) = sources(
492        host,
493        &old.request,
494        old.scope.npm.as_ref(),
495        old.scope.brew.as_ref(),
496    )?;
497    if journal::encode(&scope)? != journal::encode(&old.scope)?
498        || fresh.host_sha256 != old.sources.host_sha256
499        || !same_source(&fresh.manifest, &old.sources.manifest)
500        || !same_source(&fresh.local_config, &old.sources.local_config)
501        || !same_source(&fresh.executable, &old.sources.executable)
502        || match (&fresh.brew, &old.sources.brew) {
503            (Some(a), Some(b)) => !brew::same(a, b),
504            (None, None) => false,
505            _ => true,
506        }
507        || match (&fresh.npm, &old.sources.npm) {
508            (Some(a), Some(b)) => !npm::same(a, b),
509            (None, None) => false,
510            _ => true,
511        }
512    {
513        return Err(invalid(
514            "installation scope changed; request a fresh review",
515        ));
516    }
517    Ok((manifest, scope, fresh))
518}
519/// Call only under the application writer lock after consuming a real preview.
520pub fn execute(
521    host: &HostContext,
522    lock: &WriterLock,
523    approval: Approval,
524    mut observer: impl FnMut(Event),
525) -> Result<Report> {
526    lock.check_context(host)?;
527    journal::ensure_writable(host)?;
528    attempts::ensure_clear(host)?;
529    let mut old = approval.0;
530    observer(Event::FreshValidation);
531    let (manifest, scope, mut fresh) = revalidate(host, &old)?;
532    observer(Event::FreshInspection);
533    let brew_probe = if scope.brew.is_some() {
534        Some(brew::probe(&scope, || revalidate(host, &old).map(|_| ()))?)
535    } else {
536        None
537    };
538    let before = collect(host, &old)?;
539    let before_refs = before.iter().collect::<Vec<_>>();
540    let row = evaluate_catalogs(host, &manifest, &scope, &before_refs)?;
541    revalidate(host, &old)?;
542    if let Some(probe) = &brew_probe
543        && row_versions(&row) != probe.installed_versions
544    {
545        return Err(invalid(
546            "Homebrew target and installed catalog observations disagree; inspect again",
547        ));
548    }
549    if row.action == planning::PackageAction::NoChange {
550        let observed_versions = brew_probe
551            .as_ref()
552            .map(|p| p.installed_versions.clone())
553            .unwrap_or_default();
554        return Ok(Report {
555            scope,
556            attempt_id: None,
557            no_op: true,
558            outcome: None,
559            observed_versions,
560            possible_partial_effects: false,
561            readiness_verified: false,
562        });
563    }
564    if row.action != planning::PackageAction::ReviewMissingPackage || !row.blockers.is_empty() {
565        return Err(invalid(
566            "fresh inspection refused installation; inspect current scope and review again",
567        ));
568    }
569    fresh.brew_probe = brew_probe;
570    bounded_metadata(&scope, &fresh)?;
571    let attempt = attempts::begin(host, lock, scope.clone(), fresh)?;
572    observer(Event::IntentDurable);
573    // Fail closed if source bindings changed while intent was made durable.
574    revalidate(host, &old)?;
575    revalidate(host, &old)?;
576    journal::ensure_writable(host)?;
577    attempts::verify_pending(host, &attempt)?;
578    let ready = evaluate_catalogs(host, &manifest, &scope, &before_refs)?;
579    if ready.action != planning::PackageAction::ReviewMissingPackage || !ready.blockers.is_empty() {
580        return Err(invalid(
581            "binary or prerequisite scope changed before installation; inspect and close the pending attempt",
582        ));
583    }
584    if let Some(bound) = &old.sources.npm {
585        old.sources.npm = Some(npm::create_directories(&scope, bound)?);
586        revalidate(host, &old)?;
587        journal::ensure_writable(host)?;
588        attempts::verify_pending(host, &attempt)?;
589    }
590    observer(Event::Installing);
591    revalidate(host, &old)?;
592    journal::ensure_writable(host)?;
593    attempts::verify_pending(host, &attempt)?;
594    let ready = evaluate_catalogs(host, &manifest, &scope, &before_refs)?;
595    if ready.action != planning::PackageAction::ReviewMissingPackage || !ready.blockers.is_empty() {
596        return Err(invalid(
597            "binary or prerequisite scope changed before spawn; inspect the pending attempt",
598        ));
599    }
600    let process = process::run(&scope, std::time::Duration::from_secs(TIMEOUT_SECONDS));
601    observer(Event::PostInspection);
602    let (mut package, mut binary, mut observed_versions) = if revalidate(host, &old).is_ok() {
603        match collect(host, &old) {
604            Ok(after) => observe(host, &manifest, &scope, &after.iter().collect::<Vec<_>>()),
605            Err(_) => (
606                PackageState::Unavailable,
607                BinaryState::Unavailable,
608                Vec::new(),
609            ),
610        }
611    } else {
612        // Do not run a provider whose binding changed during installation.
613        (
614            PackageState::Unavailable,
615            BinaryState::Unavailable,
616            Vec::new(),
617        )
618    };
619    if revalidate(host, &old).is_err() {
620        package = PackageState::Unavailable;
621        binary = BinaryState::Unavailable;
622        observed_versions.clear();
623    }
624    if scope.brew.is_some() && revalidate(host, &old).is_ok() {
625        match brew::formula_info(&scope) {
626            Ok((_, versions)) if revalidate(host, &old).is_ok() => {
627                let expected = if versions.is_empty() {
628                    PackageState::Absent
629                } else {
630                    PackageState::ProviderCurrentPresent
631                };
632                if package != expected || observed_versions != versions {
633                    package = PackageState::Unavailable;
634                    observed_versions.clear();
635                }
636            }
637            _ => {
638                package = PackageState::Unavailable;
639                binary = BinaryState::Unavailable;
640                observed_versions.clear();
641            }
642        }
643    }
644    let outcome = Outcome {
645        process,
646        package,
647        binary,
648    };
649    attempts::finish(host, lock, &attempt, outcome, observed_versions.clone()).map_err(|_| crate::Error::Invalid(format!(
650        "Tools attempt {} has no durable outcome; inspect and close it before retrying (possible partial effects)", attempt.id
651    )))?;
652    observer(Event::OutcomeDurable);
653    Ok(Report {
654        scope,
655        attempt_id: Some(attempt.id),
656        no_op: false,
657        outcome: Some(outcome),
658        observed_versions,
659        possible_partial_effects: process != ProcessOutcome::Success
660            || !matches!(
661                package,
662                PackageState::ExactPresent | PackageState::ProviderCurrentPresent
663            ),
664        readiness_verified: false,
665    })
666}