nitijo-save 0.1.0

Veto-based policy checks for protecting everyday life during change
Documentation
//! Veto-based policy checks for protecting everyday life during change.
//!
//! A [`ChangeProposal`] records evidence for six [`EverydayPrinciple`] values.
//! [`ProtectionPolicy`] gives known deprivation priority over missing or
//! favorable findings, so harm in one area cannot be averaged away.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;

/// A condition needed to preserve ordinary, self-directed daily life.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EverydayPrinciple {
    /// Affected people receive understandable information and can consent.
    InformedConsent,
    /// Affected people retain a real alternative rather than a forced choice.
    MeaningfulChoice,
    /// Ordinary rhythms, relationships, and practices can continue.
    RoutineContinuity,
    /// Essential people, places, services, and communication remain reachable.
    EssentialAccess,
    /// The change can be undone or has a practical path back.
    Reversibility,
    /// Time, money, travel, cognitive, and emotional burdens are proportionate.
    ProportionateBurden,
}

impl EverydayPrinciple {
    /// Every principle in stable report order.
    pub const ALL: [Self; 6] = [
        Self::InformedConsent,
        Self::MeaningfulChoice,
        Self::RoutineContinuity,
        Self::EssentialAccess,
        Self::Reversibility,
        Self::ProportionateBurden,
    ];
}

/// The observed effect of a proposal on one principle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Finding {
    /// The proposal has an evidenced protection for this principle.
    Protected,
    /// A plausible problem remains and needs mitigation.
    AtRisk,
    /// The proposal removes or denies this part of everyday life.
    Deprives,
}

/// A finding together with the evidence supporting it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Assessment {
    finding: Finding,
    evidence: String,
}

impl Assessment {
    /// Creates an assessment with non-blank evidence.
    pub fn new(finding: Finding, evidence: impl Into<String>) -> Result<Self, ProtectionError> {
        let evidence = evidence.into();
        if evidence.trim().is_empty() {
            return Err(ProtectionError::EmptyEvidence);
        }
        Ok(Self { finding, evidence })
    }

    /// Returns the finding.
    pub const fn finding(&self) -> Finding {
        self.finding
    }

    /// Returns the evidence text.
    pub fn evidence(&self) -> &str {
        &self.evidence
    }
}

/// A named change and its principle assessments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangeProposal {
    name: String,
    assessments: BTreeMap<EverydayPrinciple, Assessment>,
}

impl ChangeProposal {
    /// Creates an unassessed proposal with a non-blank name.
    pub fn new(name: impl Into<String>) -> Result<Self, ProtectionError> {
        let name = name.into();
        if name.trim().is_empty() {
            return Err(ProtectionError::EmptyProposalName);
        }
        Ok(Self {
            name,
            assessments: BTreeMap::new(),
        })
    }

    /// Adds or replaces an assessment and returns the proposal for chaining.
    pub fn assess(
        mut self,
        principle: EverydayPrinciple,
        finding: Finding,
        evidence: impl Into<String>,
    ) -> Result<Self, ProtectionError> {
        self.set_assessment(principle, finding, evidence)?;
        Ok(self)
    }

    /// Adds or replaces an assessment in place.
    pub fn set_assessment(
        &mut self,
        principle: EverydayPrinciple,
        finding: Finding,
        evidence: impl Into<String>,
    ) -> Result<(), ProtectionError> {
        self.assessments
            .insert(principle, Assessment::new(finding, evidence)?);
        Ok(())
    }

    /// Returns the proposal name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns an assessment when one has been recorded.
    pub fn assessment(&self, principle: EverydayPrinciple) -> Option<&Assessment> {
        self.assessments.get(&principle)
    }
}

/// The outcome of the everyday-life protection policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtectionDecision {
    /// At least one principle contains a known deprivation.
    Reject,
    /// No deprivation is known, but one or more principles lack evidence.
    NeedsEvidence,
    /// All principles are assessed, but one or more remain at risk.
    Revise,
    /// Every principle is assessed as protected.
    Accept,
}

/// The strict, veto-based protection policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProtectionPolicy;

impl ProtectionPolicy {
    /// Evaluates a proposal.
    ///
    /// Known deprivation is checked first, followed by missing evidence, risk,
    /// and finally full acceptance.
    pub fn evaluate(proposal: &ChangeProposal) -> ProtectionReport {
        let mut missing = Vec::new();
        let mut at_risk = Vec::new();
        let mut deprivations = Vec::new();

        for principle in EverydayPrinciple::ALL {
            match proposal.assessment(principle).map(Assessment::finding) {
                None => missing.push(principle),
                Some(Finding::Protected) => {}
                Some(Finding::AtRisk) => at_risk.push(principle),
                Some(Finding::Deprives) => deprivations.push(principle),
            }
        }

        let decision = if !deprivations.is_empty() {
            ProtectionDecision::Reject
        } else if !missing.is_empty() {
            ProtectionDecision::NeedsEvidence
        } else if !at_risk.is_empty() {
            ProtectionDecision::Revise
        } else {
            ProtectionDecision::Accept
        };

        ProtectionReport {
            decision,
            missing,
            at_risk,
            deprivations,
        }
    }
}

