use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::path::PathBuf;
use serde::Serialize;
use crate::agent::{self, AgentResolution};
use crate::config::{ProjectSelection, UserConfig};
use crate::inventory::{self, InventoryWarningCode, SkillDelivery, SkillRecord, SourceInventory};
use crate::plugin::{self, PluginInventory, PluginResolution, PluginState};
use crate::source::{SourceConfig, SourceKind};
use crate::store::ApprovalRecord;
#[derive(Debug, Clone)]
pub struct ResolutionInput<'a> {
pub sources: &'a [SourceConfig],
pub inventories: Vec<SourceInventory>,
pub approvals: Vec<ApprovalRecord>,
}
#[derive(Debug, Clone)]
pub struct SourceScan {
pub source: SourceConfig,
pub inventory: Option<SourceInventory>,
pub error: Option<String>,
}
#[derive(Debug, Clone)]
pub struct LiveResolution {
pub scans: Vec<SourceScan>,
pub resolution: Resolution,
pub plugins: PluginResolution,
pub agents: AgentResolution,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ActiveSkillCause {
LocalSource,
TrustedSource,
Approval {
scope: String,
value: String,
},
CatalogSelection {
selector: String,
},
}
impl LiveResolution {
#[must_use]
pub(crate) fn degraded_sources(
&self,
audit_failures: &[crate::audit::ActiveAuditFailure],
) -> Vec<crate::materialize::DegradedSource> {
let mut degraded = self
.scans
.iter()
.filter(|scan| {
scan.error.is_some()
|| scan
.inventory
.as_ref()
.is_some_and(inventory_degrades_source_for_removal)
})
.map(|scan| crate::materialize::DegradedSource {
id: scan.source.id.clone(),
path: scan.source.path.clone(),
reason: scan
.error
.clone()
.unwrap_or_else(|| "inventory warnings make removals unsafe".to_owned()),
})
.collect::<Vec<_>>();
for failure in audit_failures {
let reason = format!(
"security audit failed for {}: {}",
failure.source_ref, failure.reason
);
if let Some(existing) = degraded
.iter_mut()
.find(|source| source.id == failure.source_id)
{
existing.reason = format!("{}; {reason}", existing.reason);
} else if let Some(scan) = self
.scans
.iter()
.find(|scan| scan.source.id == failure.source_id)
{
degraded.push(crate::materialize::DegradedSource {
id: failure.source_id.clone(),
path: scan.source.path.clone(),
reason,
});
}
}
degraded.sort_by(|left, right| left.id.cmp(&right.id));
degraded
}
}
#[derive(Debug, Clone)]
pub(crate) struct ResolutionWithPluginInventories {
pub(crate) live: LiveResolution,
plugin_inventories: Vec<PluginInventory>,
}
#[must_use]
pub(crate) fn plugin_inventories(
resolution: &ResolutionWithPluginInventories,
) -> Vec<SourceInventory> {
resolution
.live
.scans
.iter()
.zip(&resolution.plugin_inventories)
.map(|(scan, plugin_inventory)| {
plugin_inventory_as_source_inventory(&scan.source, plugin_inventory)
})
.collect()
}
#[must_use]
pub(crate) fn inventories_with_plugins(
resolution: &ResolutionWithPluginInventories,
) -> Vec<SourceInventory> {
resolution
.live
.scans
.iter()
.zip(&resolution.plugin_inventories)
.map(|(scan, plugin_inventory)| {
scan.inventory.clone().map_or_else(
|| plugin_inventory_as_source_inventory(&scan.source, plugin_inventory),
|mut inventory| {
inventory.plugins = plugin_inventory.plugins.clone();
inventory.plugin_warnings = plugin_inventory.warnings.clone();
inventory
},
)
})
.collect()
}
fn plugin_inventory_as_source_inventory(
source: &SourceConfig,
plugin_inventory: &PluginInventory,
) -> SourceInventory {
SourceInventory {
source_id: source.id.clone(),
skills: Vec::new(),
agents: Vec::new(),
plugins: plugin_inventory.plugins.clone(),
warnings: Vec::new(),
agent_warnings: Vec::new(),
plugin_warnings: plugin_inventory.warnings.clone(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Resolution {
pub active_skills: Vec<ResolvedSkill>,
pub pending_approval_skills: Vec<ResolvedSkill>,
pub unlinked_skills: Vec<UnlinkedSkill>,
pub blocked_skills: Vec<BlockedSkill>,
pub diagnostics: Vec<ResolutionDiagnostic>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResolvedSkill {
pub source_ref: String,
pub slot_name: String,
#[serde(skip)]
pub source_namespace: Option<String>,
pub id: Option<String>,
pub source_id: String,
pub source_kind: SourceKind,
pub source_priority: i32,
pub path: PathBuf,
pub delivery: SkillDelivery,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compatibility: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub binaries: Vec<crate::binary::BinaryRecord>,
pub local_override: bool,
#[serde(skip)]
pub requires: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct UnlinkedSkill {
pub skill: ResolvedSkill,
pub status: UnlinkedStatus,
pub reason: UnlinkedReason,
pub shadowed_by: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BlockedSkill {
pub skill: ResolvedSkill,
pub requirement: String,
pub reason: ClosureBlockReason,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ClosureBlockReason {
Missing,
PendingApproval,
ShadowedNotSatisfied,
SameNameBlocked,
Unlinked,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UnlinkedStatus {
Unlinked,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UnlinkedReason {
Shadowed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResolutionDiagnostic {
pub code: ResolutionDiagnosticCode,
pub message: String,
pub source_ref: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResolutionDiagnosticCode {
PendingApproval,
LocalOverride,
Shadowed,
RequiredExpanded,
CrossSourceRequire,
RequiredBlocked,
LegacyBareApproval,
AuditFailed,
BlockedWinnerAlternateAvailable,
UndeclaredProjectSkill,
}
impl ResolutionDiagnosticCode {
#[must_use]
pub const fn requires_review(self) -> bool {
matches!(
self,
Self::PendingApproval
| Self::CrossSourceRequire
| Self::RequiredBlocked
| Self::LegacyBareApproval
| Self::AuditFailed
| Self::UndeclaredProjectSkill
)
}
}
#[derive(Debug, Clone)]
struct Candidate {
skill: ResolvedSkill,
owners: Vec<String>,
trusted: bool,
requires: Vec<String>,
}
pub fn resolve_from_config(config: &UserConfig, approvals: Vec<ApprovalRecord>) -> LiveResolution {
resolve_from_config_with_plugin_inventories(config, approvals).live
}
pub(crate) fn active_skill_causes(
live: &LiveResolution,
active: &ResolvedSkill,
approvals: &[ApprovalRecord],
) -> Vec<ActiveSkillCause> {
let Some(scan) = live.scans.iter().find(|scan| {
scan.source.id == active.source_id
&& scan.inventory.as_ref().is_some_and(|inventory| {
inventory
.skills
.iter()
.any(|skill| skill.source_ref == active.source_ref)
})
}) else {
return Vec::new();
};
let Some(inventory) = scan.inventory.as_ref() else {
return Vec::new();
};
let Some(record) = inventory
.skills
.iter()
.find(|skill| skill.source_ref == active.source_ref)
else {
return Vec::new();
};
let candidate = Candidate {
skill: active.clone(),
owners: record.owners.clone(),
trusted: scan.source.trusted,
requires: record.requires.clone(),
};
if !is_approved(&candidate, approvals) {
return Vec::new();
}
let mut causes = Vec::new();
if candidate.skill.source_kind == SourceKind::Local {
causes.push(ActiveSkillCause::LocalSource);
}
if candidate.trusted {
causes.push(ActiveSkillCause::TrustedSource);
}
for approval in approvals {
let matches = approval_matches_skill(approval, &candidate)
|| approval_matches_source(approval, &candidate)
|| approval_matches_owner(approval, &candidate);
if matches {
causes.push(ActiveSkillCause::Approval {
scope: approval.scope.clone(),
value: approval.value.clone(),
});
}
}
if scan.source.kind == SourceKind::Catalog {
let mut selectors = BTreeSet::new();
for selector in &scan.source.selection {
let Some(root) = inventory
.skills
.iter()
.find(|skill| selection_ref_matches_skill(selector, skill, &scan.source.path))
else {
continue;
};
if catalog_selection_reaches(root, record, &inventory.skills) {
selectors.insert(root.slot_name.clone());
}
}
causes.extend(
selectors
.into_iter()
.map(|selector| ActiveSkillCause::CatalogSelection { selector }),
);
}
causes
}
pub(crate) fn resolve_from_config_with_plugin_inventories(
config: &UserConfig,
approvals: Vec<ApprovalRecord>,
) -> ResolutionWithPluginInventories {
resolve_from_config_with_plugin_inventories_with_source_errors(
config,
approvals,
&BTreeMap::new(),
)
}
pub(crate) fn resolve_from_config_with_plugin_inventories_with_source_errors(
config: &UserConfig,
approvals: Vec<ApprovalRecord>,
source_errors: &BTreeMap<String, String>,
) -> ResolutionWithPluginInventories {
let enabled = config
.sources
.iter()
.filter(|source| source.enabled)
.cloned()
.collect::<Vec<_>>();
let mut scans = Vec::with_capacity(enabled.len());
let mut plugin_inventories = Vec::with_capacity(enabled.len());
let mut inventories = Vec::new();
for source in &enabled {
let (plugin_inventory, scanned) = source_errors.get(&source.id).map_or_else(
|| scan_enabled_source(source),
|error| (PluginInventory::default(), Err(error.clone())),
);
match scanned {
Ok(mut inventory) => {
if source.kind == SourceKind::Catalog
&& let Some(selectors) = config
.project_selections
.as_ref()
.and_then(|declared| declared.get(&source.id))
{
scope_project_symlink_warnings(source, selectors, &mut inventory);
}
inventories.push(inventory.clone());
scans.push(SourceScan {
source: source.clone(),
inventory: Some(inventory),
error: None,
});
plugin_inventories.push(plugin_inventory);
}
Err(error) => {
inventories.push(plugin_inventory_as_source_inventory(
source,
&plugin_inventory,
));
scans.push(SourceScan {
source: source.clone(),
inventory: None,
error: Some(error),
});
plugin_inventories.push(plugin_inventory);
}
}
}
let mut plugins = if config.is_project_store() {
PluginResolution::default()
} else {
plugin::resolve_plugins(config, &inventories)
};
let mut effective_sources = enabled;
for resolved in &plugins.plugins {
if matches!(
resolved.state,
PluginState::Shadowed | PluginState::Declined
) {
continue;
}
for member in &resolved.members {
if !member.reference.starts_with("skill:") {
continue;
}
let Some(component_ref) = &member.resolved_ref else {
continue;
};
let Some((source_id, slot_name)) = component_ref.split_once(':') else {
continue;
};
if let Some(source) = effective_sources
.iter_mut()
.find(|source| source.id == source_id && source.kind == SourceKind::Catalog)
&& !source
.selection
.iter()
.any(|selected| selected == slot_name)
{
source.selection.push(slot_name.to_owned());
source.selection.sort();
}
}
}
let mut resolution = resolve(&ResolutionInput {
sources: &effective_sources,
inventories: inventories.clone(),
approvals: approvals.clone(),
});
if let Some(declared) = &config.project_selections {
restrict_to_declared_closure(&mut resolution, &config.sources, &inventories, declared);
}
let agents = agent::resolve_agents(&effective_sources, &inventories, &approvals);
plugin::apply_component_resolution(&mut plugins, &resolution, &agents, &BTreeSet::new());
ResolutionWithPluginInventories {
live: LiveResolution {
scans,
resolution,
plugins,
agents,
},
plugin_inventories,
}
}
fn project_catalog_references_for_inventory(
source: &SourceConfig,
declared: &ProjectSelection,
skills: &[SkillRecord],
) -> Vec<String> {
let prefix = format!("{}:", source.id);
declared
.skills
.iter()
.map(|reference| {
let lookup = reference.strip_prefix(&prefix).unwrap_or(reference);
if skills
.iter()
.any(|skill| selection_ref_matches_skill(lookup, skill, &source.path))
{
lookup.to_owned()
} else {
let scoped = crate::project::project_catalog_reference(
&source.id,
declared.path.as_deref(),
reference,
);
scoped.strip_prefix(&prefix).unwrap_or(&scoped).to_owned()
}
})
.collect()
}
fn scope_project_symlink_warnings(
source: &SourceConfig,
declared: &ProjectSelection,
inventory: &mut SourceInventory,
) {
let selectors = project_catalog_references_for_inventory(source, declared, &inventory.skills);
let mut queue = selectors
.iter()
.map(|reference| (reference.clone(), true))
.collect::<VecDeque<_>>();
let mut paths = BTreeSet::new();
while let Some((reference, explicit)) = queue.pop_front() {
let Some(skill) = inventory.skills.iter().find(|skill| {
if explicit {
selection_ref_matches_skill(&reference, skill, &source.path)
} else {
ref_matches_skill(&reference, skill)
}
}) else {
inventory.warnings.push(inventory::InventoryWarning {
code: InventoryWarningCode::UnreadablePath,
path: source.path.clone(),
message: format!(
"project-selected skill or requirement `{reference}` could not be inventoried"
),
});
return;
};
if paths.insert(skill.path.clone()) {
queue.extend(
skill
.requires
.iter()
.map(|reference| (reference.clone(), false)),
);
}
}
inventory.warnings.retain(|warning| {
warning.code != InventoryWarningCode::SkippedSymlink
|| paths
.iter()
.any(|path| warning.path.starts_with(path) || path.starts_with(&warning.path))
});
}
fn restrict_to_declared_closure(
resolution: &mut Resolution,
sources: &[SourceConfig],
inventories: &[SourceInventory],
declared: &BTreeMap<String, ProjectSelection>,
) {
let source_by_id = sources
.iter()
.filter(|source| source.enabled)
.map(|source| (source.id.as_str(), source))
.collect::<BTreeMap<_, _>>();
let closures = declared
.iter()
.filter_map(|(source_id, declared)| {
let source = source_by_id.get(source_id.as_str())?;
let skills = inventory_for(inventories, source_id)?;
(source.kind == SourceKind::Catalog).then(|| {
let selectors = project_catalog_references_for_inventory(source, declared, skills);
(
source_id.as_str(),
closure_for_selection(&selectors, skills, &source.path),
)
})
})
.collect::<BTreeMap<_, _>>();
let is_declared = |skill: &ResolvedSkill| {
if skill.source_kind == SourceKind::Local {
return true;
}
let (Some(source), Some(closure), Some(skills)) = (
source_by_id.get(skill.source_id.as_str()),
closures.get(skill.source_id.as_str()),
inventory_for(inventories, &skill.source_id),
) else {
return false;
};
skills
.iter()
.find(|record| record.source_ref == skill.source_ref)
.is_some_and(|record| crate::catalog::skill_is_selected(record, closure, &source.path))
};
let mut held_back = Vec::new();
for skills in [
&mut resolution.active_skills,
&mut resolution.pending_approval_skills,
] {
skills.retain(|skill| {
let keep = is_declared(skill);
if !keep {
held_back.push(skill.source_ref.clone());
}
keep
});
}
held_back.sort();
held_back.dedup();
if held_back.is_empty() {
return;
}
resolution.diagnostics.retain(|diagnostic| {
diagnostic.code != ResolutionDiagnosticCode::PendingApproval
|| diagnostic
.source_ref
.as_ref()
.is_none_or(|source_ref| held_back.binary_search(source_ref).is_err())
});
for source_ref in held_back {
resolution.diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::UndeclaredProjectSkill,
message: format!(
"skill `{source_ref}` is outside the project's declared selections and their required closure; project scope does not deliver it"
),
source_ref: Some(source_ref),
});
}
resolution.diagnostics.sort_by(|left, right| {
diagnostic_code_name(left.code)
.cmp(diagnostic_code_name(right.code))
.then_with(|| left.source_ref.cmp(&right.source_ref))
});
}
fn scan_enabled_source(
source: &SourceConfig,
) -> (PluginInventory, Result<SourceInventory, String>) {
if !source.path.exists() {
return (
PluginInventory::default(),
Err("source path does not exist".to_owned()),
);
}
let source_root =
match crate::source::scoped_source_root(&source.path, source.subpath.as_deref()) {
Ok(root) => root,
Err(error) => return (PluginInventory::default(), Err(error.to_string())),
};
let plugin_inventory = plugin::scan_source_plugins(&source.id, &source_root);
let inventory = inventory::scan_configured_source_with_plugin_inventory(
source,
&source_root,
plugin_inventory.clone(),
)
.map_err(|error| error.to_string());
(plugin_inventory, inventory)
}
#[must_use]
pub fn inventory_degrades_source_for_removal(inventory: &SourceInventory) -> bool {
inventory.warnings.iter().any(|warning| {
matches!(
warning.code,
InventoryWarningCode::UnreadablePath
| InventoryWarningCode::InvalidSlotName
| InventoryWarningCode::SkippedSymlink
| InventoryWarningCode::InvalidDelivery
| InventoryWarningCode::InvalidBinaryDeclaration
)
})
}
#[must_use]
pub fn resolve(input: &ResolutionInput) -> Resolution {
let source_by_id = input
.sources
.iter()
.filter(|source| source.enabled)
.map(|source| (source.id.as_str(), source))
.collect::<BTreeMap<_, _>>();
let effective_selection = expand_catalog_selections(&source_by_id, &input.inventories);
let mut candidates = Vec::new();
for inventory in &input.inventories {
let Some(source) = source_by_id.get(inventory.source_id.as_str()) else {
continue;
};
let selection = effective_selection
.get(source.id.as_str())
.map_or(source.selection.as_slice(), Vec::as_slice);
let has_generated_delivery = inventory
.skills
.iter()
.any(|skill| matches!(skill.delivery, SkillDelivery::Generated { .. }));
let source_commit = (source.kind != SourceKind::Local && has_generated_delivery)
.then(|| crate::git::rev_parse_head(&source.path).ok())
.flatten();
for skill in &inventory.skills {
if source.kind == SourceKind::Catalog
&& !crate::catalog::skill_is_selected(skill, selection, &source.path)
{
continue;
}
let mut delivery = skill.delivery.clone();
let stable_ref = skill
.id
.as_ref()
.map(|id| format!("{}:{id}", skill.source_id))
.unwrap_or_else(|| skill.source_ref.clone());
delivery.bind_generated_approvals(
&skill.source_ref,
&stable_ref,
source_commit.clone(),
&input.approvals,
);
candidates.push(Candidate {
skill: ResolvedSkill {
source_ref: skill.source_ref.clone(),
slot_name: materialized_slot_name(
source.namespace.as_deref(),
&skill.slot_name,
),
source_namespace: source.namespace.clone(),
id: skill.id.clone(),
source_id: source.id.clone(),
source_kind: source.kind,
source_priority: source.priority,
path: skill.path.clone(),
delivery,
compatibility: skill.compatibility.clone(),
binaries: skill.binaries.clone(),
local_override: false,
requires: skill.requires.clone(),
},
owners: skill.owners.clone(),
trusted: source.trusted,
requires: skill.requires.clone(),
});
}
}
let requires_by_ref: BTreeMap<String, Vec<String>> = candidates
.iter()
.filter(|candidate| !candidate.requires.is_empty())
.map(|candidate| {
(
candidate.skill.source_ref.clone(),
candidate.requires.clone(),
)
})
.collect();
candidates.sort_by(|left, right| {
left.skill
.source_priority
.cmp(&right.skill.source_priority)
.then_with(|| left.skill.source_id.cmp(&right.skill.source_id))
.then_with(|| left.skill.source_ref.cmp(&right.skill.source_ref))
});
let mut groups: BTreeMap<String, Vec<Candidate>> = BTreeMap::new();
for candidate in candidates {
let slot_name = candidate.skill.slot_name.clone();
groups.entry(slot_name).or_default().push(candidate);
}
let mut active_skills = Vec::new();
let mut pending_approval_skills = Vec::new();
let mut unlinked_skills = Vec::new();
let mut diagnostics = Vec::new();
let mut approved_alternates: BTreeMap<String, Vec<String>> = BTreeMap::new();
for group in groups.into_values() {
let Some(winner_index) = group
.iter()
.position(|candidate| is_approved(candidate, &input.approvals))
else {
for candidate in &group {
pending_approval_skills.push(candidate.skill.clone());
if let Some((legacy, suggested)) = legacy_bare_approval(candidate, &input.approvals)
{
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::LegacyBareApproval,
message: format!(
"legacy approval `{}` found for `{}`; re-approve as `{}`",
legacy, candidate.skill.source_ref, suggested
),
source_ref: Some(candidate.skill.source_ref.clone()),
});
}
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::PendingApproval,
message: format!("skill `{}` is pending approval", candidate.skill.source_ref),
source_ref: Some(candidate.skill.source_ref.clone()),
});
}
continue;
};
for candidate in group.iter().take(winner_index) {
pending_approval_skills.push(candidate.skill.clone());
if let Some((legacy, suggested)) = legacy_bare_approval(candidate, &input.approvals) {
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::LegacyBareApproval,
message: format!(
"legacy approval `{}` found for `{}`; re-approve as `{}`",
legacy, candidate.skill.source_ref, suggested
),
source_ref: Some(candidate.skill.source_ref.clone()),
});
}
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::PendingApproval,
message: format!("skill `{}` is pending approval", candidate.skill.source_ref),
source_ref: Some(candidate.skill.source_ref.clone()),
});
}
let mut winner = group[winner_index].skill.clone();
winner.local_override = winner.source_kind == SourceKind::Local && group.len() > 1;
if winner.local_override {
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::LocalOverride,
message: format!(
"local skill `{}` overrides another source",
winner.source_ref
),
source_ref: Some(winner.source_ref.clone()),
});
}
for candidate in group.iter().skip(winner_index + 1) {
unlinked_skills.push(UnlinkedSkill {
skill: candidate.skill.clone(),
status: UnlinkedStatus::Unlinked,
reason: UnlinkedReason::Shadowed,
shadowed_by: winner.source_ref.clone(),
});
let message = if candidate.skill.source_priority == winner.source_priority {
format!(
"skill `{}` is unlinked because `{}` wins the same slot at equal source priority (the tie was broken by source id) — set an explicit `dalo source priority` to choose deliberately",
candidate.skill.source_ref, winner.source_ref
)
} else {
format!(
"skill `{}` is unlinked because `{}` wins the same slot",
candidate.skill.source_ref, winner.source_ref
)
};
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::Shadowed,
message,
source_ref: Some(candidate.skill.source_ref.clone()),
});
if is_approved(candidate, &input.approvals) {
approved_alternates
.entry(winner.source_ref.clone())
.or_default()
.push(candidate.skill.source_ref.clone());
}
}
active_skills.push(winner);
}
let (mut blocked_skills, closure_diagnostics) = required_closure_preflight(
&mut active_skills,
&pending_approval_skills,
&requires_by_ref,
&input.inventories,
);
diagnostics.extend(closure_diagnostics);
for blocked in &blocked_skills {
if let Some(alternate) = approved_alternates
.get(&blocked.skill.source_ref)
.and_then(|refs| refs.first())
{
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::BlockedWinnerAlternateAvailable,
message: format!(
"slot `{}` has no active skill: winner `{}` is blocked, and the approved alternate `{}` is shadowed behind it — give the alternate higher precedence with a lower `dalo source priority` value than the winner to select it, or resolve the blocking requirement(s) in the winner's closure",
blocked.skill.slot_name, blocked.skill.source_ref, alternate
),
source_ref: Some(alternate.clone()),
});
}
}
active_skills.sort_by(|left, right| {
left.slot_name
.cmp(&right.slot_name)
.then_with(|| left.source_ref.cmp(&right.source_ref))
});
pending_approval_skills.sort_by(|left, right| {
left.slot_name
.cmp(&right.slot_name)
.then_with(|| left.source_ref.cmp(&right.source_ref))
});
unlinked_skills.sort_by(|left, right| {
left.skill
.slot_name
.cmp(&right.skill.slot_name)
.then_with(|| left.skill.source_ref.cmp(&right.skill.source_ref))
});
for (source_id, effective) in &effective_selection {
let Some(source) = source_by_id.get(source_id.as_str()) else {
continue;
};
for reference in effective {
if !source
.selection
.iter()
.any(|selected| selected == reference)
{
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::RequiredExpanded,
message: format!(
"`{reference}` was pulled into catalog `{source_id}` by a requires closure"
),
source_ref: Some(format!("{source_id}:{reference}")),
});
}
}
}
diagnostics.sort_by(|left, right| {
diagnostic_code_name(left.code)
.cmp(diagnostic_code_name(right.code))
.then_with(|| left.source_ref.cmp(&right.source_ref))
});
blocked_skills.sort_by(|left, right| {
left.skill
.slot_name
.cmp(&right.skill.slot_name)
.then_with(|| left.skill.source_ref.cmp(&right.skill.source_ref))
});
Resolution {
active_skills,
pending_approval_skills,
unlinked_skills,
blocked_skills,
diagnostics,
}
}
#[must_use]
pub fn materialized_slot_name(namespace: Option<&str>, slot_name: &str) -> String {
namespace.map_or_else(
|| slot_name.to_owned(),
|namespace| format!("{namespace}__{slot_name}"),
)
}
pub fn degrade_audit_failures(
resolution: &mut Resolution,
failures: &[crate::audit::ActiveAuditFailure],
) {
if failures.is_empty() {
return;
}
let failure_by_ref = failures
.iter()
.map(|failure| {
let logical_ref = failure
.source_ref
.rsplit_once('@')
.map_or(failure.source_ref.as_str(), |(logical_ref, _)| logical_ref);
(logical_ref, failure.reason.as_str())
})
.collect::<BTreeMap<_, _>>();
let mut unavailable = Vec::new();
let mut active = Vec::new();
for skill in std::mem::take(&mut resolution.active_skills) {
if let Some(reason) = failure_by_ref.get(skill.source_ref.as_str()) {
resolution.diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::AuditFailed,
message: format!("security audit failed for `{}`: {reason}", skill.source_ref),
source_ref: Some(skill.source_ref.clone()),
});
unavailable.push(skill);
} else {
active.push(skill);
}
}
resolution.active_skills = active;
while let Some((index, requirement)) =
resolution
.active_skills
.iter()
.enumerate()
.find_map(|(index, dependent)| {
dependent.requires.iter().find_map(|requirement| {
unavailable
.iter()
.any(|blocked| {
blocked.source_id == dependent.source_id
&& requirement_matches_resolved(requirement, dependent, blocked)
})
.then(|| (index, requirement.clone()))
})
})
{
let skill = resolution.active_skills.remove(index);
resolution.diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::RequiredBlocked,
message: format!(
"skill `{}` is blocked: requirement `{requirement}` is unlinked",
skill.source_ref
),
source_ref: Some(skill.source_ref.clone()),
});
resolution.blocked_skills.push(BlockedSkill {
skill: skill.clone(),
requirement,
reason: ClosureBlockReason::Unlinked,
});
unavailable.push(skill);
}
resolution.active_skills.sort_by(|left, right| {
left.slot_name
.cmp(&right.slot_name)
.then_with(|| left.source_ref.cmp(&right.source_ref))
});
resolution
.blocked_skills
.sort_by(|left, right| left.skill.source_ref.cmp(&right.skill.source_ref));
resolution.diagnostics.sort_by(|left, right| {
diagnostic_code_name(left.code)
.cmp(diagnostic_code_name(right.code))
.then_with(|| left.source_ref.cmp(&right.source_ref))
});
}
fn requirement_matches_resolved(
requirement: &str,
dependent: &ResolvedSkill,
candidate: &ResolvedSkill,
) -> bool {
candidate.slot_name
== materialized_slot_name(dependent.source_namespace.as_deref(), requirement)
|| candidate.source_ref == requirement
|| candidate.id.as_deref() == Some(requirement)
}
fn is_approved(candidate: &Candidate, approvals: &[ApprovalRecord]) -> bool {
if candidate.skill.source_kind == SourceKind::Local || candidate.trusted {
return true;
}
approvals.iter().any(|approval| {
approval_matches_skill(approval, candidate)
|| approval_matches_source(approval, candidate)
|| approval_matches_owner(approval, candidate)
})
}
fn legacy_bare_approval(
candidate: &Candidate,
approvals: &[ApprovalRecord],
) -> Option<(String, String)> {
approvals
.iter()
.filter(|approval| approval.scope == "skill" && !approval.value.contains(':'))
.find_map(|approval| {
if approval.value == candidate.skill.slot_name {
return Some((approval.value.clone(), candidate.skill.source_ref.clone()));
}
let id = candidate.skill.id.as_ref()?;
(approval.value == *id).then(|| {
(
approval.value.clone(),
format!("{}:{}", candidate.skill.source_id, id),
)
})
})
}
fn approval_matches_skill(approval: &ApprovalRecord, candidate: &Candidate) -> bool {
if approval.scope != "skill" {
return false;
}
if approval.value == candidate.skill.source_ref {
return true;
}
let Some((source_id, stable_id)) = approval.value.split_once(':') else {
return false;
};
source_id == candidate.skill.source_id
&& candidate
.skill
.id
.as_deref()
.is_some_and(|id| id == stable_id)
}
fn approval_matches_source(approval: &ApprovalRecord, candidate: &Candidate) -> bool {
approval.scope == "source" && approval.value == candidate.skill.source_id
}
fn approval_matches_owner(approval: &ApprovalRecord, candidate: &Candidate) -> bool {
if !matches!(approval.scope.as_str(), "author" | "org") {
return false;
}
let Some((source_id, owner)) = approval.value.split_once(':') else {
return false;
};
source_id == candidate.skill.source_id
&& candidate
.owners
.iter()
.any(|candidate_owner| candidate_owner == owner)
}
#[must_use]
pub fn diagnostic_code_name(code: ResolutionDiagnosticCode) -> &'static str {
match code {
ResolutionDiagnosticCode::PendingApproval => "pending_approval",
ResolutionDiagnosticCode::LocalOverride => "local_override",
ResolutionDiagnosticCode::Shadowed => "shadowed",
ResolutionDiagnosticCode::RequiredExpanded => "required_expanded",
ResolutionDiagnosticCode::CrossSourceRequire => "cross_source_require",
ResolutionDiagnosticCode::RequiredBlocked => "required_blocked",
ResolutionDiagnosticCode::LegacyBareApproval => "legacy_bare_approval",
ResolutionDiagnosticCode::AuditFailed => "audit_failed",
ResolutionDiagnosticCode::BlockedWinnerAlternateAvailable => {
"blocked_winner_alternate_available"
}
ResolutionDiagnosticCode::UndeclaredProjectSkill => "undeclared_project_skill",
}
}
impl std::fmt::Display for ResolutionDiagnosticCode {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(diagnostic_code_name(*self))
}
}
#[must_use]
pub fn closure_block_reason_name(reason: ClosureBlockReason) -> &'static str {
match reason {
ClosureBlockReason::Missing => "missing",
ClosureBlockReason::PendingApproval => "pending approval",
ClosureBlockReason::ShadowedNotSatisfied => "shadowed but not satisfied",
ClosureBlockReason::SameNameBlocked => "blocked by a same-name target entry",
ClosureBlockReason::Unlinked => "unlinked",
}
}
fn ref_matches_skill(reference: &str, skill: &SkillRecord) -> bool {
skill.slot_name == reference
|| skill.source_ref == reference
|| skill.id.as_deref() == Some(reference)
}
fn inventory_for<'a>(
inventories: &'a [SourceInventory],
source_id: &str,
) -> Option<&'a [SkillRecord]> {
inventories
.iter()
.find(|inventory| inventory.source_id == source_id)
.map(|inventory| inventory.skills.as_slice())
}
pub(crate) fn expand_catalog_selections(
source_by_id: &BTreeMap<&str, &SourceConfig>,
inventories: &[SourceInventory],
) -> BTreeMap<String, Vec<String>> {
let mut expanded = BTreeMap::new();
for inventory in inventories {
let Some(source) = source_by_id.get(inventory.source_id.as_str()) else {
continue;
};
if source.kind != SourceKind::Catalog {
continue;
}
expanded.insert(
source.id.clone(),
closure_for_selection(&source.selection, &inventory.skills, &source.path),
);
}
expanded
}
fn closure_for_selection(
selection: &[String],
skills: &[SkillRecord],
source_root: &std::path::Path,
) -> Vec<String> {
let mut result: Vec<String> = selection.to_vec();
let mut seen: BTreeSet<String> = selection.iter().cloned().collect();
let mut queue: VecDeque<String> = selection.iter().cloned().collect();
while let Some(reference) = queue.pop_front() {
let Some(skill) = skills
.iter()
.find(|skill| selection_ref_matches_skill(&reference, skill, source_root))
else {
continue;
};
for requirement in &skill.requires {
let Some(required) = skills
.iter()
.find(|skill| ref_matches_skill(requirement, skill))
else {
continue;
};
let canonical = required.slot_name.clone();
if seen.insert(canonical.clone()) {
result.push(canonical.clone());
queue.push_back(canonical);
}
}
}
result
}
fn catalog_selection_reaches(
root: &SkillRecord,
target: &SkillRecord,
skills: &[SkillRecord],
) -> bool {
let mut queue = VecDeque::from([root]);
let mut seen = BTreeSet::new();
while let Some(skill) = queue.pop_front() {
if !seen.insert(skill.source_ref.as_str()) {
continue;
}
if skill.source_ref == target.source_ref {
return true;
}
for requirement in &skill.requires {
if let Some(required) = skills
.iter()
.find(|candidate| ref_matches_skill(requirement, candidate))
{
queue.push_back(required);
}
}
}
false
}
fn selection_ref_matches_skill(
reference: &str,
skill: &SkillRecord,
source_root: &std::path::Path,
) -> bool {
ref_matches_skill(reference, skill)
|| skill
.path
.strip_prefix(source_root)
.is_ok_and(|path| path.to_string_lossy() == reference)
}
enum RequirementStatus {
Satisfied,
Block(ClosureBlockReason),
}
fn requirement_status(
requirement: &str,
required: &SkillRecord,
source_namespace: Option<&str>,
active: &[ResolvedSkill],
pending_refs: &BTreeSet<&str>,
) -> RequirementStatus {
let required_slot_name = materialized_slot_name(source_namespace, &required.slot_name);
let winner = active
.iter()
.find(|skill| skill.slot_name == required_slot_name);
match winner {
Some(skill) if skill.source_ref == required.source_ref => RequirementStatus::Satisfied,
Some(skill) if skill.id.is_some() && skill.id == required.id => {
RequirementStatus::Satisfied
}
Some(_) => {
if requirement == required.source_ref || required.id.as_deref() == Some(requirement) {
RequirementStatus::Block(ClosureBlockReason::ShadowedNotSatisfied)
} else {
RequirementStatus::Satisfied
}
}
None if pending_refs.contains(required.source_ref.as_str()) => {
RequirementStatus::Block(ClosureBlockReason::PendingApproval)
}
None => RequirementStatus::Block(ClosureBlockReason::Unlinked),
}
}
fn find_blocked(
active: &[ResolvedSkill],
pending_refs: &BTreeSet<&str>,
requires_by_ref: &BTreeMap<String, Vec<String>>,
inventories: &[SourceInventory],
) -> Option<(usize, BlockedSkill)> {
for (index, dependent) in active.iter().enumerate() {
let Some(requires) = requires_by_ref.get(&dependent.source_ref) else {
continue;
};
for requirement in requires {
let same_source = inventory_for(inventories, &dependent.source_id).and_then(|skills| {
skills
.iter()
.find(|skill| ref_matches_skill(requirement, skill))
});
let Some(required) = same_source else {
let exists_elsewhere = inventories.iter().any(|inventory| {
inventory.source_id != dependent.source_id
&& inventory
.skills
.iter()
.any(|skill| ref_matches_skill(requirement, skill))
});
if exists_elsewhere {
continue;
}
return Some((
index,
BlockedSkill {
skill: dependent.clone(),
requirement: requirement.clone(),
reason: ClosureBlockReason::Missing,
},
));
};
if let RequirementStatus::Block(reason) = requirement_status(
requirement,
required,
dependent.source_namespace.as_deref(),
active,
pending_refs,
) {
return Some((
index,
BlockedSkill {
skill: dependent.clone(),
requirement: requirement.clone(),
reason,
},
));
}
}
}
None
}
fn required_closure_preflight(
active: &mut Vec<ResolvedSkill>,
pending: &[ResolvedSkill],
requires_by_ref: &BTreeMap<String, Vec<String>>,
inventories: &[SourceInventory],
) -> (Vec<BlockedSkill>, Vec<ResolutionDiagnostic>) {
let mut blocked = Vec::new();
let mut diagnostics = Vec::new();
let pending_refs: BTreeSet<&str> = pending
.iter()
.map(|skill| skill.source_ref.as_str())
.collect();
while let Some((index, block)) =
find_blocked(active, &pending_refs, requires_by_ref, inventories)
{
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::RequiredBlocked,
message: format!(
"skill `{}` is blocked: requirement `{}` is {}",
block.skill.source_ref,
block.requirement,
closure_block_reason_name(block.reason)
),
source_ref: Some(block.skill.source_ref.clone()),
});
active.remove(index);
blocked.push(block);
}
for dependent in active.iter() {
let Some(requires) = requires_by_ref.get(&dependent.source_ref) else {
continue;
};
for requirement in requires {
let same_source =
inventory_for(inventories, &dependent.source_id).is_some_and(|skills| {
skills
.iter()
.any(|skill| ref_matches_skill(requirement, skill))
});
if same_source {
continue;
}
let cross_source = inventories.iter().any(|inventory| {
inventory.source_id != dependent.source_id
&& inventory
.skills
.iter()
.any(|skill| ref_matches_skill(requirement, skill))
});
if cross_source {
diagnostics.push(ResolutionDiagnostic {
code: ResolutionDiagnosticCode::CrossSourceRequire,
message: format!(
"skill `{}` requires `{}` from another source; reported, not installed",
dependent.source_ref, requirement
),
source_ref: Some(dependent.source_ref.clone()),
});
}
}
}
(blocked, diagnostics)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::inventory::{InventoryWarning, InventoryWarningCode, SkillRecord, SourceInventory};
use proptest::prelude::*;
#[test]
fn diagnostic_review_classification_should_separate_information_from_action() {
for code in [
ResolutionDiagnosticCode::LocalOverride,
ResolutionDiagnosticCode::Shadowed,
ResolutionDiagnosticCode::RequiredExpanded,
] {
assert!(!code.requires_review());
}
for code in [
ResolutionDiagnosticCode::PendingApproval,
ResolutionDiagnosticCode::CrossSourceRequire,
ResolutionDiagnosticCode::RequiredBlocked,
ResolutionDiagnosticCode::LegacyBareApproval,
ResolutionDiagnosticCode::AuditFailed,
ResolutionDiagnosticCode::UndeclaredProjectSkill,
] {
assert!(code.requires_review());
}
}
#[test]
fn project_resolution_holds_back_everything_outside_the_declared_closure() {
let sources = vec![
source("local", SourceKind::Local, 0),
catalog("shared", 1, &["review", "extra"]),
{
let mut other = catalog("other", 2, &["tool"]);
other.trusted = false;
other
},
];
let inventories = vec![
inventory("local", vec![skill("local", "mine")]),
inventory(
"shared",
vec![
skill_req("shared", "review", &["helper"]),
skill("shared", "helper"),
skill("shared", "extra"),
],
),
inventory("other", vec![skill("other", "tool")]),
];
let mut resolution = resolve_with(sources.clone(), inventories.clone(), Vec::new());
assert!(
resolution
.pending_approval_skills
.iter()
.any(|skill| skill.source_ref == "other:tool")
);
let declared = BTreeMap::from([(
"shared".to_owned(),
ProjectSelection {
skills: vec!["review".to_owned()],
path: None,
},
)]);
restrict_to_declared_closure(&mut resolution, &sources, &inventories, &declared);
let active = resolution
.active_skills
.iter()
.map(|skill| skill.source_ref.as_str())
.collect::<Vec<_>>();
assert_eq!(active, ["shared:helper", "local:mine", "shared:review"]);
assert!(resolution.pending_approval_skills.is_empty());
let held_back = resolution
.diagnostics
.iter()
.filter(|diagnostic| {
diagnostic.code == ResolutionDiagnosticCode::UndeclaredProjectSkill
})
.filter_map(|diagnostic| diagnostic.source_ref.as_deref())
.collect::<Vec<_>>();
assert_eq!(held_back, ["other:tool", "shared:extra"]);
assert!(
!resolution
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == ResolutionDiagnosticCode::PendingApproval),
"a held-back skill is not offered for approval"
);
let mut resolution = resolve_with(sources.clone(), inventories.clone(), Vec::new());
restrict_to_declared_closure(&mut resolution, &sources, &inventories, &BTreeMap::new());
let active = resolution
.active_skills
.iter()
.map(|skill| skill.source_ref.as_str())
.collect::<Vec<_>>();
assert_eq!(active, ["local:mine"]);
}
#[test]
fn audit_failure_should_remove_the_skill_and_transitive_dependents() {
let mut resolution = resolve_with(
vec![source("local", SourceKind::Local, 0)],
vec![inventory(
"local",
vec![
skill_req("local", "alpha", &["beta"]),
skill("local", "beta"),
],
)],
Vec::new(),
);
degrade_audit_failures(
&mut resolution,
&[crate::audit::ActiveAuditFailure {
source_ref: "local:beta".to_owned(),
source_id: "local".to_owned(),
reason: "I/O error: permission denied".to_owned(),
}],
);
assert!(resolution.active_skills.is_empty());
assert_eq!(resolution.blocked_skills.len(), 1);
assert_eq!(resolution.blocked_skills[0].skill.source_ref, "local:alpha");
assert_eq!(resolution.blocked_skills[0].requirement, "beta");
assert!(resolution.diagnostics.iter().any(|diagnostic| {
diagnostic.code == ResolutionDiagnosticCode::AuditFailed
&& diagnostic.source_ref.as_deref() == Some("local:beta")
}));
}
#[test]
fn audit_failure_should_remove_namespaced_dependents() {
let mut company = source("company", SourceKind::Team, 10);
company.namespace = Some("company".to_owned());
let mut resolution = resolve_with(
vec![company],
vec![inventory(
"company",
vec![
skill_req("company", "alpha", &["beta"]),
skill("company", "beta"),
],
)],
vec![approval("source", "company")],
);
degrade_audit_failures(
&mut resolution,
&[crate::audit::ActiveAuditFailure {
source_ref: "company:beta".to_owned(),
source_id: "company".to_owned(),
reason: "I/O error: permission denied".to_owned(),
}],
);
assert!(resolution.active_skills.is_empty());
assert_eq!(resolution.blocked_skills.len(), 1);
assert_eq!(
resolution.blocked_skills[0].skill.source_ref,
"company:alpha"
);
}
#[test]
fn provider_audit_failure_should_remove_the_logical_skill() {
let mut resolution = resolve_with(
vec![source("local", SourceKind::Local, 0)],
vec![inventory("local", vec![skill("local", "review")])],
Vec::new(),
);
degrade_audit_failures(
&mut resolution,
&[crate::audit::ActiveAuditFailure {
source_ref: "local:review@codex".to_owned(),
source_id: "local".to_owned(),
reason: "provider `codex`: permission denied".to_owned(),
}],
);
assert!(resolution.active_skills.is_empty());
assert!(resolution.diagnostics.iter().any(|diagnostic| {
diagnostic.code == ResolutionDiagnosticCode::AuditFailed
&& diagnostic.source_ref.as_deref() == Some("local:review")
&& diagnostic.message.contains("provider `codex`")
}));
}
#[test]
fn inventory_degrades_source_for_subtree_unreadable_warning() {
let inventory = SourceInventory {
source_id: "company".to_owned(),
skills: vec![skill("company", "review")],
agents: Vec::new(),
plugins: Vec::new(),
warnings: vec![InventoryWarning {
code: InventoryWarningCode::UnreadablePath,
path: PathBuf::from("/repo/skills/private"),
message: "permission denied".to_owned(),
}],
agent_warnings: Vec::new(),
plugin_warnings: Vec::new(),
};
assert!(inventory_degrades_source_for_removal(&inventory));
}
#[test]
fn live_resolution_should_merge_inventory_and_audit_degradation_per_source() {
let source_config = source("local", SourceKind::Local, 0);
let live = LiveResolution {
scans: vec![SourceScan {
source: source_config,
inventory: Some(SourceInventory {
source_id: "local".to_owned(),
skills: vec![skill("local", "review")],
agents: Vec::new(),
plugins: Vec::new(),
warnings: vec![InventoryWarning {
code: InventoryWarningCode::UnreadablePath,
path: PathBuf::from("/tmp/local/skills/private/SKILL.md"),
message: "permission denied".to_owned(),
}],
agent_warnings: Vec::new(),
plugin_warnings: Vec::new(),
}),
error: None,
}],
resolution: resolve_with(
vec![source("local", SourceKind::Local, 0)],
vec![inventory("local", vec![skill("local", "review")])],
Vec::new(),
),
plugins: PluginResolution::default(),
agents: AgentResolution::default(),
};
let failures = vec![crate::audit::ActiveAuditFailure {
source_ref: "local:alpha".to_owned(),
source_id: "local".to_owned(),
reason: "first failure".to_owned(),
}];
let degraded = live.degraded_sources(&failures);
assert_eq!(degraded.len(), 1);
assert!(degraded[0].reason.contains("inventory warnings"));
assert!(degraded[0].reason.contains("local:alpha"));
}
#[test]
fn plugin_inventory_projection_keeps_valid_plugins_when_full_scan_is_unavailable() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let package = temp.path().join("plugins/quality");
std::fs::create_dir_all(&package).expect("plugin directory should be created");
std::fs::write(
package.join(crate::plugin::PLUGIN_FILE),
"schema_version = 1\n[plugin]\nname = \"quality\"\ndescription = \"Quality policy\"\n",
)
.expect("plugin manifest should be written");
let mut source = source("local", SourceKind::Local, 0);
source.path = temp.path().to_path_buf();
let plugin_inventory = crate::plugin::scan_source_plugins("local", temp.path());
let scans = vec![SourceScan {
source: source.clone(),
inventory: None,
error: Some("skill inventory unavailable".to_owned()),
}];
let resolution = ResolutionWithPluginInventories {
live: LiveResolution {
scans,
resolution: resolve_with(
vec![source.clone()],
vec![plugin_inventory_as_source_inventory(
&source,
&plugin_inventory,
)],
Vec::new(),
),
plugins: PluginResolution::default(),
agents: AgentResolution::default(),
},
plugin_inventories: vec![plugin_inventory],
};
let inventories = plugin_inventories(&resolution);
let reconciliation_inventories = inventories_with_plugins(&resolution);
assert_eq!(inventories.len(), 1);
assert_eq!(inventories[0].plugins.len(), 1);
assert_eq!(inventories[0].plugins[0].source_ref, "local:quality");
assert_eq!(reconciliation_inventories.len(), 1);
assert_eq!(reconciliation_inventories[0].plugins.len(), 1);
assert_eq!(
reconciliation_inventories[0].plugins[0].source_ref,
"local:quality"
);
}
#[test]
fn source_scan_keeps_its_released_constructible_shape() {
let scan = SourceScan {
source: source("local", SourceKind::Local, 0),
inventory: None,
error: Some("source unavailable".to_owned()),
};
assert!(scan.inventory.is_none());
assert_eq!(scan.error.as_deref(), Some("source unavailable"));
}
#[test]
fn inventory_degrades_source_for_invalidated_slot_name() {
let inventory = SourceInventory {
source_id: "company".to_owned(),
skills: Vec::new(),
agents: Vec::new(),
plugins: Vec::new(),
warnings: vec![InventoryWarning {
code: InventoryWarningCode::InvalidSlotName,
path: PathBuf::from("/repo/skills/Review/SKILL.md"),
message: "folder name `Review` is not a valid slot name".to_owned(),
}],
agent_warnings: Vec::new(),
plugin_warnings: Vec::new(),
};
assert!(inventory_degrades_source_for_removal(&inventory));
}
#[test]
fn resolve_should_pick_lower_priority_skill_for_same_slot() {
let resolution = resolve_with(
vec![
source("team-a", SourceKind::Team, 10),
source("team-b", SourceKind::Team, 20),
],
vec![
inventory("team-a", vec![skill("team-a", "copy-editing")]),
inventory("team-b", vec![skill("team-b", "copy-editing")]),
],
vec![approval("source", "team-a"), approval("source", "team-b")],
);
assert_eq!(
resolution.active_skills[0].source_ref,
"team-a:copy-editing"
);
}
#[test]
fn resolve_should_keep_same_named_skills_from_namespaced_sources() {
let mut company = source("company", SourceKind::Team, 10);
company.namespace = Some("company".to_owned());
let mut acme = source("acme", SourceKind::Team, 20);
acme.namespace = Some("acme".to_owned());
let resolution = resolve_with(
vec![company, acme],
vec![
inventory("company", vec![skill("company", "review")]),
inventory("acme", vec![skill("acme", "review")]),
],
vec![approval("source", "company"), approval("source", "acme")],
);
assert_eq!(
active_slots(&resolution),
vec!["acme__review", "company__review"]
);
assert!(resolution.unlinked_skills.is_empty());
assert_eq!(resolution.active_skills[0].source_ref, "acme:review");
assert_eq!(resolution.active_skills[1].source_ref, "company:review");
}
#[test]
fn resolve_should_shadow_a_literal_materialized_name_by_source_priority() {
let mut company = source("company", SourceKind::Team, 10);
company.namespace = Some("company".to_owned());
let public = source("public", SourceKind::Team, 20);
let resolution = resolve_with(
vec![company, public],
vec![
inventory("company", vec![skill("company", "review")]),
inventory("public", vec![skill("public", "company__review")]),
],
vec![approval("source", "company"), approval("source", "public")],
);
assert_eq!(active_slots(&resolution), vec!["company__review"]);
assert_eq!(resolution.active_skills[0].source_ref, "company:review");
assert_eq!(resolution.unlinked_skills.len(), 1);
assert_eq!(
resolution.unlinked_skills[0].skill.source_ref,
"public:company__review"
);
assert_eq!(resolution.unlinked_skills[0].shadowed_by, "company:review");
}
#[test]
fn resolve_should_keep_local_override_for_a_materialized_name_collision() {
let mut company = source("company", SourceKind::Team, 10);
company.namespace = Some("company".to_owned());
let resolution = resolve_with(
vec![source("local", SourceKind::Local, 0), company],
vec![
inventory("local", vec![skill("local", "company__review")]),
inventory("company", vec![skill("company", "review")]),
],
vec![approval("source", "company")],
);
assert_eq!(active_slots(&resolution), vec!["company__review"]);
assert_eq!(
resolution.active_skills[0].source_ref,
"local:company__review"
);
assert!(resolution.active_skills[0].local_override);
assert_eq!(resolution.unlinked_skills.len(), 1);
assert_eq!(
resolution.unlinked_skills[0].skill.source_ref,
"company:review"
);
assert_eq!(
resolution.unlinked_skills[0].shadowed_by,
"local:company__review"
);
}
#[test]
fn resolve_should_keep_same_source_requirements_inside_a_namespace() {
let mut company = source("company", SourceKind::Team, 10);
company.namespace = Some("company".to_owned());
let resolution = resolve_with(
vec![company],
vec![inventory(
"company",
vec![
skill_req("company", "review", &["base"]),
skill("company", "base"),
],
)],
vec![approval("source", "company")],
);
assert_eq!(
active_slots(&resolution),
vec!["company__base", "company__review"]
);
assert!(resolution.blocked_skills.is_empty());
}
#[test]
fn resolve_should_tie_break_equal_priority_by_source_id() {
let resolution = resolve_with(
vec![
source("z-team", SourceKind::Team, 10),
source("a-team", SourceKind::Team, 10),
],
vec![
inventory("z-team", vec![skill("z-team", "copy-editing")]),
inventory("a-team", vec![skill("a-team", "copy-editing")]),
],
vec![approval("source", "z-team"), approval("source", "a-team")],
);
assert_eq!(
resolution.active_skills[0].source_ref,
"a-team:copy-editing"
);
}
#[test]
fn resolve_should_mark_local_winner_as_local_override() {
let resolution = resolve_with(
vec![
source("local", SourceKind::Local, 0),
source("company", SourceKind::Team, 10),
],
vec![
inventory("local", vec![skill("local", "review")]),
inventory("company", vec![skill("company", "review")]),
],
vec![approval("source", "company")],
);
assert!(resolution.active_skills[0].local_override);
}
#[test]
fn resolve_should_keep_lower_priority_approved_skill_when_winner_is_unapproved() {
let resolution = resolve_with(
vec![
source("new-team", SourceKind::Team, 0),
source("old-team", SourceKind::Team, 10),
],
vec![
inventory("new-team", vec![skill("new-team", "review")]),
inventory("old-team", vec![skill("old-team", "review")]),
],
vec![approval("source", "old-team")],
);
assert_eq!(resolution.active_skills[0].source_ref, "old-team:review");
}
#[test]
fn resolve_should_not_match_bare_skill_approval() {
let resolution = resolve_with(
vec![source("company", SourceKind::Team, 10)],
vec![inventory("company", vec![skill("company", "review")])],
vec![approval("skill", "review")],
);
assert!(resolution.active_skills.is_empty());
assert_eq!(
resolution.pending_approval_skills[0].source_ref,
"company:review"
);
assert!(resolution.diagnostics.iter().any(|diagnostic| {
diagnostic.code == ResolutionDiagnosticCode::LegacyBareApproval
&& diagnostic
.message
.contains("re-approve as `company:review`")
}));
}
#[test]
fn resolve_should_not_match_bare_stable_id_approval() {
let resolution = resolve_with(
vec![source("company", SourceKind::Team, 10)],
vec![inventory(
"company",
vec![skill_with_id("company", "review", "shared.review")],
)],
vec![approval("skill", "shared.review")],
);
assert!(resolution.active_skills.is_empty());
assert_eq!(
resolution.pending_approval_skills[0].source_ref,
"company:review"
);
assert!(resolution.diagnostics.iter().any(|diagnostic| {
diagnostic.code == ResolutionDiagnosticCode::LegacyBareApproval
&& diagnostic
.message
.contains("re-approve as `company:shared.review`")
}));
}
#[test]
fn resolve_should_match_source_qualified_skill_approval_only() {
let resolution = resolve_with(
vec![
source("new-team", SourceKind::Team, 0),
source("old-team", SourceKind::Team, 10),
],
vec![
inventory("new-team", vec![skill("new-team", "review")]),
inventory("old-team", vec![skill("old-team", "review")]),
],
vec![approval("skill", "old-team:review")],
);
assert_eq!(resolution.active_skills[0].source_ref, "old-team:review");
assert_eq!(
resolution.pending_approval_skills[0].source_ref,
"new-team:review"
);
}
#[test]
fn resolve_should_match_source_qualified_stable_id_approval_only() {
let resolution = resolve_with(
vec![
source("new-team", SourceKind::Team, 0),
source("old-team", SourceKind::Team, 10),
],
vec![
inventory(
"new-team",
vec![skill_with_id("new-team", "review", "shared.review")],
),
inventory(
"old-team",
vec![skill_with_id("old-team", "review", "shared.review")],
),
],
vec![approval("skill", "old-team:shared.review")],
);
assert_eq!(resolution.active_skills[0].source_ref, "old-team:review");
assert_eq!(
resolution.pending_approval_skills[0].source_ref,
"new-team:review"
);
}
#[test]
fn resolve_should_match_source_qualified_author_approval_against_owners() {
let mut team_skill = skill("company", "review");
team_skill.owners = vec!["core-team".to_owned()];
let resolution = resolve_with(
vec![source("company", SourceKind::Team, 10)],
vec![inventory("company", vec![team_skill])],
vec![approval("author", "company:core-team")],
);
assert_eq!(resolution.active_skills[0].source_ref, "company:review");
}
#[test]
fn resolve_should_not_apply_owner_approval_to_another_source() {
let mut approved_source_skill = skill("reviewed", "review");
approved_source_skill.owners = vec!["core-team".to_owned()];
let mut spoofed_source_skill = skill("unreviewed", "review");
spoofed_source_skill.owners = vec!["core-team".to_owned()];
let resolution = resolve_with(
vec![
source("unreviewed", SourceKind::Team, 0),
source("reviewed", SourceKind::Team, 10),
],
vec![
inventory("unreviewed", vec![spoofed_source_skill]),
inventory("reviewed", vec![approved_source_skill]),
],
vec![approval("org", "reviewed:core-team")],
);
assert_eq!(resolution.active_skills[0].source_ref, "reviewed:review");
assert_eq!(
resolution.pending_approval_skills[0].source_ref,
"unreviewed:review"
);
}
#[test]
fn resolve_should_hold_unapproved_team_skill_as_pending() {
let resolution = resolve_with(
vec![source("company", SourceKind::Team, 10)],
vec![inventory("company", vec![skill("company", "review")])],
Vec::new(),
);
assert!(resolution.active_skills.is_empty());
}
#[test]
fn resolve_should_list_unapproved_team_skill_in_pending_approval() {
let resolution = resolve_with(
vec![source("company", SourceKind::Team, 10)],
vec![inventory("company", vec![skill("company", "review")])],
Vec::new(),
);
assert_eq!(
resolution.pending_approval_skills[0].source_ref,
"company:review"
);
}
#[test]
fn resolve_should_list_all_unapproved_same_slot_skills_in_pending_approval() {
let resolution = resolve_with(
vec![
source("team-a", SourceKind::Team, 10),
source("team-b", SourceKind::Team, 20),
],
vec![
inventory("team-a", vec![skill("team-a", "review")]),
inventory("team-b", vec![skill("team-b", "review")]),
],
Vec::new(),
);
let pending = resolution
.pending_approval_skills
.iter()
.map(|skill| skill.source_ref.as_str())
.collect::<Vec<_>>();
assert!(resolution.active_skills.is_empty());
assert_eq!(pending, vec!["team-a:review", "team-b:review"]);
}
#[test]
fn resolve_should_approve_trusted_source_without_record() {
let mut trusted = source("company", SourceKind::Team, 10);
trusted.trusted = true;
let resolution = resolve_with(
vec![trusted],
vec![inventory("company", vec![skill("company", "review")])],
Vec::new(),
);
assert_eq!(resolution.active_skills[0].source_ref, "company:review");
}
proptest! {
#[test]
fn resolve_should_be_order_independent_across_input_permutations(
source_order in prop::sample::select(index_permutations()),
inventory_order in prop::sample::select(index_permutations()),
) {
let sources = vec![
source("z-team", SourceKind::Team, 10),
source("a-team", SourceKind::Team, 10),
source("c-team", SourceKind::Team, 5),
];
let inventories = vec![
inventory(
"z-team",
vec![skill("z-team", "review"), skill("z-team", "format")],
),
inventory("a-team", vec![skill("a-team", "review")]),
inventory("c-team", vec![skill("c-team", "format")]),
];
let approvals = vec![
approval("source", "z-team"),
approval("source", "a-team"),
approval("source", "c-team"),
];
let baseline =
resolve_with(sources.clone(), inventories.clone(), approvals.clone()).active_skills;
prop_assert_eq!(
resolve_with(
permute(&sources, &source_order),
permute(&inventories, &inventory_order),
approvals,
)
.active_skills,
baseline
);
}
}
fn index_permutations() -> Vec<Vec<usize>> {
vec![
vec![0, 1, 2],
vec![0, 2, 1],
vec![1, 0, 2],
vec![1, 2, 0],
vec![2, 0, 1],
vec![2, 1, 0],
]
}
fn permute<T: Clone>(items: &[T], order: &[usize]) -> Vec<T> {
order.iter().map(|index| items[*index].clone()).collect()
}
fn resolve_with(
sources: Vec<SourceConfig>,
inventories: Vec<SourceInventory>,
approvals: Vec<ApprovalRecord>,
) -> Resolution {
resolve(&ResolutionInput {
sources: &sources,
inventories,
approvals,
})
}
fn source(id: &str, kind: SourceKind, priority: i32) -> SourceConfig {
SourceConfig {
id: id.to_owned(),
kind,
path: PathBuf::from(format!("/tmp/{id}")),
subpath: None,
priority,
namespace: None,
enabled: true,
trusted: false,
url: None,
branch: None,
update_policy: None,
selection: Vec::new(),
declared_by: None,
declared_ref: None,
}
}
fn inventory(source_id: &str, skills: Vec<SkillRecord>) -> SourceInventory {
SourceInventory {
source_id: source_id.to_owned(),
skills,
agents: Vec::new(),
plugins: Vec::new(),
warnings: Vec::new(),
agent_warnings: Vec::new(),
plugin_warnings: Vec::new(),
}
}
fn skill(source_id: &str, slot_name: &str) -> SkillRecord {
SkillRecord {
source_id: source_id.to_owned(),
source_ref: format!("{source_id}:{slot_name}"),
id: None,
slot_name: slot_name.to_owned(),
path: PathBuf::from(format!("/tmp/{source_id}/{slot_name}")),
skill_file: PathBuf::from(format!("/tmp/{source_id}/{slot_name}/SKILL.md")),
delivery: SkillDelivery::Direct,
description: None,
requires: Vec::new(),
owners: Vec::new(),
tags: Vec::new(),
compatibility: None,
metadata: BTreeMap::new(),
binaries: Vec::new(),
}
}
fn skill_with_id(source_id: &str, slot_name: &str, id: &str) -> SkillRecord {
let mut skill = skill(source_id, slot_name);
skill.id = Some(id.to_owned());
skill
}
fn approval(scope: &str, value: &str) -> ApprovalRecord {
ApprovalRecord {
scope: scope.to_owned(),
value: value.to_owned(),
granted_at_unix: None,
}
}
fn catalog(id: &str, priority: i32, selection: &[&str]) -> SourceConfig {
let mut source = source(id, SourceKind::Catalog, priority);
source.trusted = true;
source.selection = selection.iter().map(|item| (*item).to_owned()).collect();
source
}
fn skill_req(source_id: &str, slot_name: &str, requires: &[&str]) -> SkillRecord {
let mut record = skill(source_id, slot_name);
record.requires = requires.iter().map(|item| (*item).to_owned()).collect();
record
}
fn active_slots(resolution: &Resolution) -> Vec<&str> {
resolution
.active_skills
.iter()
.map(|skill| skill.slot_name.as_str())
.collect()
}
#[test]
fn resolve_should_expand_same_catalog_required_closure() {
let resolution = resolve_with(
vec![catalog("cat", 10, &["alpha"])],
vec![inventory(
"cat",
vec![skill_req("cat", "alpha", &["beta"]), skill("cat", "beta")],
)],
Vec::new(),
);
let active = active_slots(&resolution);
assert!(active.contains(&"alpha"));
assert!(active.contains(&"beta"));
assert!(resolution.blocked_skills.is_empty());
}
#[test]
fn resolve_should_expand_catalog_closure_from_relative_path_selection() {
let mut alpha = skill_req("cat", "alpha", &["beta"]);
alpha.path = PathBuf::from("/tmp/cat/skills/alpha");
let mut beta = skill("cat", "beta");
beta.path = PathBuf::from("/tmp/cat/skills/beta");
let resolution = resolve_with(
vec![catalog("cat", 10, &["skills/alpha"])],
vec![inventory("cat", vec![alpha, beta])],
Vec::new(),
);
let active = active_slots(&resolution);
assert!(active.contains(&"alpha"));
assert!(active.contains(&"beta"));
}
#[test]
fn resolve_should_expand_required_closure_transitively() {
let resolution = resolve_with(
vec![catalog("cat", 10, &["alpha"])],
vec![inventory(
"cat",
vec![
skill_req("cat", "alpha", &["beta"]),
skill_req("cat", "beta", &["gamma"]),
skill("cat", "gamma"),
],
)],
Vec::new(),
);
assert!(active_slots(&resolution).contains(&"gamma"));
}
#[test]
fn resolve_should_block_dependent_on_missing_requirement() {
let resolution = resolve_with(
vec![catalog("cat", 10, &["alpha"])],
vec![inventory(
"cat",
vec![skill_req("cat", "alpha", &["ghost"])],
)],
Vec::new(),
);
assert!(resolution.active_skills.is_empty());
assert_eq!(resolution.blocked_skills.len(), 1);
assert_eq!(
resolution.blocked_skills[0].reason,
ClosureBlockReason::Missing
);
}
#[test]
fn resolve_should_hint_at_an_approved_alternate_when_the_winner_is_blocked() {
let resolution = resolve_with(
vec![
catalog("team-a", 10, &["review"]),
catalog("team-b", 20, &["review"]),
],
vec![
inventory("team-a", vec![skill_req("team-a", "review", &["base"])]),
inventory("team-b", vec![skill("team-b", "review")]),
],
Vec::new(),
);
assert!(active_slots(&resolution).is_empty());
assert!(
resolution
.blocked_skills
.iter()
.any(|blocked| blocked.skill.source_ref == "team-a:review")
);
let hint = resolution
.diagnostics
.iter()
.find(|diagnostic| {
diagnostic.code == ResolutionDiagnosticCode::BlockedWinnerAlternateAvailable
})
.expect("a blocked-winner alternate hint should be emitted");
assert_eq!(hint.source_ref.as_deref(), Some("team-b:review"));
assert!(hint.message.contains("team-b:review"));
assert!(!ResolutionDiagnosticCode::BlockedWinnerAlternateAvailable.requires_review());
}
#[test]
fn resolve_should_disclose_an_equal_priority_tie_in_the_shadow_message() {
let resolution = resolve_with(
vec![
catalog("team-a", 10, &["review"]),
catalog("team-b", 10, &["review"]),
],
vec![
inventory("team-a", vec![skill("team-a", "review")]),
inventory("team-b", vec![skill("team-b", "review")]),
],
Vec::new(),
);
assert_eq!(active_slots(&resolution), vec!["review"]);
let shadow = resolution
.diagnostics
.iter()
.find(|diagnostic| diagnostic.code == ResolutionDiagnosticCode::Shadowed)
.expect("a shadow diagnostic should be emitted");
assert_eq!(shadow.source_ref.as_deref(), Some("team-b:review"));
assert!(shadow.message.contains("equal source priority"));
assert!(shadow.message.contains("dalo source priority"));
}
#[test]
fn resolve_should_block_dependent_when_requirement_pending_approval() {
let resolution = resolve_with(
vec![source("team", SourceKind::Team, 10)],
vec![inventory(
"team",
vec![skill_req("team", "alpha", &["beta"]), skill("team", "beta")],
)],
vec![approval("skill", "team:alpha")],
);
assert!(!active_slots(&resolution).contains(&"alpha"));
assert_eq!(
resolution.blocked_skills[0].reason,
ClosureBlockReason::PendingApproval
);
}
#[test]
fn resolve_should_block_source_qualified_requirement_when_shadowed() {
let mut team = source("team", SourceKind::Team, 5);
team.trusted = true;
let resolution = resolve_with(
vec![catalog("cat", 10, &["alpha"]), team],
vec![
inventory(
"cat",
vec![
skill_req("cat", "alpha", &["cat:beta"]),
skill("cat", "beta"),
],
),
inventory("team", vec![skill("team", "beta")]),
],
Vec::new(),
);
assert!(
!resolution
.active_skills
.iter()
.any(|skill| skill.source_ref == "cat:alpha")
);
assert!(
resolution
.active_skills
.iter()
.any(|skill| skill.source_ref == "team:beta")
);
assert_eq!(
resolution.blocked_skills[0].reason,
ClosureBlockReason::ShadowedNotSatisfied
);
assert_eq!(resolution.blocked_skills[0].requirement, "cat:beta");
}
#[test]
fn resolve_should_report_cross_source_require_without_installing() {
let mut team = source("team", SourceKind::Team, 20);
team.trusted = true;
let resolution = resolve_with(
vec![catalog("cat", 10, &["alpha"]), team],
vec![
inventory("cat", vec![skill_req("cat", "alpha", &["beta"])]),
inventory("team", vec![skill("team", "beta")]),
],
Vec::new(),
);
assert!(active_slots(&resolution).contains(&"alpha"));
assert!(
resolution
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == ResolutionDiagnosticCode::CrossSourceRequire)
);
}
}