Skip to main content

qualia_core_db/semantic_instruments/
evaluators_rights.rs

1//! Bounded evaluators for `identifier-stewardship-grant-scope`, `contextual-assertions-review`,
2//! `wellfair-fairness-rights-review`, and `licence-transition-readiness` (`QUALIADB-IMPLEMENTATION-ROADMAP.md`).
3
4use serde::{Deserialize, Serialize};
5
6use super::evaluators::{
7    finalize_report, CoreInstrumentKind, DiagnosticFinding, EvaluationOutcome,
8    InstrumentEvaluationReport,
9};
10use crate::q_hash;
11
12/// Input contract for `identifier-stewardship-grant-scope`.
13#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
14pub struct IdentifierStewardshipGrantScope {
15    pub subject_did: String,
16    pub invoking_agent_did: String,
17    pub granted_purpose: String,
18    pub requested_purpose: String,
19    pub has_domain_authority: bool,
20    #[serde(default)]
21    pub is_guardian_or_proxy: bool,
22    #[serde(default)]
23    pub competing_guardianship_claims: bool,
24    #[serde(default)]
25    pub subject_human_objected: bool,
26    #[serde(default)]
27    pub touches_biometrics_or_mindware: bool,
28    #[serde(default)]
29    pub explicit_biometric_consent: bool,
30}
31
32/// Evaluate `identifier-stewardship-grant-scope`.
33pub fn evaluate_identifier_grant_scope(
34    input: &IdentifierStewardshipGrantScope,
35    now_unix: u32,
36) -> InstrumentEvaluationReport {
37    let mut findings = Vec::new();
38    if input.subject_did.trim().is_empty()
39        || input.granted_purpose.trim().is_empty()
40        || input.requested_purpose.trim().is_empty()
41    {
42        findings.push(DiagnosticFinding {
43            code: "hro:IncompleteGrantScopeInput".into(),
44            outcome: EvaluationOutcome::Held,
45            message: "missing subject DID or declared purpose".into(),
46        });
47    } else {
48        if !input.has_domain_authority {
49            findings.push(DiagnosticFinding {
50                code: "hro:MissingDomainOrStewardshipAuthority".into(),
51                outcome: EvaluationOutcome::Failed,
52                message: "invoking agent lacks DID/namespace/domain authority".into(),
53            });
54        }
55        if input.subject_human_objected {
56            findings.push(DiagnosticFinding {
57                code: "hro:SubjectHumanObjected".into(),
58                outcome: EvaluationOutcome::Failed,
59                message: "affected human objected to disclosure or delegated action".into(),
60            });
61        }
62        if input.is_guardian_or_proxy && input.competing_guardianship_claims {
63            findings.push(DiagnosticFinding {
64                code: "hro:CompetingGuardianshipClaimsHeld".into(),
65                outcome: EvaluationOutcome::Held,
66                message: "competing guardianship claims require holding dependent disclosure for competent review".into(),
67            });
68        }
69        if !input
70            .granted_purpose
71            .trim()
72            .eq_ignore_ascii_case(input.requested_purpose.trim())
73        {
74            findings.push(DiagnosticFinding {
75                code: "hro:OutOfScopePurposeOrProfiling".into(),
76                outcome: EvaluationOutcome::Failed,
77                message: "requested purpose exceeds the scoped identifier grant".into(),
78            });
79        }
80        if input.touches_biometrics_or_mindware && !input.explicit_biometric_consent {
81            findings.push(DiagnosticFinding {
82                code: "hro:ProtectedBiometricsOrMindwareBoundary".into(),
83                outcome: EvaluationOutcome::Failed,
84                message: "biometrics and mindware require explicit scoped human consent".into(),
85            });
86        }
87    }
88    finalize_report(
89        CoreInstrumentKind::IdentifierStewardshipGrantScope,
90        q_hash(&input.subject_did),
91        findings,
92        now_unix,
93    )
94}
95
96/// Epistemic assertion category for `contextual-assertions-review`.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
98#[serde(rename_all = "snake_case")]
99pub enum AssertionKind {
100    #[default]
101    Observation,
102    Inference,
103    Allegation,
104    Attestation,
105    AdjudicatedFinding,
106}
107
108/// Input contract for `contextual-assertions-review`.
109#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
110pub struct ContextualAssertionsReview {
111    pub assertion_kind: AssertionKind,
112    #[serde(default)]
113    pub claimed_target_kind: Option<AssertionKind>,
114    pub distinct_root_sources: u32,
115    #[serde(default)]
116    pub dependent_inference_count: u32,
117    #[serde(default)]
118    pub has_human_adjudicator_did: bool,
119    #[serde(default)]
120    pub is_challenged: bool,
121    #[serde(default)]
122    pub challenge_preserved: bool,
123    #[serde(default)]
124    pub downstream_marked_for_review: bool,
125    pub scope_domain: String,
126    #[serde(default)]
127    pub collapses_to_universal_reputation_score: bool,
128}
129
130/// Evaluate `contextual-assertions-review`.
131pub fn evaluate_contextual_assertions(
132    input: &ContextualAssertionsReview,
133    now_unix: u32,
134) -> InstrumentEvaluationReport {
135    let mut findings = Vec::new();
136    let scope = input.scope_domain.trim().to_ascii_lowercase();
137    if input.collapses_to_universal_reputation_score
138        || scope == "universal"
139        || scope == "global_reputation"
140        || scope == "social_credit"
141    {
142        findings.push(DiagnosticFinding {
143            code: "hro:UniversalReputationScoreForbidden".into(),
144            outcome: EvaluationOutcome::Failed,
145            message: "universal human reputation scoring across contexts is forbidden".into(),
146        });
147    } else if scope.is_empty() || input.distinct_root_sources == 0 {
148        findings.push(DiagnosticFinding {
149            code: "hro:MissingScopeOrRootProvenance".into(),
150            outcome: EvaluationOutcome::Held,
151            message: "assertion review requires a bounded scope domain and root provenance source"
152                .into(),
153        });
154    }
155    if input.claimed_target_kind == Some(AssertionKind::Observation)
156        && input.assertion_kind != AssertionKind::Observation
157    {
158        findings.push(DiagnosticFinding {
159            code: "hro:CannotPromoteToObservation".into(),
160            outcome: EvaluationOutcome::Failed,
161            message: "inferences and allegations can never be promoted to direct observations"
162                .into(),
163        });
164    }
165    if matches!(
166        input.assertion_kind,
167        AssertionKind::Allegation | AssertionKind::Inference
168    ) && input.claimed_target_kind == Some(AssertionKind::AdjudicatedFinding)
169    {
170        if !input.has_human_adjudicator_did {
171            findings.push(DiagnosticFinding {
172                code: "hro:AutoPromotionToAdjudicatedFindingForbidden".into(),
173                outcome: EvaluationOutcome::Failed,
174                message: "allegation or inference cannot auto-promote to AdjudicatedFinding without a human adjudicator DID".into(),
175            });
176        }
177        if input.distinct_root_sources <= 1 && input.dependent_inference_count > 1 {
178            findings.push(DiagnosticFinding {
179                code: "hro:SingleSourceDependentInferenceSelfCorroboration".into(),
180                outcome: EvaluationOutcome::Failed,
181                message: "dependent inferences sharing a single root source do not constitute independent corroboration".into(),
182            });
183        }
184    }
185    if input.is_challenged {
186        if !input.challenge_preserved || !input.downstream_marked_for_review {
187            findings.push(DiagnosticFinding {
188                code: "hro:ChallengeSuppressionForbidden".into(),
189                outcome: EvaluationOutcome::Failed,
190                message: "challenges must be preserved alongside the assertion and mark downstream decisions for review".into(),
191            });
192        } else {
193            findings.push(DiagnosticFinding {
194                code: "hro:AssertionChallengedPendingReview".into(),
195                outcome: EvaluationOutcome::Held,
196                message: "assertion is under active challenge with downstream decisions held for review".into(),
197            });
198        }
199    }
200    finalize_report(
201        CoreInstrumentKind::ContextualAssertionsReview,
202        q_hash(&input.scope_domain),
203        findings,
204        now_unix,
205    )
206}
207
208/// The 6 normative dimensions of `wellfair-fairness-rights-review` (`FAIRNESS-AND-RIGHTS-REVIEW.md` ยง2).
209#[repr(u8)]
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
211#[serde(rename_all = "snake_case")]
212pub enum FairnessReviewDimension {
213    LegalAndAuthority = 1,
214    EthicalAndHumanAgency = 2,
215    EconomicAndMaterial = 3,
216    SocialAndParticipation = 4,
217    ResolutionAndRemedy = 5,
218    TemporalAndLifecycle = 6,
219}
220
221impl FairnessReviewDimension {
222    pub const ALL: [Self; 6] = [
223        Self::LegalAndAuthority,
224        Self::EthicalAndHumanAgency,
225        Self::EconomicAndMaterial,
226        Self::SocialAndParticipation,
227        Self::ResolutionAndRemedy,
228        Self::TemporalAndLifecycle,
229    ];
230
231    pub const fn code(self) -> &'static str {
232        match self {
233            Self::LegalAndAuthority => "wellfair:LegalAndAuthority",
234            Self::EthicalAndHumanAgency => "wellfair:EthicalAndHumanAgency",
235            Self::EconomicAndMaterial => "wellfair:EconomicAndMaterial",
236            Self::SocialAndParticipation => "wellfair:SocialAndParticipation",
237            Self::ResolutionAndRemedy => "wellfair:ResolutionAndRemedy",
238            Self::TemporalAndLifecycle => "wellfair:TemporalAndLifecycle",
239        }
240    }
241}
242
243/// Input contract for `wellfair-fairness-rights-review`.
244#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
245pub struct WellfairFairnessRightsReview {
246    pub review_scope_id: String,
247    pub dimension_outcomes: Vec<(FairnessReviewDimension, EvaluationOutcome)>,
248    pub has_independent_challenge_route: bool,
249    #[serde(default)]
250    pub collapses_dimensions_to_single_score: bool,
251}
252
253/// Evaluate `wellfair-fairness-rights-review` across all 6 dimensions without collapsing to a scalar.
254pub fn evaluate_wellfair_fairness_rights_review(
255    input: &WellfairFairnessRightsReview,
256    now_unix: u32,
257) -> InstrumentEvaluationReport {
258    let mut findings = Vec::new();
259    if input.collapses_dimensions_to_single_score {
260        findings.push(DiagnosticFinding {
261            code: "hro:CollapsedSingleFairnessScoreForbidden".into(),
262            outcome: EvaluationOutcome::Failed,
263            message: "fairness review dimensions must never be collapsed into a single numeric score"
264                .into(),
265        });
266    }
267    if input.review_scope_id.trim().is_empty() {
268        findings.push(DiagnosticFinding {
269            code: "hro:MissingReviewScope".into(),
270            outcome: EvaluationOutcome::Held,
271            message: "review unit requires a specific scope identifier".into(),
272        });
273    }
274    if !input.has_independent_challenge_route {
275        findings.push(DiagnosticFinding {
276            code: "hro:MissingIndependentChallengeRoute".into(),
277            outcome: EvaluationOutcome::Failed,
278            message: "affected humans must have an independent challenge and remedy route".into(),
279        });
280    }
281    for dim in FairnessReviewDimension::ALL {
282        match input.dimension_outcomes.iter().find(|(d, _)| *d == dim) {
283            Some((_, outcome)) => findings.push(DiagnosticFinding {
284                code: dim.code().into(),
285                outcome: *outcome,
286                message: format!("dimension {:?} evaluated as {}", dim, outcome.as_str()),
287            }),
288            None => findings.push(DiagnosticFinding {
289                code: dim.code().into(),
290                outcome: EvaluationOutcome::Held,
291                message: format!("dimension {:?} missing evidence; held", dim),
292            }),
293        }
294    }
295    finalize_report(
296        CoreInstrumentKind::WellfairFairnessRightsReview,
297        q_hash(&input.review_scope_id),
298        findings,
299        now_unix,
300    )
301}
302
303/// Input contract for `licence-transition-readiness`.
304#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
305pub struct LicenceTransitionReadiness {
306    pub project_id: String,
307    pub pool_funded_cents: i64,
308    pub required_obligation_cents: i64,
309    pub settled_verified_cents: i64,
310    #[serde(default)]
311    pub waived_obligation_cents: i64,
312    pub dependencies_compatible: bool,
313    pub unresolved_material_challenges: u32,
314    pub authorised_human_steward_did: Option<String>,
315}
316
317/// Evaluate `licence-transition-readiness` enforcing `Pool Funded != Contributor Paid`.
318pub fn evaluate_licence_transition_readiness(
319    input: &LicenceTransitionReadiness,
320    now_unix: u32,
321) -> InstrumentEvaluationReport {
322    let mut findings = Vec::new();
323    let steward_ok = input
324        .authorised_human_steward_did
325        .as_deref()
326        .map(str::trim)
327        .is_some_and(|s| !s.is_empty());
328    if !steward_ok {
329        findings.push(DiagnosticFinding {
330            code: "hro:MissingAuthorisedHumanSteward".into(),
331            outcome: EvaluationOutcome::Failed,
332            message: "licence transition requires an authorised human release steward DID".into(),
333        });
334    }
335    if !input.dependencies_compatible {
336        findings.push(DiagnosticFinding {
337            code: "hro:DependencyLicenceIncompatible".into(),
338            outcome: EvaluationOutcome::Held,
339            message: "dependency licensing authority is unresolved or incompatible".into(),
340        });
341    }
342    if input.unresolved_material_challenges > 0 {
343        findings.push(DiagnosticFinding {
344            code: "hro:UnresolvedMaterialChallenges".into(),
345            outcome: EvaluationOutcome::Held,
346            message: "unresolved material challenges block licence transition".into(),
347        });
348    }
349    let discharged = input
350        .settled_verified_cents
351        .saturating_add(input.waived_obligation_cents);
352    if input.required_obligation_cents > 0 && discharged < input.required_obligation_cents {
353        findings.push(DiagnosticFinding {
354            code: "hro:PoolFundedIsNotContributorPaid".into(),
355            outcome: EvaluationOutcome::Held,
356            message: format!(
357                "pool funded ({}) != contributor paid ({} verified + {} waived < {} required)",
358                input.pool_funded_cents,
359                input.settled_verified_cents,
360                input.waived_obligation_cents,
361                input.required_obligation_cents
362            ),
363        });
364    }
365    finalize_report(
366        CoreInstrumentKind::LicenceTransitionReadiness,
367        q_hash(&input.project_id),
368        findings,
369        now_unix,
370    )
371}