Skip to main content

dort_core/tools/
binaries.rs

1//! Metadata-only command lookup.
2use super::{
3    inspection,
4    planning::{BinaryObservation, MAX_SELECTED_TOOLS},
5};
6use crate::{
7    Error, Manifest, Result,
8    observation::{self, Fingerprint, Kind},
9    profiles::selected,
10};
11use serde::Serialize;
12use std::{
13    collections::{BTreeMap, BTreeSet},
14    path::PathBuf,
15};
16
17pub const MAX_DIRECTORIES: usize = 32;
18pub const MAX_PROBES: usize = 32_768;
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "snake_case")]
21pub enum Failure {
22    DirectoryUnavailable,
23    EntryUnavailable,
24    Changed,
25}
26#[derive(Debug, Clone, Serialize)]
27#[serde(tag = "state", rename_all = "snake_case")]
28pub enum ProbeState {
29    Missing,
30    Present {
31        kind: Kind,
32        fingerprint: Fingerprint,
33        link_target: Option<PathBuf>,
34    },
35    Unavailable {
36        reason: Failure,
37    },
38}
39#[derive(Debug, Clone, Serialize)]
40pub struct Probe {
41    pub path: PathBuf,
42    pub observation: ProbeState,
43}
44#[derive(Debug, Serialize)]
45pub struct ToolObservation {
46    pub binary: String,
47    pub observation: BinaryObservation,
48    pub probes: Vec<Probe>,
49}
50#[derive(Debug, Serialize)]
51pub struct Directory {
52    pub path: PathBuf,
53    pub unavailable: Option<Failure>,
54}
55#[derive(Debug, Serialize)]
56pub struct Report {
57    pub directories: Vec<Directory>,
58    pub tools: BTreeMap<String, ToolObservation>,
59}
60impl Report {
61    pub fn available(&self) -> bool {
62        self.directories.iter().all(|d| d.unavailable.is_none())
63            && self
64                .tools
65                .values()
66                .all(|t| !matches!(t.observation, BinaryObservation::Unavailable))
67    }
68}
69fn invalid(message: &'static str) -> Error {
70    Error::Invalid(message.into())
71}
72/// Validate request shape without reading directories or discovering PATH.
73pub fn validate(
74    manifest: &Manifest,
75    active: &BTreeSet<String>,
76    directories: &[PathBuf],
77) -> Result<()> {
78    manifest.validate()?;
79    if !active.contains("base") || !active.is_subset(&manifest.profiles.known()) {
80        return Err(invalid(
81            "binary observation requires resolved known profiles including base",
82        ));
83    }
84    let count = manifest
85        .tools
86        .iter()
87        .filter(|t| selected(&t.profiles, active))
88        .count();
89    if count > MAX_SELECTED_TOOLS
90        || directories.is_empty()
91        || directories.len() > MAX_DIRECTORIES
92        || count.saturating_mul(directories.len()) > MAX_PROBES
93    {
94        return Err(invalid(
95            "binary observation scope exceeds supported tool/directory/probe limits",
96        ));
97    }
98    let distinct: BTreeSet<_> = directories.iter().collect();
99    if distinct.len() != directories.len()
100        || directories.iter().any(|p| {
101            !inspection::absolute(p) || p.as_os_str().len() > 4096 || p.components().count() > 64
102        })
103        || std::env::join_paths(directories).is_err()
104    {
105        return Err(invalid(
106            "tool-search directories must be distinct absolute UTF-8 paths without dot components or PATH separators",
107        ));
108    }
109    Ok(())
110}
111/// Inspect only selected declared names in explicit tool-search directories. These
112/// are NOT inferred from provider child PATH or the process environment. No files
113/// are opened for content, no links followed, no version/ownership inferred.
114pub fn observe(
115    manifest: &Manifest,
116    active: &BTreeSet<String>,
117    directories: &[PathBuf],
118) -> Result<Report> {
119    validate(manifest, active, directories)?;
120    let before: Vec<_> = directories
121        .iter()
122        .map(|path| {
123            observation::inspect(path, false)
124                .ok()
125                .filter(|e| e.kind == Kind::Directory)
126        })
127        .collect();
128    let mut directory_results: Vec<_> = directories
129        .iter()
130        .zip(&before)
131        .map(|(path, e)| Directory {
132            path: path.clone(),
133            unavailable: e.is_none().then_some(Failure::DirectoryUnavailable),
134        })
135        .collect();
136    let names: BTreeSet<_> = manifest
137        .tools
138        .iter()
139        .filter(|t| selected(&t.profiles, active))
140        .map(|t| t.binary.as_str())
141        .collect();
142    let mut probes_by_name = BTreeMap::new();
143    for name in names {
144        let mut probes = vec![];
145        for (index, directory) in directories.iter().enumerate() {
146            let path = directory.join(name);
147            let state = if before[index].is_none() {
148                ProbeState::Unavailable {
149                    reason: Failure::DirectoryUnavailable,
150                }
151            } else {
152                inspect_entry(&path)
153            };
154            probes.push(Probe {
155                path,
156                observation: state,
157            });
158        }
159        probes_by_name.insert(name, probes);
160    }
161    // Revalidate directory identities/metadata too, so changing parents or entries
162    // cannot silently turn a raced/partial scope into a healthy empty observation.
163    for (index, path) in directories.iter().enumerate() {
164        if let Some(original) = &before[index]
165            && observation::inspect(path, false).ok().as_ref() != Some(original)
166        {
167            directory_results[index].unavailable = Some(Failure::Changed);
168        }
169    }
170    let incomplete_scope = directory_results.iter().any(|d| d.unavailable.is_some());
171    let tools = manifest
172        .tools
173        .iter()
174        .filter(|t| selected(&t.profiles, active))
175        .map(|tool| {
176            let probes = probes_by_name[tool.binary.as_str()].clone();
177            let failed = incomplete_scope
178                || probes
179                    .iter()
180                    .any(|p| matches!(p.observation, ProbeState::Unavailable { .. }));
181            let paths: Vec<_> = probes
182                .iter()
183                .filter(|p| matches!(p.observation, ProbeState::Present { .. }))
184                .map(|p| p.path.clone())
185                .collect();
186            let observation = if failed {
187                BinaryObservation::Unavailable
188            } else if paths.is_empty() {
189                BinaryObservation::Missing
190            } else {
191                BinaryObservation::Candidates { paths }
192            };
193            (
194                tool.id.clone(),
195                ToolObservation {
196                    binary: tool.binary.clone(),
197                    observation,
198                    probes,
199                },
200            )
201        })
202        .collect();
203    Ok(Report {
204        directories: directory_results,
205        tools,
206    })
207}
208fn inspect_entry(path: &std::path::Path) -> ProbeState {
209    let Ok(entry) = observation::inspect(path, false) else {
210        return ProbeState::Unavailable {
211            reason: Failure::EntryUnavailable,
212        };
213    };
214    if observation::inspect(path, false).ok().as_ref() != Some(&entry) {
215        return ProbeState::Unavailable {
216            reason: Failure::Changed,
217        };
218    }
219    match (entry.kind, entry.fingerprint) {
220        (Kind::Missing, _) => ProbeState::Missing,
221        (kind, Some(fingerprint)) => ProbeState::Present {
222            kind,
223            fingerprint,
224            link_target: entry.link_target,
225        },
226        _ => ProbeState::Unavailable {
227            reason: Failure::EntryUnavailable,
228        },
229    }
230}