use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::inventory::SkillDelivery;
use crate::materialize::SyncReport;
use crate::plugin::{
AppliedPluginPolicy, PluginResolution, PluginState, ResolvedPluginDependency,
ResolvedPluginMember, SelectionOrigin,
};
use crate::resolver::{Resolution, UnlinkedReason};
use crate::source::{SourceConfig, SourceHeadCache, SourceKind};
pub const USER_LOCK_SCHEMA_VERSION: u32 = 6;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserLock {
pub schema_version: u32,
#[serde(default)]
pub sources: Vec<LockedSource>,
#[serde(default)]
pub active_skills: Vec<LockedSkill>,
#[serde(default)]
pub pending_approval_skills: Vec<LockedSkill>,
#[serde(default)]
pub unlinked_skills: Vec<LockedSkill>,
#[serde(default)]
pub target_materializations: Vec<LockedTargetMaterialization>,
#[serde(default)]
pub active_instruction_packs: Vec<LockedInstructionPack>,
#[serde(default)]
pub plugins: Vec<LockedPlugin>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub binaries: Vec<LockedBinary>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedBinary {
pub source_ref: String,
pub contract_hash: String,
pub platform: String,
pub digest: String,
pub staged_path: PathBuf,
pub exposed_path: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedPlugin {
pub source_ref: String,
pub slot_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub package_hash: String,
pub closure_hash: String,
pub origins: Vec<SelectionOrigin>,
pub policies: Vec<AppliedPluginPolicy>,
pub state: PluginState,
#[serde(skip_serializing_if = "Option::is_none")]
pub shadowed_by: Option<String>,
pub members: Vec<ResolvedPluginMember>,
#[serde(default)]
pub dependencies: Vec<ResolvedPluginDependency>,
pub blocking_reasons: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedSource {
pub id: String,
pub kind: SourceKind,
pub path: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subpath: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commit: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedSkill {
pub source_ref: String,
pub slot_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub source_id: String,
pub source_kind: SourceKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delivery: Option<SkillDelivery>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedTargetMaterialization {
pub link_path: PathBuf,
#[serde(skip_serializing_if = "Option::is_none")]
pub desired_path: Option<PathBuf>,
pub kind: String,
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedInstructionPack {
pub pack_id: String,
pub target: PathBuf,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub logical_targets: Vec<String>,
pub source_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub commit: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LockDrift {
pub code: LockDriftCode,
pub subject: String,
pub message: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LockDriftCode {
SourceCommitChanged,
SourceSubpathChanged,
SourceRemoved,
SourceAdded,
ActiveRemoved,
ActiveAdded,
UnlinkedRemoved,
UnlinkedAdded,
PendingApprovalRemoved,
PendingApprovalAdded,
SkillDeliveryChanged,
SkillMaterializationChanged,
PluginAdded,
PluginRemoved,
PluginChanged,
}
impl UserLock {
#[must_use]
pub fn empty() -> Self {
Self {
schema_version: USER_LOCK_SCHEMA_VERSION,
sources: Vec::new(),
active_skills: Vec::new(),
pending_approval_skills: Vec::new(),
unlinked_skills: Vec::new(),
target_materializations: Vec::new(),
active_instruction_packs: Vec::new(),
plugins: Vec::new(),
binaries: Vec::new(),
}
}
}
#[must_use]
pub fn build_user_lock(
sources: &[SourceConfig],
resolution: &Resolution,
sync_report: Option<&SyncReport>,
plugins: Option<&PluginResolution>,
) -> UserLock {
build_user_lock_with_head_cache(
sources,
resolution,
sync_report,
plugins,
&mut SourceHeadCache::default(),
)
}
pub(crate) fn build_user_lock_with_head_cache(
sources: &[SourceConfig],
resolution: &Resolution,
sync_report: Option<&SyncReport>,
plugins: Option<&PluginResolution>,
head_cache: &mut SourceHeadCache,
) -> UserLock {
let mut lock = UserLock {
schema_version: USER_LOCK_SCHEMA_VERSION,
sources: locked_sources(sources, resolution, head_cache),
active_skills: resolution
.active_skills
.iter()
.map(|skill| LockedSkill {
source_ref: skill.source_ref.clone(),
slot_name: skill.slot_name.clone(),
id: skill.id.clone(),
source_id: skill.source_id.clone(),
source_kind: skill.source_kind,
delivery: locked_delivery(skill, sync_report),
reason: None,
})
.collect(),
pending_approval_skills: resolution
.pending_approval_skills
.iter()
.map(|skill| LockedSkill {
source_ref: skill.source_ref.clone(),
slot_name: skill.slot_name.clone(),
id: skill.id.clone(),
source_id: skill.source_id.clone(),
source_kind: skill.source_kind,
delivery: locked_delivery(skill, None),
reason: Some("pending_approval".to_owned()),
})
.collect(),
unlinked_skills: resolution
.unlinked_skills
.iter()
.map(|unlinked| LockedSkill {
source_ref: unlinked.skill.source_ref.clone(),
slot_name: unlinked.skill.slot_name.clone(),
id: unlinked.skill.id.clone(),
source_id: unlinked.skill.source_id.clone(),
source_kind: unlinked.skill.source_kind,
delivery: locked_delivery(&unlinked.skill, None),
reason: Some(unlinked_reason_name(unlinked.reason).to_owned()),
})
.collect(),
target_materializations: sync_report.map_or_else(Vec::new, |report| {
report
.operations
.iter()
.map(|operation| LockedTargetMaterialization {
link_path: operation.link_path.clone(),
desired_path: operation.desired_path.clone(),
kind: operation.kind.as_str().to_owned(),
status: operation.status.as_str().to_owned(),
reason: operation.reason.clone(),
})
.collect()
}),
active_instruction_packs: Vec::new(),
binaries: Vec::new(),
plugins: plugins.map_or_else(Vec::new, |resolution| {
resolution
.plugins
.iter()
.map(|plugin| LockedPlugin {
source_ref: plugin.source_ref.clone(),
slot_name: plugin.slot_name.clone(),
id: plugin.id.clone(),
package_hash: plugin.package_hash.clone(),
closure_hash: plugin.closure_hash.clone(),
origins: plugin.origins.clone(),
policies: plugin.policies.clone(),
state: plugin.state,
shadowed_by: plugin.shadowed_by.clone(),
members: plugin.members.clone(),
dependencies: plugin.dependencies.clone(),
blocking_reasons: plugin.blocking_reasons.clone(),
})
.collect()
}),
};
sort_user_lock(&mut lock);
lock
}
#[must_use]
pub fn compare_user_lock(previous: &UserLock, current: &UserLock) -> Vec<LockDrift> {
let mut drift = Vec::new();
compare_sources(previous, current, &mut drift);
compare_skill_refs(
LockDriftCode::ActiveRemoved,
LockDriftCode::ActiveAdded,
"active skill",
&previous.active_skills,
¤t.active_skills,
&mut drift,
);
compare_skill_delivery(previous, current, &mut drift);
compare_plugins(previous, current, &mut drift);
compare_skill_refs(
LockDriftCode::UnlinkedRemoved,
LockDriftCode::UnlinkedAdded,
"unlinked skill",
&previous.unlinked_skills,
¤t.unlinked_skills,
&mut drift,
);
compare_skill_refs(
LockDriftCode::PendingApprovalRemoved,
LockDriftCode::PendingApprovalAdded,
"pending approval skill",
&previous.pending_approval_skills,
¤t.pending_approval_skills,
&mut drift,
);
drift.sort_by(|left, right| {
drift_code_name(left.code)
.cmp(drift_code_name(right.code))
.then_with(|| left.subject.cmp(&right.subject))
});
drift
}
fn locked_delivery(
skill: &crate::resolver::ResolvedSkill,
sync_report: Option<&SyncReport>,
) -> Option<SkillDelivery> {
match &skill.delivery {
SkillDelivery::Direct => None,
delivery @ SkillDelivery::Prebuilt { .. } => Some(delivery.clone()),
SkillDelivery::Generated { .. } => {
let mut delivery = skill.delivery.clone();
if let SkillDelivery::Generated {
output_fingerprints,
derivation_hash,
..
} = &mut delivery
&& let Some(report) = sync_report
{
for generated in report.deliveries.iter().filter(|generated| {
generated.source_ref == skill.source_ref
&& generated.mode == crate::inventory::SkillDeliveryMode::Generated
&& !generated.blocked
}) {
if let (Some(provider), Some(fingerprint)) =
(&generated.provider, &generated.fingerprint)
{
output_fingerprints.insert(provider.clone(), fingerprint.clone());
}
if derivation_hash.is_none() {
*derivation_hash = generated.derivation_hash.clone();
}
}
}
Some(delivery)
}
}
}
fn compare_skill_delivery(previous: &UserLock, current: &UserLock, drift: &mut Vec<LockDrift>) {
let previous = previous
.active_skills
.iter()
.map(|skill| (skill.source_ref.as_str(), &skill.delivery))
.collect::<BTreeMap<_, _>>();
let current = current
.active_skills
.iter()
.map(|skill| (skill.source_ref.as_str(), &skill.delivery))
.collect::<BTreeMap<_, _>>();
for source_ref in previous
.keys()
.filter(|source_ref| current.contains_key(**source_ref))
{
if previous[source_ref] != current[source_ref] {
drift.push(LockDrift {
code: LockDriftCode::SkillDeliveryChanged,
subject: (*source_ref).to_owned(),
message: format!(
"active skill `{source_ref}` delivery mapping or artifact fingerprint changed"
),
});
}
}
}
fn locked_sources(
sources: &[SourceConfig],
resolution: &Resolution,
head_cache: &mut SourceHeadCache,
) -> Vec<LockedSource> {
let mut locked = sources
.iter()
.filter(|source| source.enabled)
.map(|source| LockedSource {
id: source.id.clone(),
kind: source.kind,
path: source.path.clone(),
subpath: source.subpath.clone(),
commit: (source.kind != SourceKind::Catalog)
.then(|| {
resolved_generated_commit(resolution, &source.id)
.or_else(|| head_cache.resolve(source))
})
.flatten(),
})
.collect::<Vec<_>>();
locked.sort_by(|left, right| left.id.cmp(&right.id));
locked
}
fn resolved_generated_commit(resolution: &Resolution, source_id: &str) -> Option<String> {
resolution
.active_skills
.iter()
.chain(&resolution.pending_approval_skills)
.chain(
resolution
.unlinked_skills
.iter()
.map(|unlinked| &unlinked.skill),
)
.chain(
resolution
.blocked_skills
.iter()
.map(|blocked| &blocked.skill),
)
.filter(|skill| skill.source_id == source_id)
.find_map(|skill| match &skill.delivery {
SkillDelivery::Generated { source_commit, .. } => source_commit.clone(),
SkillDelivery::Direct | SkillDelivery::Prebuilt { .. } => None,
})
}
fn sort_user_lock(lock: &mut UserLock) {
lock.sources.sort_by(|left, right| left.id.cmp(&right.id));
sort_locked_skills(&mut lock.active_skills);
sort_locked_skills(&mut lock.pending_approval_skills);
sort_locked_skills(&mut lock.unlinked_skills);
lock.target_materializations.sort_by(|left, right| {
left.link_path
.cmp(&right.link_path)
.then_with(|| left.kind.cmp(&right.kind))
});
lock.plugins
.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
lock.binaries
.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
}
fn compare_plugins(previous: &UserLock, current: &UserLock, drift: &mut Vec<LockDrift>) {
let previous_plugins = previous
.plugins
.iter()
.map(|plugin| (plugin.source_ref.as_str(), plugin))
.collect::<BTreeMap<_, _>>();
let current_plugins = current
.plugins
.iter()
.map(|plugin| (plugin.source_ref.as_str(), plugin))
.collect::<BTreeMap<_, _>>();
let identities = previous_plugins
.keys()
.chain(current_plugins.keys())
.copied()
.collect::<BTreeSet<_>>();
for identity in identities {
match (
previous_plugins.get(identity),
current_plugins.get(identity),
) {
(Some(previous), Some(current)) if previous != current => drift.push(LockDrift {
code: LockDriftCode::PluginChanged,
subject: identity.to_owned(),
message: format!("plugin `{identity}` canonical state differs from lock"),
}),
(Some(_), None) => drift.push(LockDrift {
code: LockDriftCode::PluginRemoved,
subject: identity.to_owned(),
message: format!("plugin `{identity}` is no longer selected"),
}),
(None, Some(_)) => drift.push(LockDrift {
code: LockDriftCode::PluginAdded,
subject: identity.to_owned(),
message: format!("plugin `{identity}` is not present in the lock"),
}),
_ => {}
}
}
}
fn sort_locked_skills(skills: &mut [LockedSkill]) {
skills.sort_by(|left, right| {
left.slot_name
.cmp(&right.slot_name)
.then_with(|| left.source_ref.cmp(&right.source_ref))
});
}
fn compare_sources(previous: &UserLock, current: &UserLock, drift: &mut Vec<LockDrift>) {
let previous_sources = previous
.sources
.iter()
.map(|source| (source.id.as_str(), source))
.collect::<BTreeMap<_, _>>();
let current_sources = current
.sources
.iter()
.map(|source| (source.id.as_str(), source))
.collect::<BTreeMap<_, _>>();
let source_ids = previous_sources
.keys()
.chain(current_sources.keys())
.copied()
.collect::<BTreeSet<_>>();
for source_id in source_ids {
match (
previous_sources.get(source_id),
current_sources.get(source_id),
) {
(Some(previous_source), Some(current_source))
if previous_source.subpath != current_source.subpath =>
{
drift.push(LockDrift {
code: LockDriftCode::SourceSubpathChanged,
subject: source_id.to_owned(),
message: format!("source `{source_id}` subpath differs from lock"),
});
}
(Some(previous_source), Some(current_source))
if previous_source.kind != current_source.kind
|| (previous_source.kind != SourceKind::Catalog
&& current_source.kind != SourceKind::Catalog
&& previous_source.commit != current_source.commit) =>
{
drift.push(LockDrift {
code: LockDriftCode::SourceCommitChanged,
subject: source_id.to_owned(),
message: if previous_source.kind != current_source.kind {
format!("source `{source_id}` kind differs from lock")
} else {
format!("source `{source_id}` commit differs from lock")
},
});
}
(Some(_), None) => drift.push(LockDrift {
code: LockDriftCode::SourceRemoved,
subject: source_id.to_owned(),
message: format!("source `{source_id}` is no longer configured"),
}),
(None, Some(_)) => drift.push(LockDrift {
code: LockDriftCode::SourceAdded,
subject: source_id.to_owned(),
message: format!("source `{source_id}` is not present in the lock"),
}),
_ => {}
}
}
}
fn compare_skill_refs(
removed_code: LockDriftCode,
added_code: LockDriftCode,
label: &str,
previous: &[LockedSkill],
current: &[LockedSkill],
drift: &mut Vec<LockDrift>,
) {
let previous_refs = previous
.iter()
.map(|skill| skill.source_ref.as_str())
.collect::<BTreeSet<_>>();
let current_refs = current
.iter()
.map(|skill| skill.source_ref.as_str())
.collect::<BTreeSet<_>>();
for source_ref in previous_refs.difference(¤t_refs) {
drift.push(LockDrift {
code: removed_code,
subject: (*source_ref).to_owned(),
message: format!("{label} `{source_ref}` is no longer in the live resolution"),
});
}
for source_ref in current_refs.difference(&previous_refs) {
drift.push(LockDrift {
code: added_code,
subject: (*source_ref).to_owned(),
message: format!("{label} `{source_ref}` is not present in the lock"),
});
}
let previous_by_ref = previous
.iter()
.map(|skill| (skill.source_ref.as_str(), skill))
.collect::<BTreeMap<_, _>>();
let current_by_ref = current
.iter()
.map(|skill| (skill.source_ref.as_str(), skill))
.collect::<BTreeMap<_, _>>();
for source_ref in previous_by_ref
.keys()
.filter(|source_ref| current_by_ref.contains_key(**source_ref))
{
let previous_skill = previous_by_ref[source_ref];
let current_skill = current_by_ref[source_ref];
if previous_skill.slot_name != current_skill.slot_name {
drift.push(LockDrift {
code: LockDriftCode::SkillMaterializationChanged,
subject: (*source_ref).to_owned(),
message: format!(
"skill `{source_ref}` materializes as `{}` instead of `{}`",
current_skill.slot_name, previous_skill.slot_name
),
});
}
}
}
fn unlinked_reason_name(reason: UnlinkedReason) -> &'static str {
match reason {
UnlinkedReason::Shadowed => "shadowed",
}
}
fn drift_code_name(code: LockDriftCode) -> &'static str {
match code {
LockDriftCode::SourceCommitChanged => "source_commit_changed",
LockDriftCode::SourceSubpathChanged => "source_subpath_changed",
LockDriftCode::SourceRemoved => "source_removed",
LockDriftCode::SourceAdded => "source_added",
LockDriftCode::ActiveRemoved => "active_removed",
LockDriftCode::ActiveAdded => "active_added",
LockDriftCode::UnlinkedRemoved => "unlinked_removed",
LockDriftCode::UnlinkedAdded => "unlinked_added",
LockDriftCode::PendingApprovalRemoved => "pending_approval_removed",
LockDriftCode::PendingApprovalAdded => "pending_approval_added",
LockDriftCode::SkillDeliveryChanged => "skill_delivery_changed",
LockDriftCode::SkillMaterializationChanged => "skill_materialization_changed",
LockDriftCode::PluginAdded => "plugin_added",
LockDriftCode::PluginRemoved => "plugin_removed",
LockDriftCode::PluginChanged => "plugin_changed",
}
}
impl LockDriftCode {
#[must_use]
pub const fn awaits_sync(self) -> bool {
matches!(
self,
Self::SourceAdded
| Self::SourceRemoved
| Self::ActiveAdded
| Self::ActiveRemoved
| Self::UnlinkedAdded
| Self::UnlinkedRemoved
| Self::PendingApprovalAdded
| Self::PendingApprovalRemoved
| Self::PluginAdded
| Self::PluginRemoved
)
}
}
impl std::fmt::Display for LockDriftCode {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(drift_code_name(*self))
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::materialize::{
MaterializeOperation, MaterializeOperationKind, MaterializeOperationStatus,
};
use crate::resolver::{ResolvedSkill, UnlinkedSkill, UnlinkedStatus};
#[test]
fn build_user_lock_should_sort_skills_and_materializations() {
let resolution = Resolution {
active_skills: vec![skill("team:b", "b"), skill("team:a", "a")],
pending_approval_skills: Vec::new(),
blocked_skills: Vec::new(),
unlinked_skills: vec![UnlinkedSkill {
skill: skill("team:c", "c"),
status: UnlinkedStatus::Unlinked,
reason: UnlinkedReason::Shadowed,
shadowed_by: "team:a".to_owned(),
}],
diagnostics: Vec::new(),
};
let report = SyncReport {
store: PathBuf::from("/store"),
dry_run: false,
linked_targets: 1,
operations: vec![operation("/target/b"), operation("/target/a")],
deliveries: Vec::new(),
resolution: resolution.clone(),
degraded_sources: Vec::new(),
inventory_warnings: Vec::new(),
missing_commands: Vec::new(),
unrefreshed_tracking_sources: Vec::new(),
manifest_catalogs: Vec::new(),
instruction_operations: Vec::new(),
instruction_removal_operations: Vec::new(),
unselected_catalogs: Vec::new(),
installation_plan: None,
hook_targets: Vec::new(),
plugin_targets: Vec::new(),
};
let lock = build_user_lock(&[], &resolution, Some(&report), None);
assert_eq!(lock.active_skills[0].source_ref, "team:a");
assert_eq!(
lock.target_materializations[0].link_path,
PathBuf::from("/target/a")
);
assert_eq!(lock.unlinked_skills[0].reason.as_deref(), Some("shadowed"));
}
#[test]
fn compare_user_lock_should_report_active_drift() {
let previous = UserLock {
active_skills: vec![locked_skill("local:review")],
..UserLock::empty()
};
let current = UserLock {
active_skills: vec![locked_skill("local:test")],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::ActiveRemoved)
);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::ActiveAdded)
);
}
#[test]
fn compare_user_lock_should_report_prebuilt_artifact_drift() {
let mut old = locked_skill("catalog:impeccable");
old.delivery = Some(prebuilt_delivery("sha256:old"));
let mut changed = old.clone();
changed.delivery = Some(prebuilt_delivery("sha256:new"));
let previous = UserLock {
active_skills: vec![old],
..UserLock::empty()
};
let current = UserLock {
active_skills: vec![changed],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(drift.iter().any(|entry| {
entry.code == LockDriftCode::SkillDeliveryChanged
&& entry.subject == "catalog:impeccable"
}));
}
#[test]
fn compare_sources_should_report_source_commit_changed_when_commit_differs() {
let previous = UserLock {
sources: vec![locked_source("company", Some("aaaa"))],
..UserLock::empty()
};
let current = UserLock {
sources: vec![locked_source("company", Some("bbbb"))],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::SourceCommitChanged
&& entry.subject == "company")
);
}
#[test]
fn compare_sources_should_report_subpath_change() {
let mut previous_source = locked_source("company", Some("aaaa"));
previous_source.subpath = Some(PathBuf::from("tools/skills"));
let mut current_source = previous_source.clone();
current_source.subpath = Some(PathBuf::from("agent/skills"));
let previous = UserLock {
sources: vec![previous_source],
..UserLock::empty()
};
let current = UserLock {
sources: vec![current_source],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(drift.iter().any(|entry| {
entry.code == LockDriftCode::SourceSubpathChanged && entry.subject == "company"
}));
}
#[test]
fn compare_sources_should_ignore_catalog_checkout_commit_drift() {
let previous = UserLock {
sources: vec![LockedSource {
id: "catalog".to_owned(),
kind: SourceKind::Catalog,
path: PathBuf::from("/catalog"),
subpath: None,
commit: Some("aaaa".to_owned()),
}],
..UserLock::empty()
};
let current = UserLock {
sources: vec![LockedSource {
id: "catalog".to_owned(),
kind: SourceKind::Catalog,
path: PathBuf::from("/catalog"),
subpath: None,
commit: Some("bbbb".to_owned()),
}],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.all(|entry| entry.code != LockDriftCode::SourceCommitChanged)
);
}
#[test]
fn compare_sources_should_report_source_kind_change() {
let previous = UserLock {
sources: vec![LockedSource {
id: "source".to_owned(),
kind: SourceKind::Catalog,
path: PathBuf::from("/source"),
subpath: None,
commit: None,
}],
..UserLock::empty()
};
let current = UserLock {
sources: vec![LockedSource {
id: "source".to_owned(),
kind: SourceKind::Team,
path: PathBuf::from("/source"),
subpath: None,
commit: Some("bbbb".to_owned()),
}],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(drift.iter().any(|entry| {
entry.code == LockDriftCode::SourceCommitChanged && entry.subject == "source"
}));
}
#[test]
fn compare_sources_should_report_source_removed_when_source_disappears() {
let previous = UserLock {
sources: vec![locked_source("company", Some("aaaa"))],
..UserLock::empty()
};
let current = UserLock::empty();
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::SourceRemoved
&& entry.subject == "company")
);
}
#[test]
fn compare_sources_should_report_source_added_when_source_appears() {
let previous = UserLock::empty();
let current = UserLock {
sources: vec![locked_source("company", Some("aaaa"))],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::SourceAdded
&& entry.subject == "company")
);
}
#[test]
fn compare_user_lock_should_report_unlinked_added_when_skill_becomes_unlinked() {
let previous = UserLock::empty();
let current = UserLock {
unlinked_skills: vec![locked_skill("company:review")],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::UnlinkedAdded
&& entry.subject == "company:review")
);
}
#[test]
fn compare_user_lock_should_report_unlinked_removed_when_skill_stops_being_unlinked() {
let previous = UserLock {
unlinked_skills: vec![locked_skill("company:review")],
..UserLock::empty()
};
let current = UserLock::empty();
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::UnlinkedRemoved
&& entry.subject == "company:review")
);
}
#[test]
fn compare_user_lock_should_report_materialization_change_for_same_source_skill() {
let previous = UserLock {
active_skills: vec![locked_skill("company:review")],
..UserLock::empty()
};
let mut renamed = locked_skill("company:review");
renamed.slot_name = "company__review".to_owned();
let current = UserLock {
active_skills: vec![renamed],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(drift.iter().any(|entry| {
entry.code == LockDriftCode::SkillMaterializationChanged
&& entry.subject == "company:review"
}));
}
#[test]
fn compare_user_lock_should_report_pending_approval_added_when_skill_becomes_pending() {
let previous = UserLock::empty();
let current = UserLock {
pending_approval_skills: vec![locked_skill("company:review")],
..UserLock::empty()
};
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::PendingApprovalAdded
&& entry.subject == "company:review")
);
}
#[test]
fn compare_user_lock_should_report_pending_approval_removed_when_skill_stops_being_pending() {
let previous = UserLock {
pending_approval_skills: vec![locked_skill("company:review")],
..UserLock::empty()
};
let current = UserLock::empty();
let drift = compare_user_lock(&previous, ¤t);
assert!(
drift
.iter()
.any(|entry| entry.code == LockDriftCode::PendingApprovalRemoved
&& entry.subject == "company:review")
);
}
fn skill(source_ref: &str, slot_name: &str) -> ResolvedSkill {
ResolvedSkill {
source_ref: source_ref.to_owned(),
slot_name: slot_name.to_owned(),
source_namespace: None,
id: None,
source_id: "team".to_owned(),
source_kind: SourceKind::Team,
source_priority: 10,
path: PathBuf::from(format!("/store/{slot_name}")),
delivery: crate::inventory::SkillDelivery::Direct,
compatibility: None,
binaries: Vec::new(),
local_override: false,
requires: Vec::new(),
}
}
fn operation(link_path: &str) -> MaterializeOperation {
MaterializeOperation {
kind: MaterializeOperationKind::Create,
link_path: PathBuf::from(link_path),
desired_path: Some(PathBuf::from("/store/skill")),
status: MaterializeOperationStatus::Applied,
reason: None,
}
}
fn locked_skill(source_ref: &str) -> LockedSkill {
LockedSkill {
source_ref: source_ref.to_owned(),
slot_name: source_ref
.split_once(':')
.map_or(source_ref, |(_, slot_name)| slot_name)
.to_owned(),
id: None,
source_id: "local".to_owned(),
source_kind: SourceKind::Local,
delivery: None,
reason: None,
}
}
fn prebuilt_delivery(fingerprint: &str) -> SkillDelivery {
SkillDelivery::Prebuilt {
providers: [(
"codex".to_owned(),
crate::inventory::PrebuiltSkillArtifact {
path: PathBuf::from("/source/builds/codex/impeccable"),
fingerprint: fingerprint.to_owned(),
},
)]
.into_iter()
.collect(),
universal_fallback: false,
fallback_fingerprint: None,
manifest_path: PathBuf::from("/source/skills/impeccable/DELIVERY.toml"),
}
}
fn locked_source(id: &str, commit: Option<&str>) -> LockedSource {
LockedSource {
id: id.to_owned(),
kind: SourceKind::Team,
path: PathBuf::from(format!("/store/sources/{id}")),
subpath: None,
commit: commit.map(str::to_owned),
}
}
#[test]
fn awaits_sync_should_separate_recorded_changes_from_moved_content() {
for code in [
LockDriftCode::SourceAdded,
LockDriftCode::SourceRemoved,
LockDriftCode::ActiveAdded,
LockDriftCode::ActiveRemoved,
LockDriftCode::UnlinkedAdded,
LockDriftCode::UnlinkedRemoved,
LockDriftCode::PendingApprovalAdded,
LockDriftCode::PendingApprovalRemoved,
LockDriftCode::PluginAdded,
LockDriftCode::PluginRemoved,
] {
assert!(code.awaits_sync(), "{code} should wait for sync");
}
for code in [
LockDriftCode::SourceCommitChanged,
LockDriftCode::SourceSubpathChanged,
LockDriftCode::SkillDeliveryChanged,
LockDriftCode::SkillMaterializationChanged,
LockDriftCode::PluginChanged,
] {
assert!(!code.awaits_sync(), "{code} should stay lock drift");
}
}
}