merry-core 0.1.3

Core IDs, schemas, artifacts, events, and error contracts for the Merry agent runtime.
Documentation
//! Shared capability policy and approval scope contracts.
//!
//! These provider-neutral enums cross configuration, runtime admission,
//! process sandboxes, file tools, and UI boundaries.

use serde::{Deserialize, Deserializer, Serialize};
use std::fmt;

/// Three-state policy governing an external capability such as network access
/// or a host integration (`ssh-agent`, `gpg-agent`, `dbus`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CapabilityPolicy {
    /// Capability is hard-disabled; requests are rejected before review.
    Deny,
    /// Capability starts closed and may be requested through permission review.
    #[default]
    Ask,
    /// Capability is pre-authorized in the baseline without per-action review.
    Allow,
}

impl CapabilityPolicy {
    /// Returns the canonical kebab-case config/API spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Deny => "deny",
            Self::Ask => "ask",
            Self::Allow => "allow",
        }
    }

    /// Returns whether this capability is hard-blocked.
    #[must_use]
    pub const fn is_denied(self) -> bool {
        matches!(self, Self::Deny)
    }

    /// Returns whether this capability is pre-authorized without review.
    #[must_use]
    pub const fn is_preauthorized(self) -> bool {
        matches!(self, Self::Allow)
    }

    /// Returns whether actions may request this capability at runtime.
    #[must_use]
    pub const fn allows_requests(self) -> bool {
        !self.is_denied()
    }
}

impl fmt::Display for CapabilityPolicy {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for CapabilityPolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        match value.as_str() {
            "deny" => Ok(Self::Deny),
            "ask" => Ok(Self::Ask),
            "allow" => Ok(Self::Allow),
            other => Err(serde::de::Error::custom(format!(
                "invalid capability policy `{other}`; expected \"deny\", \"ask\", or \"allow\""
            ))),
        }
    }
}

/// Lifetime scope selected when approving a permission review request.
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum ApprovalScope {
    /// Authorizes strictly this single action and retains nothing afterward.
    #[default]
    Once,
    /// Retains eligible capabilities or narrow local-action classes in memory
    /// for the rest of the current runtime session.
    Session,
}

impl ApprovalScope {
    /// Returns the canonical kebab-case spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Once => "once",
            Self::Session => "session",
        }
    }
}

impl fmt::Display for ApprovalScope {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::{ApprovalScope, CapabilityPolicy};

    #[test]
    fn capability_policy_round_trips_canonical_strings() {
        for policy in [
            CapabilityPolicy::Deny,
            CapabilityPolicy::Ask,
            CapabilityPolicy::Allow,
        ] {
            let encoded = serde_json::to_string(&policy).expect("serialize");
            let decoded: CapabilityPolicy = serde_json::from_str(&encoded).expect("deserialize");
            assert_eq!(decoded, policy);
            assert_eq!(encoded, format!("\"{}\"", policy.as_str()));
        }
        assert!(serde_json::from_str::<CapabilityPolicy>("\"invalid\"").is_err());
    }

    #[test]
    fn approval_scope_defaults_to_once_and_round_trips() {
        assert_eq!(ApprovalScope::default(), ApprovalScope::Once);
        for scope in [ApprovalScope::Once, ApprovalScope::Session] {
            let encoded = serde_json::to_string(&scope).expect("serialize");
            let decoded: ApprovalScope = serde_json::from_str(&encoded).expect("deserialize");
            assert_eq!(decoded, scope);
            assert_eq!(encoded, format!("\"{}\"", scope.as_str()));
        }
    }
}