1use super::{VersionMatch, VersionPolicy, inspection};
3use crate::{
4 Error, Manifest, Result,
5 model::{InstallSpec, Provider},
6 platform::Platform,
7 profiles::selected,
8};
9use serde::Serialize;
10use std::{
11 collections::{BTreeMap, BTreeSet},
12 path::PathBuf,
13};
14
15pub const MAX_SELECTED_TOOLS: usize = 4096;
16pub const MAX_VERSION_CLAIMS: usize = 65_536;
17const MAX_CATALOG_RECORDS: usize = 32_768;
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)]
22#[serde(tag = "state", rename_all = "snake_case")]
23pub enum BinaryObservation {
24 #[default]
25 NotObserved,
26 Unavailable,
27 Missing,
28 Candidates {
29 paths: Vec<PathBuf>,
30 },
31}
32#[derive(Default)]
35pub struct Observations<'a> {
36 pub catalogs: BTreeMap<String, &'a inspection::Report>,
37 pub binaries: BTreeMap<String, BinaryObservation>,
38}
39#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
40#[serde(rename_all = "snake_case")]
41pub enum ScopeIssue {
42 WrongProvider,
43 InvalidRuntimeBinding,
44}
45#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
46pub struct VersionClaim {
47 pub version: String,
48 pub policy_match: VersionMatch,
49}
50#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
51#[serde(tag = "state", rename_all = "snake_case")]
52pub enum PackageFinding {
53 NotObserved,
54 Unavailable {
55 reason: inspection::Failure,
56 },
57 ScopeMismatch {
58 reason: ScopeIssue,
59 },
60 AmbiguousIdentity,
62 Absent,
63 InvalidMetadata,
65 Present {
66 versions: Vec<VersionClaim>,
67 },
68}
69#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
70#[serde(tag = "reason", rename_all = "snake_case")]
71pub enum Blocker {
72 ProviderNotObserved,
73 ProviderUnavailable,
74 ProviderScopeMismatch,
75 AmbiguousPackageIdentity,
76 InvalidProviderMetadata,
77 VersionMismatch,
78 VersionUnverifiable,
79 BinaryNotObserved,
80 BinaryObservationUnavailable,
81 UnattributedBinaryCandidates,
82 RuntimeBindingUnverified,
83 DependencyInactive {
84 tool: String,
85 },
86 DependencyBlocked {
87 tool: String,
88 },
89 DependencyNeedsReview {
91 tool: String,
92 },
93}
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
95#[serde(rename_all = "snake_case")]
96pub enum PackageAction {
97 NoChange,
99 ReviewMissingPackage,
101 Blocked,
102}
103#[derive(Debug, Serialize)]
104pub struct Declaration {
105 pub provider: Provider,
106 pub package: String,
107 pub policy: VersionPolicy,
108 pub runtime_tool: Option<String>,
109}
110#[derive(Debug, Serialize)]
111pub struct CatalogScope {
112 pub query: inspection::Query,
113 pub executable: PathBuf,
114 pub home: PathBuf,
115 pub npm_binding: Option<inspection::NpmBinding>,
116}
117#[derive(Debug, Serialize)]
118pub struct Row {
119 pub id: String,
120 pub binary: String,
121 pub dependencies: Vec<String>,
122 pub declaration: Option<Declaration>,
123 pub catalog_scope: Option<CatalogScope>,
124 pub package: PackageFinding,
125 pub binary_observation: BinaryObservation,
126 pub action: PackageAction,
127 pub blockers: Vec<Blocker>,
128 pub install_preview: super::install_preview::Preview,
129}
130#[derive(Debug, Serialize)]
131pub struct Plan {
132 pub platform: Platform,
133 pub active_profiles: BTreeSet<String>,
134 pub rows: Vec<Row>,
136}
137impl Plan {
138 pub fn has_blockers(&self) -> bool {
139 self.rows.iter().any(|row| !row.blockers.is_empty())
140 }
141}
142fn invalid(message: &'static str) -> Error {
143 Error::Invalid(message.into())
144}
145
146pub fn plan(
152 manifest: &Manifest,
153 platform: Platform,
154 active: &BTreeSet<String>,
155 observed: &Observations<'_>,
156) -> Result<Plan> {
157 manifest.validate()?;
158 if !active.contains("base") || !active.is_subset(&manifest.profiles.known()) {
159 return Err(invalid(
160 "tool planning requires resolved, known profiles including base",
161 ));
162 }
163 let tools: BTreeMap<_, _> = manifest
164 .tools
165 .iter()
166 .filter(|t| selected(&t.profiles, active))
167 .map(|t| (t.id.clone(), t))
168 .collect();
169 if tools.len() > MAX_SELECTED_TOOLS {
170 return Err(invalid("tool planning selected-tool limit exceeded"));
171 }
172 if observed
173 .catalogs
174 .keys()
175 .chain(observed.binaries.keys())
176 .any(|id| !tools.contains_key(id))
177 {
178 return Err(invalid("The checked tool is not in the manifest."));
179 }
180 validate_observations(observed)?;
181 let order = manifest.order(platform, &tools.keys().cloned().collect())?;
182 let mut rows: Vec<Row> = vec![];
183 let mut claim_count = 0usize;
184 for id in order {
185 let tool = tools[&id];
186 let deps: Vec<_> = manifest
187 .dependencies(tool, platform)
188 .into_iter()
189 .map(str::to_owned)
190 .collect();
191 let binary = observed.binaries.get(&id).cloned().unwrap_or_default();
192 let report = observed.catalogs.get(&id).copied();
193 let spec = &tool.install;
194 let declaration = Some(Declaration {
195 provider: spec.provider,
196 package: spec.package.clone(),
197 policy: VersionPolicy::parse(spec.provider, spec.version.as_deref())
198 .map_err(|_| invalid("unsupported tool version policy"))?,
199 runtime_tool: spec.runtime_tool.clone(),
200 });
201 let package = classify(
202 spec,
203 &declaration.as_ref().expect("declared tool").policy,
204 report,
205 );
206 if let PackageFinding::Present { versions } = &package {
207 claim_count += versions.len();
208 if claim_count > MAX_VERSION_CLAIMS {
209 return Err(invalid("tool planning version-claim limit exceeded"));
210 }
211 }
212 let mut blockers = package_blockers(&package);
213 if declaration
214 .as_ref()
215 .is_some_and(|d| !comparable_policy(&d.policy))
216 && !blockers.contains(&Blocker::VersionUnverifiable)
217 {
218 blockers.push(Blocker::VersionUnverifiable);
219 }
220 let satisfied = matches!(&package, PackageFinding::Present { versions } if versions.iter().any(|v| v.policy_match == VersionMatch::Satisfied));
221 if matches!(package, PackageFinding::Absent) {
222 match &binary {
223 BinaryObservation::NotObserved => blockers.push(Blocker::BinaryNotObserved),
224 BinaryObservation::Unavailable => {
225 blockers.push(Blocker::BinaryObservationUnavailable)
226 }
227 BinaryObservation::Candidates { .. } => {
228 blockers.push(Blocker::UnattributedBinaryCandidates)
229 }
230 BinaryObservation::Missing => (),
231 }
232 if spec.provider == Provider::Npm && !runtime_candidate_matches(spec, report, observed)
233 {
234 blockers.push(Blocker::RuntimeBindingUnverified);
235 }
236 }
237 for dependency in &deps {
238 if !tools.contains_key(dependency) {
239 blockers.push(Blocker::DependencyInactive {
240 tool: dependency.clone(),
241 });
242 } else if let Some(row) = rows.iter().find(|row| &row.id == dependency) {
243 if !row.blockers.is_empty() {
244 blockers.push(Blocker::DependencyBlocked {
245 tool: dependency.clone(),
246 });
247 } else if row.action == PackageAction::ReviewMissingPackage {
248 blockers.push(Blocker::DependencyNeedsReview {
249 tool: dependency.clone(),
250 });
251 }
252 }
253 }
254 let action = if satisfied {
255 PackageAction::NoChange
256 } else if matches!(package, PackageFinding::Absent) && blockers.is_empty() {
257 PackageAction::ReviewMissingPackage
258 } else {
259 PackageAction::Blocked
260 };
261 rows.push(Row {
262 id: id.clone(),
263 binary: tool.binary.clone(),
264 dependencies: deps,
265 declaration,
266 catalog_scope: report.map(|r| CatalogScope {
267 query: r.description.query,
268 executable: r.description.executable.clone(),
269 home: r.description.home.clone(),
270 npm_binding: r.description.npm_binding.clone(),
271 }),
272 package,
273 binary_observation: binary,
274 action,
275 blockers,
276 install_preview: Default::default(),
277 });
278 }
279 let mut preview_bytes = 0usize;
280 for row in &mut rows {
281 let paths = observed
282 .catalogs
283 .get(&row.id)
284 .map_or(&[][..], |r| r.description.trusted_search_path.as_slice());
285 row.install_preview = super::install_preview::describe(row, paths, &mut preview_bytes);
286 }
287 Ok(Plan {
288 platform,
289 active_profiles: active.clone(),
290 rows,
291 })
292}
293
294fn validate_observations(observed: &Observations<'_>) -> Result<()> {
295 let valid = |path: &PathBuf| inspection::absolute(path);
296 for binary in observed.binaries.values() {
297 if let BinaryObservation::Candidates { paths } = binary
298 && (paths.is_empty() || paths.len() > 1024 || !paths.iter().all(valid))
299 {
300 return Err(invalid(
301 "binary candidates require a bounded nonempty list of absolute UTF-8 paths without dot components",
302 ));
303 }
304 }
305 for report in observed.catalogs.values() {
306 if let inspection::Observation::Complete { installations } = &report.observation
307 && installations.len() > MAX_CATALOG_RECORDS
308 {
309 return Err(invalid("Too many package records."));
310 }
311 let d = &report.description;
312 if !valid(&d.executable)
313 || !valid(&d.home)
314 || d.trusted_search_path.is_empty()
315 || !d.trusted_search_path.iter().all(valid)
316 || std::env::join_paths(&d.trusted_search_path).is_err()
317 || d.npm_binding
318 .as_ref()
319 .is_some_and(|b| !valid(&b.node) || !valid(&b.npm_cli) || !valid(&b.prefix))
320 {
321 return Err(invalid(
322 "Package-manager settings need absolute UTF-8 paths without dot components.",
323 ));
324 }
325 }
326 Ok(())
327}
328fn classify(
329 spec: &InstallSpec,
330 policy: &VersionPolicy,
331 report: Option<&inspection::Report>,
332) -> PackageFinding {
333 let Some(report) = report else {
334 return PackageFinding::NotObserved;
335 };
336 let d = &report.description;
337 if d.query.provider() != spec.provider {
338 return PackageFinding::ScopeMismatch {
339 reason: ScopeIssue::WrongProvider,
340 };
341 }
342 if (spec.provider == Provider::Npm
343 && d.npm_binding.as_ref().is_none_or(|b| {
344 Some(b.runtime_tool.as_str()) != spec.runtime_tool.as_deref() || b.node != d.executable
345 }))
346 || (spec.provider != Provider::Npm && d.npm_binding.is_some())
347 {
348 return PackageFinding::ScopeMismatch {
349 reason: ScopeIssue::InvalidRuntimeBinding,
350 };
351 }
352 let installations = match &report.observation {
353 inspection::Observation::Unavailable { reason } => {
354 return PackageFinding::Unavailable { reason: *reason };
355 }
356 inspection::Observation::Complete { installations } => installations,
357 };
358 let mut versions: BTreeSet<String> = BTreeSet::new();
359 let mut related = false;
360 for entry in installations {
361 if entry.package == spec.package {
362 if !super::valid_observed_version(&entry.version) {
363 return PackageFinding::InvalidMetadata;
364 }
365 versions.insert(entry.version.clone());
366 } else if related_identity(spec.provider, &spec.package, &entry.package) {
367 related = true;
368 }
369 }
370 if versions.is_empty() {
371 if related {
372 PackageFinding::AmbiguousIdentity
373 } else {
374 PackageFinding::Absent
375 }
376 } else {
377 PackageFinding::Present {
378 versions: versions
379 .into_iter()
380 .map(|version| VersionClaim {
381 policy_match: policy.matches_version(Some(&version)),
382 version,
383 })
384 .collect(),
385 }
386 }
387}
388fn related_identity(provider: Provider, requested: &str, reported: &str) -> bool {
389 match provider {
390 Provider::Brew => requested.rsplit('/').next() == reported.rsplit('/').next(),
391 Provider::Npm => false,
392 }
393}
394fn comparable_policy(policy: &VersionPolicy) -> bool {
395 match policy {
396 VersionPolicy::ProviderDefault {} | VersionPolicy::Latest {} => true,
397 VersionPolicy::Exact { version } => super::valid_observed_version(version),
398 }
399}
400fn package_blockers(package: &PackageFinding) -> Vec<Blocker> {
401 use PackageFinding::*;
402 match package {
403 NotObserved => vec![Blocker::ProviderNotObserved],
404 Unavailable { .. } => vec![Blocker::ProviderUnavailable],
405 ScopeMismatch { .. } => vec![Blocker::ProviderScopeMismatch],
406 AmbiguousIdentity => vec![Blocker::AmbiguousPackageIdentity],
407 InvalidMetadata => vec![Blocker::InvalidProviderMetadata],
408 Absent => vec![],
409 Present { versions }
410 if versions
411 .iter()
412 .any(|v| v.policy_match == VersionMatch::Satisfied) =>
413 {
414 vec![]
415 }
416 Present { versions }
417 if versions
418 .iter()
419 .any(|v| v.policy_match == VersionMatch::Unverifiable) =>
420 {
421 vec![Blocker::VersionUnverifiable]
422 }
423 Present { .. } => vec![Blocker::VersionMismatch],
424 }
425}
426fn runtime_candidate_matches(
427 spec: &InstallSpec,
428 report: Option<&inspection::Report>,
429 observed: &Observations<'_>,
430) -> bool {
431 let Some(runtime) = spec.runtime_tool.as_ref() else {
432 return false;
433 };
434 let Some(binding) = report.and_then(|r| r.description.npm_binding.as_ref()) else {
435 return false;
436 };
437 matches!(observed.binaries.get(runtime), Some(BinaryObservation::Candidates { paths }) if paths.len() == 1 && paths[0] == binding.node)
440}