/// An explainable policy result with stable principle ordering.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProtectionReport {
    decision: ProtectionDecision,
    missing: Vec<EverydayPrinciple>,
    at_risk: Vec<EverydayPrinciple>,
    deprivations: Vec<EverydayPrinciple>,
}

impl ProtectionReport {
    /// Returns the final decision.
    pub const fn decision(&self) -> ProtectionDecision {
        self.decision
    }

    /// Returns principles without an assessment.
    pub fn missing(&self) -> &[EverydayPrinciple] {
        &self.missing
    }

    /// Returns principles that need mitigation.
    pub fn at_risk(&self) -> &[EverydayPrinciple] {
        &self.at_risk
    }

    /// Returns principles containing known deprivation.
    pub fn deprivations(&self) -> &[EverydayPrinciple] {
        &self.deprivations
    }
}

/// Invalid proposal or assessment input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProtectionError {
    /// The proposal name was blank.
    EmptyProposalName,
    /// Assessment evidence was blank.
    EmptyEvidence,
}

impl fmt::Display for ProtectionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyProposalName => formatter.write_str("proposal name must not be blank"),
            Self::EmptyEvidence => formatter.write_str("assessment evidence must not be blank"),
        }
    }
}

impl Error for ProtectionError {}

#[cfg(test)]
mod tests {
    use super::*;

    fn fully_protected() -> ChangeProposal {
        EverydayPrinciple::ALL
            .into_iter()
            .try_fold(
                ChangeProposal::new("change").unwrap(),
                |proposal, principle| {
                    proposal.assess(principle, Finding::Protected, "verified evidence")
                },
            )
            .unwrap()
    }

    #[test]
    fn all_protected_is_accepted() {
        let report = ProtectionPolicy::evaluate(&fully_protected());
        assert_eq!(report.decision(), ProtectionDecision::Accept);
        assert!(report.missing().is_empty());
        assert!(report.at_risk().is_empty());
        assert!(report.deprivations().is_empty());
    }

    #[test]
    fn deprivation_is_a_veto_even_with_missing_evidence() {
        let proposal = ChangeProposal::new("forced move")
            .unwrap()
            .assess(
                EverydayPrinciple::MeaningfulChoice,
                Finding::Deprives,
                "no alternative is offered",
            )
            .unwrap();
        let report = ProtectionPolicy::evaluate(&proposal);

        assert_eq!(report.decision(), ProtectionDecision::Reject);
        assert_eq!(
            report.deprivations(),
            &[EverydayPrinciple::MeaningfulChoice]
        );
        assert!(!report.missing().is_empty());
    }

    #[test]
    fn incomplete_proposal_needs_evidence_in_stable_order() {
        let proposal = ChangeProposal::new("draft").unwrap();
        let report = ProtectionPolicy::evaluate(&proposal);

        assert_eq!(report.decision(), ProtectionDecision::NeedsEvidence);
        assert_eq!(report.missing(), &EverydayPrinciple::ALL);
    }

    #[test]
    fn assessed_risk_requires_revision() {
        let proposal = fully_protected()
            .assess(
                EverydayPrinciple::RoutineContinuity,
                Finding::AtRisk,
                "hours may change",
            )
            .unwrap();
        let report = ProtectionPolicy::evaluate(&proposal);

        assert_eq!(report.decision(), ProtectionDecision::Revise);
        assert_eq!(report.at_risk(), &[EverydayPrinciple::RoutineContinuity]);
    }

    #[test]
    fn replacing_a_finding_changes_the_decision() {
        let mut proposal = fully_protected();
        proposal
            .set_assessment(
                EverydayPrinciple::EssentialAccess,
                Finding::Deprives,
                "service becomes unreachable",
            )
            .unwrap();
        assert_eq!(
            ProtectionPolicy::evaluate(&proposal).decision(),
            ProtectionDecision::Reject
        );

        proposal
            .set_assessment(
                EverydayPrinciple::EssentialAccess,
                Finding::Protected,
                "accessible transport is funded",
            )
            .unwrap();
        assert_eq!(
            ProtectionPolicy::evaluate(&proposal).decision(),
            ProtectionDecision::Accept
        );
    }

    #[test]
    fn blank_names_and_evidence_are_rejected() {
        assert_eq!(
            ChangeProposal::new("  "),
            Err(ProtectionError::EmptyProposalName)
        );
        assert_eq!(
            Assessment::new(Finding::Protected, "\t"),
            Err(ProtectionError::EmptyEvidence)
        );
    }
}