Skip to main content

qualia_cooperative_core/
taxonomy.rs

1//! Extensible taxonomy primitives — the base for the `AuthorityType` and `GuardianshipRole`
2//! vocabularies (see `docs/plans/adr-authority-attestation-guardianship-model.md`).
3//!
4//! Design constraint (Timothy, 2026-07-03): **must be extensible**. Terms are therefore *data*,
5//! not a closed Rust enum — a `Taxonomy` is an open registry of `TaxonomyTerm`s keyed by a stable
6//! URI id (which `q_hash`es cleanly and can be exported to / loaded from a cooperative ontology).
7//! New terms can be added at load-time (ontology) or runtime without changing these types. Each
8//! term carries an attribute bag so ABAC axioms and jurisdiction facets can grow without a schema
9//! migration. Well-known terms also get `const` ids so code references them without magic strings.
10
11use serde::{Deserialize, Serialize};
12
13/// A stable term identifier — a URI, e.g. `urn:qualia:guardianship-role:welfare:healthcare-proxy`.
14/// Kept as `String` (not an enum) so the vocabulary is open/extensible.
15pub type TermId = String;
16
17/// Selfhood vs personhood (Timothy): *selfhood* is inherent to the person and non-delegable by
18/// default (genome, biometrics, reproductive autonomy); *personhood* is the socio-legal
19/// relationship between an agent and societal structures, which may be delegated under a role.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
21#[serde(rename_all = "snake_case")]
22pub enum Sphere {
23    /// Inherent to the person — never shared/delegated unless a role explicitly, narrowly permits it.
24    Selfhood,
25    /// Socio-legal — delegable under an appropriate role.
26    #[default]
27    Personhood,
28}
29
30/// A single term in some taxonomy: a stable id, a human label, an optional grouping category
31/// (a coarser term id), and an open attribute bag for ABAC / ontological axioms.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct TaxonomyTerm {
34    pub id: TermId,
35    pub label: String,
36    /// Grouping/parent term id (a facet or category). `None` for top-level facets/categories.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub category: Option<TermId>,
39    #[serde(default)]
40    pub description: String,
41    /// Extensible axioms: `("sphere","selfhood")`, `("domains","health,welfare")`,
42    /// `("facet","temporal")`, jurisdiction hints, etc. Attribute keys are open by design.
43    #[serde(default)]
44    pub attributes: Vec<(String, String)>,
45}
46
47impl TaxonomyTerm {
48    /// Creates a new instance.
49    pub fn new(id: impl Into<TermId>, label: impl Into<String>) -> Self {
50        Self {
51            id: id.into(),
52            label: label.into(),
53            category: None,
54            description: String::new(),
55            attributes: Vec::new(),
56        }
57    }
58
59    /// `true` when in the category.
60    pub fn in_category(mut self, category: impl Into<TermId>) -> Self {
61        self.category = Some(category.into());
62        self
63    }
64
65    /// `true` when described.
66    pub fn described(mut self, description: impl Into<String>) -> Self {
67        self.description = description.into();
68        self
69    }
70
71    /// Builder — sets attr.
72    pub fn with_attr(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
73        self.attributes.push((key.into(), value.into()));
74        self
75    }
76
77    /// First attribute value for `key`, if any.
78    pub fn attr(&self, key: &str) -> Option<&str> {
79        self.attributes
80            .iter()
81            .find(|(k, _)| k == key)
82            .map(|(_, v)| v.as_str())
83    }
84
85    /// A comma-separated attribute parsed into its members (e.g. `domains = "health,welfare"`).
86    pub fn attr_list(&self, key: &str) -> Vec<String> {
87        self.attr(key)
88            .map(|v| {
89                v.split(',')
90                    .map(|s| s.trim().to_string())
91                    .filter(|s| !s.is_empty())
92                    .collect()
93            })
94            .unwrap_or_default()
95    }
96
97    /// The sphere this term operates in (attribute `sphere`), defaulting to Personhood.
98    pub fn sphere(&self) -> Sphere {
99        match self.attr("sphere") {
100            Some("selfhood") => Sphere::Selfhood,
101            _ => Sphere::Personhood,
102        }
103    }
104}
105
106/// An open registry of terms. Both `AuthorityType` and `GuardianshipRole` are `Taxonomy`s.
107/// Extensible: `insert` adds or replaces a term by id; nothing here is closed at compile time.
108#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Taxonomy {
110    terms: Vec<TaxonomyTerm>,
111}
112
113impl Taxonomy {
114    /// Creates a new instance.
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// Constructs from terms.
120    pub fn from_terms(terms: impl IntoIterator<Item = TaxonomyTerm>) -> Self {
121        let mut t = Self::new();
122        for term in terms {
123            t.insert(term);
124        }
125        t
126    }
127
128    /// Add or replace a term (idempotent by id). This is the extensibility point — a bundled
129    /// ontology, a jurisdiction pack, or a user extension can register additional terms.
130    pub fn insert(&mut self, term: TaxonomyTerm) {
131        if let Some(existing) = self.terms.iter_mut().find(|t| t.id == term.id) {
132            *existing = term;
133        } else {
134            self.terms.push(term);
135        }
136    }
137
138    /// Merge another taxonomy's terms into this one (later terms win on id collision).
139    pub fn extend_with(&mut self, other: &Taxonomy) {
140        for term in &other.terms {
141            self.insert(term.clone());
142        }
143    }
144
145    /// Gets a value.
146    pub fn get(&self, id: &str) -> Option<&TaxonomyTerm> {
147        self.terms.iter().find(|t| t.id == id)
148    }
149
150    /// `true` when it contains the item.
151    pub fn contains(&self, id: &str) -> bool {
152        self.get(id).is_some()
153    }
154
155    /// All direct members of a category (by category term id).
156    pub fn in_category(&self, category_id: &str) -> Vec<&TaxonomyTerm> {
157        self.terms
158            .iter()
159            .filter(|t| t.category.as_deref() == Some(category_id))
160            .collect()
161    }
162
163    /// All entries.
164    pub fn all(&self) -> &[TaxonomyTerm] {
165        &self.terms
166    }
167
168    /// Length.
169    pub fn len(&self) -> usize {
170        self.terms.len()
171    }
172
173    /// `true` when empty.
174    pub fn is_empty(&self) -> bool {
175        self.terms.is_empty()
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    #[test]
184    fn insert_get_and_replace_by_id() {
185        let mut tax = Taxonomy::new();
186        tax.insert(TaxonomyTerm::new("urn:x:a", "A").with_attr("v", "1"));
187        assert_eq!(tax.get("urn:x:a").unwrap().attr("v"), Some("1"));
188        // Idempotent replace.
189        tax.insert(TaxonomyTerm::new("urn:x:a", "A2").with_attr("v", "2"));
190        assert_eq!(tax.len(), 1);
191        assert_eq!(tax.get("urn:x:a").unwrap().label, "A2");
192        assert_eq!(tax.get("urn:x:a").unwrap().attr("v"), Some("2"));
193    }
194
195    #[test]
196    fn category_membership() {
197        let tax = Taxonomy::from_terms([
198            TaxonomyTerm::new("urn:cat", "Cat"),
199            TaxonomyTerm::new("urn:x:1", "One").in_category("urn:cat"),
200            TaxonomyTerm::new("urn:x:2", "Two").in_category("urn:cat"),
201            TaxonomyTerm::new("urn:y:1", "Other").in_category("urn:othercat"),
202        ]);
203        let members = tax.in_category("urn:cat");
204        assert_eq!(members.len(), 2);
205    }
206
207    #[test]
208    fn extensible_at_runtime_with_custom_term() {
209        // A user / ontology pack adds a term the core never hard-coded.
210        let mut tax = Taxonomy::new();
211        tax.insert(
212            TaxonomyTerm::new("urn:custom:role:beekeeping-steward", "Beekeeping Steward")
213                .in_category("urn:qualia:guardianship-role:socio-economic")
214                .with_attr("domains", "custodial,welfare")
215                .with_attr("sphere", "personhood"),
216        );
217        assert!(tax.contains("urn:custom:role:beekeeping-steward"));
218        assert_eq!(
219            tax.get("urn:custom:role:beekeeping-steward")
220                .unwrap()
221                .sphere(),
222            Sphere::Personhood
223        );
224    }
225
226    #[test]
227    fn attr_list_parses_comma_members() {
228        let t = TaxonomyTerm::new("urn:x", "X").with_attr("domains", "health, welfare ,legal");
229        assert_eq!(t.attr_list("domains"), vec!["health", "welfare", "legal"]);
230    }
231
232    #[test]
233    fn sphere_defaults_to_personhood() {
234        assert_eq!(TaxonomyTerm::new("urn:x", "X").sphere(), Sphere::Personhood);
235        assert_eq!(
236            TaxonomyTerm::new("urn:x", "X")
237                .with_attr("sphere", "selfhood")
238                .sphere(),
239            Sphere::Selfhood
240        );
241    }
242}