use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use serde::Serialize;
use crate::agent::{self, AgentProvider, CompatibilityResult};
use crate::error::{DaloError, DaloResult};
use crate::hook::{HookProvider, HookRequirement, HookStatusReport, HookTrustState};
use crate::inventory::SourceInventory;
use crate::materialize::{self, MaterializeOperation, MaterializeOperationStatus};
use crate::plugin::{
AppliedPluginPolicy, MemberRequirement, PluginComponentState, PluginInventoryWarning,
PluginResolution, PluginState, ResolvedPluginDependency, SelectionOrigin,
};
use crate::store::{self, MaterializationDirState, StateFile, StorePaths};
use crate::tool::{ToolState, ToolStatusReport};
pub const INSTALLATION_PLAN_SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstallationPlan {
pub schema_version: u32,
pub store: PathBuf,
pub canonical_plugins: PluginResolution,
pub inventory_warnings: Vec<PluginInventoryWarning>,
pub tools: Vec<ToolStatusReport>,
pub hooks: Vec<HookStatusReport>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_plugins: Vec<crate::plugin_projection::PluginTargetReport>,
pub destinations: Vec<DestinationPlan>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DestinationPlan {
pub path: PathBuf,
pub logical_targets: Vec<LogicalTargetPlan>,
pub portable_operations: Vec<MaterializeOperation>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LogicalTargetPlan {
pub id: String,
pub verification_baseline: String,
pub plugins: Vec<TargetPluginPlan>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetPluginPlan {
pub source_ref: String,
pub origins: Vec<SelectionOrigin>,
pub policies: Vec<AppliedPluginPolicy>,
pub dependencies: Vec<ResolvedPluginDependency>,
pub state: TargetPluginState,
pub compatibility: PlanCompatibility,
pub components: Vec<TargetComponentPlan>,
pub blockers: Vec<PlanBlocker>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetPluginState {
Active,
Degraded,
Blocked,
Declined,
Shadowed,
}
impl std::fmt::Display for TargetPluginState {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::Active => "active",
Self::Degraded => "degraded",
Self::Blocked => "blocked",
Self::Declined => "declined",
Self::Shadowed => "shadowed",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanCompatibility {
Exact,
Mapped,
GuidanceOnly,
Unsupported,
Blocked,
}
impl std::fmt::Display for PlanCompatibility {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::Exact => "exact",
Self::Mapped => "mapped",
Self::GuidanceOnly => "guidance_only",
Self::Unsupported => "unsupported",
Self::Blocked => "blocked",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetComponentPlan {
pub reference: String,
pub requirement: MemberRequirement,
pub canonical_state: PluginComponentState,
pub state: TargetComponentState,
pub compatibility: PlanCompatibility,
#[serde(skip_serializing_if = "Option::is_none")]
pub authored_fallback: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selected_fallback: Option<String>,
pub proposed_artifact: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub blocker: Option<PlanBlocker>,
#[serde(skip_serializing_if = "Option::is_none")]
pub remediation: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetComponentState {
Active,
Inactive,
PendingApproval,
Shadowed,
IntentionallyOmitted,
Blocked,
}
impl std::fmt::Display for TargetComponentState {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::Active => "active",
Self::Inactive => "inactive",
Self::PendingApproval => "pending_approval",
Self::Shadowed => "shadowed",
Self::IntentionallyOmitted => "intentionally_omitted",
Self::Blocked => "blocked",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PlanBlocker {
pub source: PlanBlockerSource,
pub message: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanBlockerSource {
MalformedInput,
MissingDependency,
MissingApproval,
TargetUnlinked,
UnsupportedBehavior,
RequiredSafetyBoundary,
Drift,
Conflict,
PolicyDecision,
InactiveInstruction,
}
pub fn build_installation_plan(
store_root: &Path,
target_filter: Option<&str>,
) -> DaloResult<InstallationPlan> {
let paths = StorePaths::new(store_root.to_path_buf());
let config = store::read_config(&paths)?;
let approvals = store::read_approvals(&paths)?;
let lock = store::read_user_lock(&paths)?;
let state = store::read_state(&paths)?;
if let Some(target) = target_filter
&& !state
.targets
.iter()
.any(|candidate| candidate.enabled && candidate.id == target)
{
return Err(DaloError::InvalidArgument {
reason: format!("target `{target}` is not linked"),
});
}
let resolved = crate::resolver::resolve_from_config_with_plugin_inventories(
&config,
approvals.approvals.clone(),
);
let plugin_inventories = crate::resolver::plugin_inventories(&resolved);
let reconciliation_inventories = crate::resolver::inventories_with_plugins(&resolved);
let mut live = resolved.live;
let active_instructions = lock
.active_instruction_packs
.iter()
.map(|pack| format!("{}:{}", pack.source_id, pack.pack_id))
.collect::<BTreeSet<_>>();
crate::plugin::apply_component_resolution(
&mut live.plugins,
&live.resolution,
&live.agents,
&active_instructions,
);
let materialization = materialize::materialize(&paths, &live.resolution, true)?;
let mut plan = build_from_facts_with_active_skills(
store_root,
&state,
&live.plugins,
&reconciliation_inventories,
&materialization.resolution.active_skills,
&materialization.operations,
target_filter,
);
let tools = crate::tool::list_from_inventories(
&paths,
&config.sources,
&approvals.approvals,
&plugin_inventories,
);
let hooks = crate::hook::list_from_inventories(
&paths,
&config.sources,
&approvals.approvals,
&plugin_inventories,
&tools.tools,
)?;
attach_tool_status_from_report(&mut plan, &tools.tools);
attach_hook_status_from_report(&mut plan, &hooks.hooks);
plan.native_plugins = crate::plugin_projection::reconcile(
&paths,
&state,
&live.plugins,
&reconciliation_inventories,
&plan.tools,
&plan.hooks,
true,
)?;
if let Some(target) = target_filter {
plan.native_plugins.retain(|report| report.target == target);
}
Ok(plan)
}
#[must_use]
pub fn build_from_facts(
store_root: &Path,
state: &StateFile,
plugins: &PluginResolution,
inventories: &[SourceInventory],
operations: &[MaterializeOperation],
target_filter: Option<&str>,
) -> InstallationPlan {
build_from_facts_with_skill_slots(
store_root,
state,
plugins,
inventories,
None,
operations,
target_filter,
)
}
#[must_use]
pub(crate) fn build_from_facts_with_active_skills(
store_root: &Path,
state: &StateFile,
plugins: &PluginResolution,
inventories: &[SourceInventory],
active_skills: &[crate::resolver::ResolvedSkill],
operations: &[MaterializeOperation],
target_filter: Option<&str>,
) -> InstallationPlan {
build_from_facts_with_skill_slots(
store_root,
state,
plugins,
inventories,
Some(active_skills),
operations,
target_filter,
)
}
fn build_from_facts_with_skill_slots(
store_root: &Path,
state: &StateFile,
plugins: &PluginResolution,
inventories: &[SourceInventory],
active_skills: Option<&[crate::resolver::ResolvedSkill]>,
operations: &[MaterializeOperation],
target_filter: Option<&str>,
) -> InstallationPlan {
let mut destinations = state
.materialization_dirs
.iter()
.filter_map(|destination| {
destination_plan(
destination,
plugins,
inventories,
active_skills,
operations,
target_filter,
)
})
.collect::<Vec<_>>();
destinations.sort_by(|left, right| left.path.cmp(&right.path));
let mut inventory_warnings = inventories
.iter()
.flat_map(|inventory| inventory.plugin_warnings.iter().cloned())
.collect::<Vec<_>>();
inventory_warnings.sort_by(|left, right| {
left.path
.cmp(&right.path)
.then_with(|| left.code.as_str().cmp(right.code.as_str()))
});
InstallationPlan {
schema_version: INSTALLATION_PLAN_SCHEMA_VERSION,
store: store_root.to_path_buf(),
canonical_plugins: plugins.clone(),
inventory_warnings,
tools: Vec::new(),
hooks: Vec::new(),
native_plugins: Vec::new(),
destinations,
}
}
pub fn attach_hook_status(plan: &mut InstallationPlan, paths: &StorePaths) -> DaloResult<()> {
let hooks = crate::hook::list(paths)?.hooks;
attach_hook_status_from_report(plan, &hooks);
Ok(())
}
pub fn attach_hook_status_from_report(plan: &mut InstallationPlan, hooks: &[HookStatusReport]) {
plan.hooks = hooks.to_vec();
for destination in &mut plan.destinations {
for target in &mut destination.logical_targets {
for plugin in &mut target.plugins {
let prefix = format!("{}#hook:", plugin.source_ref);
for status in plan
.hooks
.iter()
.filter(|status| status.hook.source_ref.starts_with(&prefix))
{
let requirement = match status.hook.descriptor.requirement {
HookRequirement::Required => MemberRequirement::Required,
HookRequirement::Optional => MemberRequirement::Optional,
};
let provider = match target.id.as_str() {
"codex" => Some(HookProvider::Codex),
"claude" => Some(HookProvider::Claude),
_ => None,
};
let supported = provider.is_some_and(|provider| {
crate::hook::provider_supports_descriptor(provider, &status.hook.descriptor)
});
let suppressed = matches!(
plugin.state,
TargetPluginState::Declined | TargetPluginState::Shadowed
);
let optional_omit = requirement == MemberRequirement::Optional
&& status.hook.descriptor.fallback == Some(crate::hook::HookFallback::Omit);
let (canonical_state, state, compatibility, blocker, remediation) = if status
.state
== HookTrustState::Ready
&& supported
{
(
PluginComponentState::Active,
TargetComponentState::Active,
if status.hook.descriptor.subject == crate::hook::HookSubject::Session {
PlanCompatibility::Exact
} else {
PlanCompatibility::Mapped
},
None,
None,
)
} else if !supported && optional_omit {
(
PluginComponentState::Active,
TargetComponentState::IntentionallyOmitted,
PlanCompatibility::Unsupported,
None,
None,
)
} else {
let (source, remediation) = match status.state {
HookTrustState::PendingApproval => (
PlanBlockerSource::MissingApproval,
Some(format!("dalo approve hook {}", status.hook.source_ref)),
),
HookTrustState::ToolUnavailable => (
PlanBlockerSource::MissingApproval,
Some(format!("dalo approve tool {}", status.hook.tool_source_ref)),
),
HookTrustState::HashDrift => (
PlanBlockerSource::Drift,
Some(format!("dalo hook show {}", status.hook.source_ref)),
),
HookTrustState::Ready => (PlanBlockerSource::UnsupportedBehavior, None),
};
(
PluginComponentState::Blocked,
TargetComponentState::Blocked,
PlanCompatibility::Blocked,
Some(PlanBlocker {
source,
message: if supported {
status.diagnostic.clone()
} else {
format!(
"target `{}` cannot preserve required hook `{}`",
target.id, status.hook.source_ref
)
},
}),
remediation,
)
};
if !suppressed
&& requirement == MemberRequirement::Required
&& let Some(blocker) = blocker.clone()
{
plugin.blockers.push(blocker);
}
plugin.components.push(TargetComponentPlan {
reference: status.hook.source_ref.clone(),
requirement,
canonical_state,
state: if suppressed {
if plugin.state == TargetPluginState::Shadowed {
TargetComponentState::Shadowed
} else {
TargetComponentState::IntentionallyOmitted
}
} else {
state
},
compatibility,
authored_fallback: optional_omit.then(|| "omit".to_owned()),
selected_fallback: (!supported && optional_omit).then(|| "omit".to_owned()),
proposed_artifact: match target.id.as_str() {
"codex" => "~/.codex/hooks.json (Dalo-owned hook groups)",
"claude" => "~/.claude/settings.json (Dalo-owned hook groups)",
_ => "no verified native hook sidecar",
}
.to_owned(),
blocker: if suppressed { None } else { blocker },
remediation,
});
}
plugin
.components
.sort_by(|left, right| left.reference.cmp(&right.reference));
plugin
.blockers
.sort_by(|left, right| left.message.cmp(&right.message));
plugin.blockers.dedup();
if plugin.state == TargetPluginState::Active && !plugin.blockers.is_empty() {
plugin.state = TargetPluginState::Blocked;
plugin.compatibility = PlanCompatibility::Blocked;
}
}
}
}
}
pub fn attach_tool_status(plan: &mut InstallationPlan, paths: &StorePaths) -> DaloResult<()> {
let tools = crate::tool::list(paths)?.tools;
attach_tool_status_from_report(plan, &tools);
Ok(())
}
pub fn attach_tool_status_from_report(plan: &mut InstallationPlan, tools: &[ToolStatusReport]) {
plan.tools = tools.to_vec();
for destination in &mut plan.destinations {
for target in &mut destination.logical_targets {
for plugin in &mut target.plugins {
let prefix = format!("{}#tool:", plugin.source_ref);
for status in plan
.tools
.iter()
.filter(|status| status.tool.source_ref.starts_with(&prefix))
{
let requirement = match status.tool.availability {
crate::plugin::ToolAvailability::Required => MemberRequirement::Required,
crate::plugin::ToolAvailability::Optional => MemberRequirement::Optional,
};
let (canonical_state, mut component_state, compatibility, blocker, remediation) =
tool_plan_facts(status);
let suppressed = matches!(
plugin.state,
TargetPluginState::Declined | TargetPluginState::Shadowed
);
if plugin.state == TargetPluginState::Declined {
component_state = TargetComponentState::IntentionallyOmitted;
} else if plugin.state == TargetPluginState::Shadowed {
component_state = TargetComponentState::Shadowed;
}
if !suppressed
&& requirement == MemberRequirement::Required
&& let Some(blocker) = blocker.clone()
{
plugin.blockers.push(blocker);
}
plugin.components.push(TargetComponentPlan {
reference: status.tool.source_ref.clone(),
requirement,
canonical_state,
state: component_state,
compatibility,
authored_fallback: None,
selected_fallback: None,
proposed_artifact: status.staged_path.as_ref().map_or_else(
|| format!("immutable tool root sha256:{}", status.tool.contract_hash),
|path| path.display().to_string(),
),
blocker: if suppressed { None } else { blocker },
remediation,
});
}
plugin
.components
.sort_by(|left, right| left.reference.cmp(&right.reference));
plugin
.blockers
.sort_by(|left, right| left.message.cmp(&right.message));
plugin.blockers.dedup();
if plugin.state == TargetPluginState::Active && !plugin.blockers.is_empty() {
plugin.state = TargetPluginState::Blocked;
plugin.compatibility = PlanCompatibility::Blocked;
} else if plugin.state == TargetPluginState::Active
&& plugin.components.iter().any(|component| {
component.requirement == MemberRequirement::Optional
&& component.state != TargetComponentState::Active
})
{
plugin.state = TargetPluginState::Degraded;
}
}
}
}
}
fn tool_plan_facts(
status: &ToolStatusReport,
) -> (
PluginComponentState,
TargetComponentState,
PlanCompatibility,
Option<PlanBlocker>,
Option<String>,
) {
let (canonical, state, compatibility, source, remediation) = match status.state {
ToolState::Ready => (
PluginComponentState::Active,
TargetComponentState::Active,
PlanCompatibility::Exact,
None,
None,
),
ToolState::PendingApproval | ToolState::Revoked | ToolState::ApprovedNotStaged => (
PluginComponentState::PendingApproval,
TargetComponentState::PendingApproval,
PlanCompatibility::Blocked,
Some(PlanBlockerSource::MissingApproval),
Some(format!("dalo approve tool {}", status.tool.source_ref)),
),
ToolState::HashDrift | ToolState::AuditFailure => (
PluginComponentState::Blocked,
TargetComponentState::Blocked,
PlanCompatibility::Blocked,
Some(PlanBlockerSource::Drift),
Some(format!("dalo tool audit {}", status.tool.source_ref)),
),
ToolState::RuntimeMissing | ToolState::PlatformMismatch => (
PluginComponentState::Blocked,
TargetComponentState::Blocked,
PlanCompatibility::Unsupported,
Some(PlanBlockerSource::UnsupportedBehavior),
None,
),
};
let blocker = source.map(|source| PlanBlocker {
source,
message: status.diagnostic.clone(),
});
(canonical, state, compatibility, blocker, remediation)
}
fn destination_plan(
destination: &MaterializationDirState,
plugins: &PluginResolution,
inventories: &[SourceInventory],
active_skills: Option<&[crate::resolver::ResolvedSkill]>,
operations: &[MaterializeOperation],
target_filter: Option<&str>,
) -> Option<DestinationPlan> {
let mut logical_targets = destination
.logical_targets
.iter()
.filter(|target| target_filter.is_none_or(|filter| target.as_str() == filter))
.map(|target| {
logical_target_plan(
target,
plugins,
inventories,
active_skills,
operations,
&destination.path,
)
})
.collect::<Vec<_>>();
if logical_targets.is_empty() {
return None;
}
logical_targets.sort_by(|left, right| left.id.cmp(&right.id));
let mut portable_operations = operations
.iter()
.filter(|operation| operation.link_path.parent() == Some(destination.path.as_path()))
.cloned()
.collect::<Vec<_>>();
portable_operations.sort_by(|left, right| left.link_path.cmp(&right.link_path));
Some(DestinationPlan {
path: destination.path.clone(),
logical_targets,
portable_operations,
})
}
fn logical_target_plan(
target: &str,
plugins: &PluginResolution,
inventories: &[SourceInventory],
active_skills: Option<&[crate::resolver::ResolvedSkill]>,
operations: &[MaterializeOperation],
destination: &Path,
) -> LogicalTargetPlan {
let mut target_plugins = plugins
.plugins
.iter()
.map(|plugin| {
target_plugin_plan(
target,
plugin,
inventories,
active_skills,
operations,
destination,
)
})
.collect::<Vec<_>>();
target_plugins.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
LogicalTargetPlan {
id: target.to_owned(),
verification_baseline: verification_baseline(target).to_owned(),
plugins: target_plugins,
}
}
fn target_plugin_plan(
target: &str,
plugin: &crate::plugin::ResolvedPlugin,
inventories: &[SourceInventory],
active_skills: Option<&[crate::resolver::ResolvedSkill]>,
operations: &[MaterializeOperation],
destination: &Path,
) -> TargetPluginPlan {
let mut blockers = Vec::new();
let mut components = plugin
.members
.iter()
.map(|member| {
component_plan(
target,
member,
inventories,
active_skills,
operations,
destination,
)
})
.collect::<Vec<_>>();
components.sort_by(|left, right| left.reference.cmp(&right.reference));
for dependency in &plugin.dependencies {
if dependency.requirement == crate::plugin::DependencyRequirement::Required
&& dependency.state != crate::plugin::PluginDependencyState::Selected
{
blockers.push(PlanBlocker {
source: PlanBlockerSource::MissingDependency,
message: format!(
"required dependency `{}` is {}",
dependency.reference, dependency.state
)
.to_lowercase(),
});
}
}
for component in &components {
if component.requirement == MemberRequirement::Required
&& let Some(blocker) = &component.blocker
{
blockers.push(blocker.clone());
}
}
if plugin.state == PluginState::Declined {
for component in &mut components {
component.state = TargetComponentState::IntentionallyOmitted;
}
blockers.push(PlanBlocker {
source: PlanBlockerSource::PolicyDecision,
message: "selected plugin is declined by user-local policy".to_owned(),
});
}
blockers.sort_by(|left, right| left.message.cmp(&right.message));
blockers.dedup();
let optional_degradation = components.iter().any(|component| {
component.requirement != MemberRequirement::Required
&& component.compatibility >= PlanCompatibility::GuidanceOnly
});
let state = match plugin.state {
PluginState::Shadowed => TargetPluginState::Shadowed,
PluginState::Declined => TargetPluginState::Declined,
PluginState::Blocked => TargetPluginState::Blocked,
PluginState::Selected if !blockers.is_empty() => TargetPluginState::Blocked,
PluginState::Selected if optional_degradation => TargetPluginState::Degraded,
PluginState::Selected => TargetPluginState::Active,
};
let compatibility = if matches!(
state,
TargetPluginState::Blocked | TargetPluginState::Declined
) {
PlanCompatibility::Blocked
} else {
components
.iter()
.filter(|component| component.requirement == MemberRequirement::Required)
.map(|component| component.compatibility)
.max()
.unwrap_or(PlanCompatibility::Exact)
};
TargetPluginPlan {
source_ref: plugin.source_ref.clone(),
origins: plugin.origins.clone(),
policies: plugin.policies.clone(),
dependencies: plugin.dependencies.clone(),
state,
compatibility,
components,
blockers,
}
}
fn component_plan(
target: &str,
member: &crate::plugin::ResolvedPluginMember,
inventories: &[SourceInventory],
active_skills: Option<&[crate::resolver::ResolvedSkill]>,
operations: &[MaterializeOperation],
destination: &Path,
) -> TargetComponentPlan {
let mut compatibility = canonical_compatibility(member.state);
let mut blocker = canonical_blocker(member);
let mut remediation = canonical_remediation(member);
let mut selected_fallback = None;
let proposed_artifact = if member.reference.starts_with("skill:") {
if let Some(identity) = &member.resolved_ref {
let operation = match active_skills {
Some(active_skills) => active_skills
.iter()
.find(|skill| skill.source_ref == *identity)
.and_then(|skill| {
operations.iter().find(|operation| {
operation.link_path == destination.join(&skill.slot_name)
})
}),
None => {
let slot = identity
.split_once(':')
.map_or(identity.as_str(), |(_, slot)| slot);
operations
.iter()
.find(|operation| operation.link_path == destination.join(slot))
}
};
if let Some(operation) = operation {
if operation.status == MaterializeOperationStatus::Blocked {
compatibility = PlanCompatibility::Blocked;
blocker = Some(PlanBlocker {
source: PlanBlockerSource::Conflict,
message: operation.reason.clone().unwrap_or_else(|| {
format!("target slot `{}` is blocked", operation.link_path.display())
}),
});
remediation =
Some("resolve the target slot conflict and run plan again".to_owned());
}
format!("portable skill link: {}", operation.link_path.display())
} else {
format!("portable skill `{identity}` (no target operation while inactive)")
}
} else {
"portable skill unavailable".to_owned()
}
} else if member.reference.starts_with("agent:") {
let agent = member.resolved_ref.as_deref().and_then(|identity| {
inventories
.iter()
.flat_map(|inventory| &inventory.agents)
.find(|agent| agent.source_ref == identity)
});
match (AgentProvider::parse(target).ok(), agent) {
(Some(provider), Some(agent)) if member.state == PluginComponentState::Active => {
let compilation = agent::compile_record(agent, provider);
compatibility = map_agent_compatibility(compilation.overall);
if compilation.not_targeted {
compatibility = PlanCompatibility::Unsupported;
}
if compatibility == PlanCompatibility::Blocked {
blocker = Some(PlanBlocker {
source: PlanBlockerSource::RequiredSafetyBoundary,
message: format!(
"{target} cannot preserve the canonical agent safety boundary"
),
});
remediation = Some(
"adjust the canonical agent boundary or choose a compatible target"
.to_owned(),
);
}
format!(
"read-only {} agent projection preview: {}",
provider.id(),
provider.filename(&agent.slot_name)
)
}
(None, _) if member.state == PluginComponentState::Active => {
compatibility = PlanCompatibility::Unsupported;
if let Some(fallback) = &member.fallback {
compatibility = PlanCompatibility::Mapped;
selected_fallback = Some(fallback.clone());
blocker = None;
remediation = None;
} else {
blocker = Some(PlanBlocker {
source: PlanBlockerSource::UnsupportedBehavior,
message: format!(
"target `{target}` has no isolated canonical-agent adapter"
),
});
remediation = Some(
"link a Codex or Claude target, or author an inline skill fallback"
.to_owned(),
);
}
"portable agent only; no native write in this slice".to_owned()
}
_ => "portable agent unavailable until its independent activation boundary succeeds"
.to_owned(),
}
} else {
compatibility = if member.state == PluginComponentState::Active {
PlanCompatibility::GuidanceOnly
} else if member.requirement == MemberRequirement::Required {
PlanCompatibility::Blocked
} else {
PlanCompatibility::GuidanceOnly
};
"independently managed instruction block; planner never enables it".to_owned()
};
TargetComponentPlan {
reference: member.reference.clone(),
requirement: member.requirement,
canonical_state: member.state,
state: target_component_state(member, compatibility, selected_fallback.is_some()),
compatibility,
authored_fallback: member.fallback.clone(),
selected_fallback,
proposed_artifact,
blocker,
remediation,
}
}
fn target_component_state(
member: &crate::plugin::ResolvedPluginMember,
compatibility: PlanCompatibility,
fallback_selected: bool,
) -> TargetComponentState {
if fallback_selected {
return TargetComponentState::Active;
}
match member.state {
PluginComponentState::PendingApproval => TargetComponentState::PendingApproval,
PluginComponentState::Shadowed => TargetComponentState::Shadowed,
PluginComponentState::Inactive | PluginComponentState::Available => {
TargetComponentState::Inactive
}
PluginComponentState::Active
if compatibility == PlanCompatibility::Unsupported
&& member.requirement != MemberRequirement::Required =>
{
TargetComponentState::IntentionallyOmitted
}
PluginComponentState::Active if compatibility < PlanCompatibility::Blocked => {
TargetComponentState::Active
}
PluginComponentState::Active
| PluginComponentState::Blocked
| PluginComponentState::Missing
| PluginComponentState::Ambiguous => TargetComponentState::Blocked,
}
}
fn canonical_compatibility(state: PluginComponentState) -> PlanCompatibility {
match state {
PluginComponentState::Active => PlanCompatibility::Exact,
PluginComponentState::Available | PluginComponentState::Inactive => {
PlanCompatibility::GuidanceOnly
}
PluginComponentState::PendingApproval
| PluginComponentState::Shadowed
| PluginComponentState::Blocked
| PluginComponentState::Missing
| PluginComponentState::Ambiguous => PlanCompatibility::Blocked,
}
}
fn canonical_blocker(member: &crate::plugin::ResolvedPluginMember) -> Option<PlanBlocker> {
let source = match member.state {
PluginComponentState::PendingApproval => PlanBlockerSource::MissingApproval,
PluginComponentState::Inactive if member.reference.starts_with("instruction:") => {
PlanBlockerSource::InactiveInstruction
}
PluginComponentState::Shadowed | PluginComponentState::Ambiguous => {
PlanBlockerSource::Conflict
}
PluginComponentState::Blocked => PlanBlockerSource::RequiredSafetyBoundary,
PluginComponentState::Missing => PlanBlockerSource::MalformedInput,
PluginComponentState::Active
| PluginComponentState::Available
| PluginComponentState::Inactive => return None,
};
Some(PlanBlocker {
source,
message: format!("component `{}` is {}", member.reference, member.state),
})
}
fn canonical_remediation(member: &crate::plugin::ResolvedPluginMember) -> Option<String> {
match member.state {
PluginComponentState::PendingApproval if member.reference.starts_with("skill:") => member
.resolved_ref
.as_ref()
.map(|identity| format!("run `dalo approve skill {identity}` after review")),
PluginComponentState::PendingApproval if member.reference.starts_with("agent:") => member
.resolved_ref
.as_ref()
.map(|identity| format!("run `dalo approve agent {identity}` after review")),
PluginComponentState::Inactive if member.reference.starts_with("instruction:") => Some(
"enable the instruction pack explicitly for its instruction file, then plan again"
.to_owned(),
),
PluginComponentState::Missing => {
Some("add the exact referenced component to its source".to_owned())
}
_ => None,
}
}
fn map_agent_compatibility(result: CompatibilityResult) -> PlanCompatibility {
match result {
CompatibilityResult::Exact => PlanCompatibility::Exact,
CompatibilityResult::Mapped => PlanCompatibility::Mapped,
CompatibilityResult::GuidanceOnly => PlanCompatibility::GuidanceOnly,
CompatibilityResult::Unsupported => PlanCompatibility::Unsupported,
CompatibilityResult::Blocked => PlanCompatibility::Blocked,
}
}
fn verification_baseline(target: &str) -> &'static str {
match target {
"codex" => "portable-skill-v1 + canonical-agent-codex-v1",
"claude" => "portable-skill-v1 + canonical-agent-claude-v1",
"openclaw" | "hermes" | "opencode" | "generic" => {
"portable-skill-v1; no verified agent adapter"
}
_ => "unknown target; portable skill path only",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::inventory::SkillDelivery;
use crate::plugin::ResolvedPluginMember;
use crate::source::SourceKind;
type BuildFromFacts = fn(
&Path,
&StateFile,
&PluginResolution,
&[SourceInventory],
&[MaterializeOperation],
Option<&str>,
) -> InstallationPlan;
fn active_skill(source_ref: &str, slot_name: &str) -> crate::resolver::ResolvedSkill {
crate::resolver::ResolvedSkill {
source_ref: source_ref.to_owned(),
slot_name: slot_name.to_owned(),
source_namespace: Some("company".to_owned()),
id: None,
source_id: "company".to_owned(),
source_kind: SourceKind::Team,
source_priority: 10,
path: PathBuf::from("/store/company/review"),
delivery: SkillDelivery::Direct,
compatibility: None,
binaries: Vec::new(),
local_override: false,
requires: Vec::new(),
}
}
#[test]
fn released_plan_and_status_attachment_apis_should_remain_callable() {
let _build_from_facts: BuildFromFacts = build_from_facts;
let _tool: fn(&mut InstallationPlan, &StorePaths) -> DaloResult<()> = attach_tool_status;
let _hook: fn(&mut InstallationPlan, &StorePaths) -> DaloResult<()> = attach_hook_status;
}
#[test]
fn generic_target_selects_authored_inline_fallback_for_active_agent() {
let member = ResolvedPluginMember {
reference: "agent:reviewer".to_owned(),
requirement: MemberRequirement::Required,
state: PluginComponentState::Active,
resolved_ref: Some("team:reviewer".to_owned()),
fallback: Some("skill:review".to_owned()),
};
let planned = component_plan(
"generic",
&member,
&[],
Some(&[]),
&[],
Path::new("/target"),
);
assert_eq!(planned.compatibility, PlanCompatibility::Mapped);
assert_eq!(planned.selected_fallback.as_deref(), Some("skill:review"));
assert!(planned.blocker.is_none());
}
#[test]
fn pending_required_skill_names_approval_boundary_and_remediation() {
let member = ResolvedPluginMember {
reference: "skill:core".to_owned(),
requirement: MemberRequirement::Required,
state: PluginComponentState::PendingApproval,
resolved_ref: Some("team:core".to_owned()),
fallback: None,
};
let planned = component_plan("codex", &member, &[], Some(&[]), &[], Path::new("/target"));
assert_eq!(planned.compatibility, PlanCompatibility::Blocked);
assert_eq!(
planned.blocker.as_ref().map(|blocker| blocker.source),
Some(PlanBlockerSource::MissingApproval)
);
assert_eq!(
planned.remediation.as_deref(),
Some("run `dalo approve skill team:core` after review")
);
}
#[test]
fn active_namespaced_skill_member_uses_its_materialized_slot_operation() {
let member = ResolvedPluginMember {
reference: "skill:review".to_owned(),
requirement: MemberRequirement::Required,
state: PluginComponentState::Active,
resolved_ref: Some("company:review".to_owned()),
fallback: None,
};
let operation = MaterializeOperation {
kind: materialize::MaterializeOperationKind::Create,
link_path: PathBuf::from("/target/company__review"),
desired_path: Some(PathBuf::from("/store/company/review")),
status: MaterializeOperationStatus::Planned,
reason: None,
};
let planned = component_plan(
"generic",
&member,
&[],
Some(&[active_skill("company:review", "company__review")]),
&[operation],
Path::new("/target"),
);
assert_eq!(planned.state, TargetComponentState::Active);
assert_eq!(planned.compatibility, PlanCompatibility::Exact);
assert_eq!(
planned.proposed_artifact,
"portable skill link: /target/company__review"
);
assert!(planned.blocker.is_none());
}
#[test]
fn namespaced_skill_member_reports_its_materialized_target_conflict() {
let member = ResolvedPluginMember {
reference: "skill:review".to_owned(),
requirement: MemberRequirement::Required,
state: PluginComponentState::Active,
resolved_ref: Some("company:review".to_owned()),
fallback: None,
};
let operation = MaterializeOperation {
kind: materialize::MaterializeOperationKind::Conflict,
link_path: PathBuf::from("/target/company__review"),
desired_path: Some(PathBuf::from("/store/company/review")),
status: MaterializeOperationStatus::Blocked,
reason: Some("foreign directory blocks target slot".to_owned()),
};
let planned = component_plan(
"generic",
&member,
&[],
Some(&[active_skill("company:review", "company__review")]),
&[operation],
Path::new("/target"),
);
assert_eq!(planned.state, TargetComponentState::Blocked);
assert_eq!(planned.compatibility, PlanCompatibility::Blocked);
assert_eq!(
planned.blocker,
Some(PlanBlocker {
source: PlanBlockerSource::Conflict,
message: "foreign directory blocks target slot".to_owned(),
})
);
assert_eq!(
planned.remediation.as_deref(),
Some("resolve the target slot conflict and run plan again")
);
}
#[test]
fn public_wrapper_keeps_non_namespaced_skill_operations_and_conflicts() {
let target = PathBuf::from("/target");
let state = StateFile {
materialization_dirs: vec![crate::store::MaterializationDirState {
path: target.clone(),
logical_targets: vec!["generic".to_owned()],
extra: Default::default(),
}],
..StateFile::empty()
};
let plugins = PluginResolution {
plugins: vec![crate::plugin::ResolvedPlugin {
source_ref: "local:review-plugin".to_owned(),
slot_name: "review-plugin".to_owned(),
id: None,
source_priority: 0,
package_hash: "package".to_owned(),
closure_hash: "closure".to_owned(),
origins: Vec::new(),
policies: Vec::new(),
state: crate::plugin::PluginState::Selected,
shadowed_by: None,
members: vec![ResolvedPluginMember {
reference: "skill:review".to_owned(),
requirement: MemberRequirement::Required,
state: PluginComponentState::Active,
resolved_ref: Some("local:review".to_owned()),
fallback: None,
}],
dependencies: Vec::new(),
blocking_reasons: Vec::new(),
}],
diagnostics: Vec::new(),
};
let create = MaterializeOperation {
kind: materialize::MaterializeOperationKind::Create,
link_path: target.join("review"),
desired_path: Some(PathBuf::from("/store/local/review")),
status: MaterializeOperationStatus::Planned,
reason: None,
};
let planned = build_from_facts(
Path::new("/store"),
&state,
&plugins,
&[],
std::slice::from_ref(&create),
None,
);
let planned_destination = &planned.destinations[0];
let planned_component = &planned_destination.logical_targets[0].plugins[0].components[0];
assert_eq!(planned_destination.portable_operations, vec![create]);
assert_eq!(planned_component.state, TargetComponentState::Active);
assert_eq!(
planned_component.proposed_artifact,
"portable skill link: /target/review"
);
let conflict = MaterializeOperation {
kind: materialize::MaterializeOperationKind::Conflict,
link_path: target.join("review"),
desired_path: Some(PathBuf::from("/store/local/review")),
status: MaterializeOperationStatus::Blocked,
reason: Some("foreign directory blocks target slot".to_owned()),
};
let blocked = build_from_facts(
Path::new("/store"),
&state,
&plugins,
&[],
std::slice::from_ref(&conflict),
None,
);
let blocked_destination = &blocked.destinations[0];
let blocked_plugin = &blocked_destination.logical_targets[0].plugins[0];
let blocked_component = &blocked_plugin.components[0];
let expected_blocker = PlanBlocker {
source: PlanBlockerSource::Conflict,
message: "foreign directory blocks target slot".to_owned(),
};
assert_eq!(blocked_destination.portable_operations, vec![conflict]);
assert_eq!(blocked_plugin.state, TargetPluginState::Blocked);
assert_eq!(blocked_component.state, TargetComponentState::Blocked);
assert_eq!(blocked_component.blocker, Some(expected_blocker.clone()));
assert_eq!(blocked_plugin.blockers, vec![expected_blocker]);
}
}