Skip to main content

nitijo_save/
lib.rs

1//! Veto-based policy checks for protecting everyday life during change.
2//!
3//! A [`ChangeProposal`] records evidence for six [`EverydayPrinciple`] values.
4//! [`ProtectionPolicy`] gives known deprivation priority over missing or
5//! favorable findings, so harm in one area cannot be averaged away.
6
7#![forbid(unsafe_code)]
8#![warn(missing_docs)]
9
10use std::collections::BTreeMap;
11use std::error::Error;
12use std::fmt;
13
14/// A condition needed to preserve ordinary, self-directed daily life.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub enum EverydayPrinciple {
17    /// Affected people receive understandable information and can consent.
18    InformedConsent,
19    /// Affected people retain a real alternative rather than a forced choice.
20    MeaningfulChoice,
21    /// Ordinary rhythms, relationships, and practices can continue.
22    RoutineContinuity,
23    /// Essential people, places, services, and communication remain reachable.
24    EssentialAccess,
25    /// The change can be undone or has a practical path back.
26    Reversibility,
27    /// Time, money, travel, cognitive, and emotional burdens are proportionate.
28    ProportionateBurden,
29}
30
31impl EverydayPrinciple {
32    /// Every principle in stable report order.
33    pub const ALL: [Self; 6] = [
34        Self::InformedConsent,
35        Self::MeaningfulChoice,
36        Self::RoutineContinuity,
37        Self::EssentialAccess,
38        Self::Reversibility,
39        Self::ProportionateBurden,
40    ];
41}
42
43/// The observed effect of a proposal on one principle.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Finding {
46    /// The proposal has an evidenced protection for this principle.
47    Protected,
48    /// A plausible problem remains and needs mitigation.
49    AtRisk,
50    /// The proposal removes or denies this part of everyday life.
51    Deprives,
52}
53
54/// A finding together with the evidence supporting it.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Assessment {
57    finding: Finding,
58    evidence: String,
59}
60
61impl Assessment {
62    /// Creates an assessment with non-blank evidence.
63    pub fn new(finding: Finding, evidence: impl Into<String>) -> Result<Self, ProtectionError> {
64        let evidence = evidence.into();
65        if evidence.trim().is_empty() {
66            return Err(ProtectionError::EmptyEvidence);
67        }
68        Ok(Self { finding, evidence })
69    }
70
71    /// Returns the finding.
72    pub const fn finding(&self) -> Finding {
73        self.finding
74    }
75
76    /// Returns the evidence text.
77    pub fn evidence(&self) -> &str {
78        &self.evidence
79    }
80}
81
82/// A named change and its principle assessments.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct ChangeProposal {
85    name: String,
86    assessments: BTreeMap<EverydayPrinciple, Assessment>,
87}
88
89impl ChangeProposal {
90    /// Creates an unassessed proposal with a non-blank name.
91    pub fn new(name: impl Into<String>) -> Result<Self, ProtectionError> {
92        let name = name.into();
93        if name.trim().is_empty() {
94            return Err(ProtectionError::EmptyProposalName);
95        }
96        Ok(Self {
97            name,
98            assessments: BTreeMap::new(),
99        })
100    }
101
102    /// Adds or replaces an assessment and returns the proposal for chaining.
103    pub fn assess(
104        mut self,
105        principle: EverydayPrinciple,
106        finding: Finding,
107        evidence: impl Into<String>,
108    ) -> Result<Self, ProtectionError> {
109        self.set_assessment(principle, finding, evidence)?;
110        Ok(self)
111    }
112
113    /// Adds or replaces an assessment in place.
114    pub fn set_assessment(
115        &mut self,
116        principle: EverydayPrinciple,
117        finding: Finding,
118        evidence: impl Into<String>,
119    ) -> Result<(), ProtectionError> {
120        self.assessments
121            .insert(principle, Assessment::new(finding, evidence)?);
122        Ok(())
123    }
124
125    /// Returns the proposal name.
126    pub fn name(&self) -> &str {
127        &self.name
128    }
129
130    /// Returns an assessment when one has been recorded.
131    pub fn assessment(&self, principle: EverydayPrinciple) -> Option<&Assessment> {
132        self.assessments.get(&principle)
133    }
134}
135
136/// The outcome of the everyday-life protection policy.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum ProtectionDecision {
139    /// At least one principle contains a known deprivation.
140    Reject,
141    /// No deprivation is known, but one or more principles lack evidence.
142    NeedsEvidence,
143    /// All principles are assessed, but one or more remain at risk.
144    Revise,
145    /// Every principle is assessed as protected.
146    Accept,
147}
148
149/// The strict, veto-based protection policy.
150#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
151pub struct ProtectionPolicy;
152
153impl ProtectionPolicy {
154    /// Evaluates a proposal.
155    ///
156    /// Known deprivation is checked first, followed by missing evidence, risk,
157    /// and finally full acceptance.
158    pub fn evaluate(proposal: &ChangeProposal) -> ProtectionReport {
159        let mut missing = Vec::new();
160        let mut at_risk = Vec::new();
161        let mut deprivations = Vec::new();
162
163        for principle in EverydayPrinciple::ALL {
164            match proposal.assessment(principle).map(Assessment::finding) {
165                None => missing.push(principle),
166                Some(Finding::Protected) => {}
167                Some(Finding::AtRisk) => at_risk.push(principle),
168                Some(Finding::Deprives) => deprivations.push(principle),
169            }
170        }
171
172        let decision = if !deprivations.is_empty() {
173            ProtectionDecision::Reject
174        } else if !missing.is_empty() {
175            ProtectionDecision::NeedsEvidence
176        } else if !at_risk.is_empty() {
177            ProtectionDecision::Revise
178        } else {
179            ProtectionDecision::Accept
180        };
181
182        ProtectionReport {
183            decision,
184            missing,
185            at_risk,
186            deprivations,
187        }
188    }
189}
190
191/// An explainable policy result with stable principle ordering.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct ProtectionReport {
194    decision: ProtectionDecision,
195    missing: Vec<EverydayPrinciple>,
196    at_risk: Vec<EverydayPrinciple>,
197    deprivations: Vec<EverydayPrinciple>,
198}
199
200impl ProtectionReport {
201    /// Returns the final decision.
202    pub const fn decision(&self) -> ProtectionDecision {
203        self.decision
204    }
205
206    /// Returns principles without an assessment.
207    pub fn missing(&self) -> &[EverydayPrinciple] {
208        &self.missing
209    }
210
211    /// Returns principles that need mitigation.
212    pub fn at_risk(&self) -> &[EverydayPrinciple] {
213        &self.at_risk
214    }
215
216    /// Returns principles containing known deprivation.
217    pub fn deprivations(&self) -> &[EverydayPrinciple] {
218        &self.deprivations
219    }
220}
221
222/// Invalid proposal or assessment input.
223#[derive(Debug, Clone, PartialEq, Eq)]
224pub enum ProtectionError {
225    /// The proposal name was blank.
226    EmptyProposalName,
227    /// Assessment evidence was blank.
228    EmptyEvidence,
229}
230
231impl fmt::Display for ProtectionError {
232    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
233        match self {
234            Self::EmptyProposalName => formatter.write_str("proposal name must not be blank"),
235            Self::EmptyEvidence => formatter.write_str("assessment evidence must not be blank"),
236        }
237    }
238}
239
240impl Error for ProtectionError {}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    fn fully_protected() -> ChangeProposal {
247        EverydayPrinciple::ALL
248            .into_iter()
249            .try_fold(
250                ChangeProposal::new("change").unwrap(),
251                |proposal, principle| {
252                    proposal.assess(principle, Finding::Protected, "verified evidence")
253                },
254            )
255            .unwrap()
256    }
257
258    #[test]
259    fn all_protected_is_accepted() {
260        let report = ProtectionPolicy::evaluate(&fully_protected());
261        assert_eq!(report.decision(), ProtectionDecision::Accept);
262        assert!(report.missing().is_empty());
263        assert!(report.at_risk().is_empty());
264        assert!(report.deprivations().is_empty());
265    }
266
267    #[test]
268    fn deprivation_is_a_veto_even_with_missing_evidence() {
269        let proposal = ChangeProposal::new("forced move")
270            .unwrap()
271            .assess(
272                EverydayPrinciple::MeaningfulChoice,
273                Finding::Deprives,
274                "no alternative is offered",
275            )
276            .unwrap();
277        let report = ProtectionPolicy::evaluate(&proposal);
278
279        assert_eq!(report.decision(), ProtectionDecision::Reject);
280        assert_eq!(
281            report.deprivations(),
282            &[EverydayPrinciple::MeaningfulChoice]
283        );
284        assert!(!report.missing().is_empty());
285    }
286
287    #[test]
288    fn incomplete_proposal_needs_evidence_in_stable_order() {
289        let proposal = ChangeProposal::new("draft").unwrap();
290        let report = ProtectionPolicy::evaluate(&proposal);
291
292        assert_eq!(report.decision(), ProtectionDecision::NeedsEvidence);
293        assert_eq!(report.missing(), &EverydayPrinciple::ALL);
294    }
295
296    #[test]
297    fn assessed_risk_requires_revision() {
298        let proposal = fully_protected()
299            .assess(
300                EverydayPrinciple::RoutineContinuity,
301                Finding::AtRisk,
302                "hours may change",
303            )
304            .unwrap();
305        let report = ProtectionPolicy::evaluate(&proposal);
306
307        assert_eq!(report.decision(), ProtectionDecision::Revise);
308        assert_eq!(report.at_risk(), &[EverydayPrinciple::RoutineContinuity]);
309    }
310
311    #[test]
312    fn replacing_a_finding_changes_the_decision() {
313        let mut proposal = fully_protected();
314        proposal
315            .set_assessment(
316                EverydayPrinciple::EssentialAccess,
317                Finding::Deprives,
318                "service becomes unreachable",
319            )
320            .unwrap();
321        assert_eq!(
322            ProtectionPolicy::evaluate(&proposal).decision(),
323            ProtectionDecision::Reject
324        );
325
326        proposal
327            .set_assessment(
328                EverydayPrinciple::EssentialAccess,
329                Finding::Protected,
330                "accessible transport is funded",
331            )
332            .unwrap();
333        assert_eq!(
334            ProtectionPolicy::evaluate(&proposal).decision(),
335            ProtectionDecision::Accept
336        );
337    }
338
339    #[test]
340    fn blank_names_and_evidence_are_rejected() {
341        assert_eq!(
342            ChangeProposal::new("  "),
343            Err(ProtectionError::EmptyProposalName)
344        );
345        assert_eq!(
346            Assessment::new(Finding::Protected, "\t"),
347            Err(ProtectionError::EmptyEvidence)
348        );
349    }
350}