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