Skip to main content

qualia_core_db/foundation/
plane_feature_guard.rs

1//! Classifier & Symbolic Feature-Bag Plane Guard (Packet `IDF-05` — F6 §§1–16).
2//!
3//! Enforces strict plane separation (`Who`, `Claim`, `SpatiotemporalHandle`,
4//! `Instrument`, `Policy`) and closed `KeyRoleTag` validation before any feature
5//! vector or symbolic binding bag reaches a classifier, GNN, or policy engine.
6//!
7//! # Zero-Heap Guarantee
8//! All types and validators operate over borrowed slices (`&str`, `&[TaggedFeature]`)
9//! without heap allocation.
10
11/// Top-level ontological plane tag for every feature in a symbolic/classifier bag.
12#[repr(u8)]
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum PlaneTag {
15    /// `NaturalAgent` (`Who`) — living-SHACL non-`owl:Thing` selfhood plane.
16    Who = 0,
17    /// `Claim` / Opinion (`AssertionClaim`, `RoleCapacityGrant`, `RelianceRecord`, etc.).
18    Claim = 1,
19    /// `SpatiotemporalHandle` (`DNI`, `USRI`, `QRC`, `RelationScopedLocator`, `EnvironmentPredicate`).
20    SpatiotemporalHandle = 2,
21    /// `Instrument` (`did:qi` key material, `Wallet`, `OnlineAccount`, `PasswordVerifier`,
22    /// `BiometricInstance`, `RAR`, `QSessionProof`, sensors).
23    Instrument = 3,
24    /// Deontic / governance policy plane.
25    Policy = 4,
26}
27
28/// Closed 7-variant key-role enumeration (F2 §12 / F6 §7).
29/// Any unrecognised role string MUST fail closed to [`FeatureGuardError::HeldUnknownKeyRole`].
30#[repr(u8)]
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum KeyRoleTag {
33    SessionAuthentication = 0,
34    RouteUpdate = 1,
35    TransportAead = 2,
36    QLinkEphemeralDh = 3,
37    ControllerSigning = 4,
38    CapabilityPresentation = 5,
39    DiscoveryPsk = 6,
40}
41
42impl KeyRoleTag {
43    /// Parse a key-role token from a string slice in zero-heap fashion.
44    /// Unknown roles fail closed with [`FeatureGuardError::HeldUnknownKeyRole`].
45    #[inline]
46    pub fn parse_token(token: &str) -> Result<Self, FeatureGuardError> {
47        match token {
48            "SessionAuthentication" => Ok(Self::SessionAuthentication),
49            "RouteUpdate" => Ok(Self::RouteUpdate),
50            "TransportAead" => Ok(Self::TransportAead),
51            "QLinkEphemeralDh" => Ok(Self::QLinkEphemeralDh),
52            "ControllerSigning" => Ok(Self::ControllerSigning),
53            "CapabilityPresentation" => Ok(Self::CapabilityPresentation),
54            "DiscoveryPsk" => Ok(Self::DiscoveryPsk),
55            _ => Err(FeatureGuardError::HeldUnknownKeyRole),
56        }
57    }
58}
59
60/// A single feature descriptor inside a classifier or symbolic-binding feature bag.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct TaggedFeature<'a> {
63    /// Feature or artifact identifier (e.g. `"Wallet"`, `"jane@bob.tld"`, `"did:q42:..."`).
64    pub name: &'a str,
65    /// Declared source plane tag (`None` triggers [`FeatureGuardError::MissingPlaneTag`]).
66    pub plane_tag: Option<PlaneTag>,
67    /// Optional target plane into which this feature is being projected or concatenated.
68    pub target_plane: Option<PlaneTag>,
69    /// Optional cryptographic key-role string token associated with the feature.
70    pub key_role_token: Option<&'a str>,
71    /// Optional expected key-role slot for the operation consuming this feature.
72    pub required_key_role: Option<KeyRoleTag>,
73    /// True when the feature represents an `owl:sameAs` equivalence assertion.
74    pub is_same_as_operator: bool,
75    /// True when the caller attempted to collapse `DNI`, `RAR`, and `QSessionProof`
76    /// into a single undifferentiated record.
77    pub collapses_dni_rar_qsession: bool,
78}
79
80impl<'a> TaggedFeature<'a> {
81    /// Construct a tagged feature on `plane_tag`.
82    pub const fn new(name: &'a str, plane_tag: Option<PlaneTag>) -> Self {
83        Self {
84            name,
85            plane_tag,
86            target_plane: None,
87            key_role_token: None,
88            required_key_role: None,
89            is_same_as_operator: false,
90            collapses_dni_rar_qsession: false,
91        }
92    }
93
94    /// Set the target projection/concatenation plane.
95    pub const fn with_target_plane(mut self, target: PlaneTag) -> Self {
96        self.target_plane = Some(target);
97        self
98    }
99
100    /// Attach a key-role token and optional expected slot role.
101    pub const fn with_key_role(
102        mut self,
103        role_token: &'a str,
104        required: Option<KeyRoleTag>,
105    ) -> Self {
106        self.key_role_token = Some(role_token);
107        self.required_key_role = required;
108        self
109    }
110
111    /// Mark this feature as an `owl:sameAs` assertion.
112    pub const fn with_same_as(mut self) -> Self {
113        self.is_same_as_operator = true;
114        self
115    }
116
117    /// Mark this feature as a collapsed `DNI` + `RAR` + `QSessionProof` record.
118    pub const fn with_collapsed_dni_rar_qsession(mut self) -> Self {
119        self.collapses_dni_rar_qsession = true;
120        self
121    }
122}
123
124/// Deterministic fail-closed errors emitted by [`validate_feature_bag`].
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum FeatureGuardError {
127    /// Feature has `plane_tag: None`.
128    MissingPlaneTag,
129    /// Non-`Who` feature (`Instrument`, `Claim`, `SpatiotemporalHandle`, or `Policy`)
130    /// was projected into or tagged as `PlaneTag::Who`.
131    CrossPlaneWhoFusion { source_plane: PlaneTag },
132    /// `owl:sameAs` was applied on `PlaneTag::Who`.
133    SameAsOnWhoPlane,
134    /// Unknown key-role string was supplied (fails closed to `Held`).
135    HeldUnknownKeyRole,
136    /// Key role does not match the required key-role slot.
137    KeyRoleMismatch {
138        actual: KeyRoleTag,
139        expected: KeyRoleTag,
140    },
141    /// `DNI`, `RAR`, and `QSessionProof` were collapsed into one record.
142    DniRarQSessionCollapsed,
143    /// A `did:q42:` Q42 Resource Coordinate was promoted to `PlaneTag::Who`.
144    QrcPromotedToWho,
145}
146
147/// Detect the intrinsic non-`Who` plane of known F6 §§8–15 artifacts so they can
148/// never be smuggled into `PlaneTag::Who` by mislabeling their `plane_tag`.
149fn intrinsic_non_who_plane(name: &str) -> Option<PlaneTag> {
150    if name.starts_with("did:q42:") || name.starts_with("<did:q42:") {
151        return Some(PlaneTag::SpatiotemporalHandle);
152    }
153    // F6 §8: Relation-scoped locator syntax (`jane@bob.tld`) is a SpatiotemporalHandle.
154    if name.contains('@') && name.contains('.') {
155        return Some(PlaneTag::SpatiotemporalHandle);
156    }
157    match name {
158        // F6 §§8, 10: Spatiotemporal handles & environment predicates
159        "RelationScopedLocator"
160        | "EnvironmentPredicate"
161        | "GeocachePlaceSecret"
162        | "DigitalNetworkIdentifier"
163        | "DNI"
164        | "QrcCoordinate" => Some(PlaneTag::SpatiotemporalHandle),
165
166        // F6 §§9, 10: Instruments, verifiers, biometrics, and hardware sensors
167        "OnlineAccount"
168        | "Wallet"
169        | "PasswordVerifier"
170        | "BiometricFamily"
171        | "BiometricInstance"
172        | "AiAgent"
173        | "MachineDevice"
174        | "BleProximitySensor"
175        | "AtmPresenceSensor"
176        | "RendezvousAuthorizationRecord"
177        | "QSessionProof" => Some(PlaneTag::Instrument),
178
179        // F6 §§11–15: Claims, role grants, accountability chains, aliases, counterpart graphs
180        "RoleCapacityGrant"
181        | "OrgRepresentativeBinding"
182        | "Organization"
183        | "AccountabilityArtifact"
184        | "AssertionClaim"
185        | "RuleBreachClaim"
186        | "RelationshipAssessmentClaim"
187        | "RelianceRecord"
188        | "AssumptionChain"
189        | "RootCauseBundle"
190        | "BlastRadiusMap"
191        | "PseudonymAlias"
192        | "CounterpartNQuinGraph" => Some(PlaneTag::Claim),
193
194        _ => None,
195    }
196}
197
198/// Validate a slice of [`TaggedFeature`] descriptors in zero-heap fashion.
199///
200/// Enforces:
201/// 1. Mandatory `PlaneTag` on every feature (`MissingPlaneTag`).
202/// 2. No collapse of `DNI`, `RAR`, and `QSessionProof` (`DniRarQSessionCollapsed`).
203/// 3. No `owl:sameAs` on `PlaneTag::Who` (`SameAsOnWhoPlane`).
204/// 4. No promotion of `did:q42:` QRC coordinates to `PlaneTag::Who` (`QrcPromotedToWho`).
205/// 5. No cross-plane concatenation or mislabeling of `Instrument`, `Claim`,
206///    `SpatiotemporalHandle`, or `Policy` features into `PlaneTag::Who` (`CrossPlaneWhoFusion`).
207/// 6. Closed-enum `KeyRoleTag` validation (`HeldUnknownKeyRole`) and slot role separation
208///    (`KeyRoleMismatch`, e.g. `QLinkEphemeralDh != TransportAead` and
209///    `RouteUpdate != SessionAuthentication`).
210pub fn validate_feature_bag(features: &[TaggedFeature<'_>]) -> Result<(), FeatureGuardError> {
211    for f in features {
212        let Some(plane) = f.plane_tag else {
213            return Err(FeatureGuardError::MissingPlaneTag);
214        };
215
216        if f.collapses_dni_rar_qsession {
217            return Err(FeatureGuardError::DniRarQSessionCollapsed);
218        }
219
220        let touches_who = plane == PlaneTag::Who || f.target_plane == Some(PlaneTag::Who);
221
222        if touches_who && (f.is_same_as_operator || f.name.contains("owl:sameAs")) {
223            return Err(FeatureGuardError::SameAsOnWhoPlane);
224        }
225
226        if touches_who && (f.name.starts_with("did:q42:") || f.name.starts_with("<did:q42:")) {
227            return Err(FeatureGuardError::QrcPromotedToWho);
228        }
229
230        if let Some(intrinsic) = intrinsic_non_who_plane(f.name) {
231            if plane == PlaneTag::Who {
232                return Err(FeatureGuardError::CrossPlaneWhoFusion {
233                    source_plane: intrinsic,
234                });
235            }
236        }
237
238        if f.target_plane == Some(PlaneTag::Who) && plane != PlaneTag::Who {
239            return Err(FeatureGuardError::CrossPlaneWhoFusion {
240                source_plane: plane,
241            });
242        }
243
244        if let Some(role_token) = f.key_role_token {
245            let role = KeyRoleTag::parse_token(role_token)?;
246            if let Some(expected) = f.required_key_role {
247                if role != expected {
248                    return Err(FeatureGuardError::KeyRoleMismatch {
249                        actual: role,
250                        expected,
251                    });
252                }
253            }
254        }
255    }
256    Ok(())
257}