Skip to main content

qualia_core_db/semantic_instruments/
rpl.rs

1//! Recognition of Prior Learning over the existing capability-gap kernel.
2//!
3//! Formal, prior-learning, experiential and peer-attested evidence are first-class
4//! held capabilities. Unauthorised equivalence never closes a gap. Unavailable
5//! evidence is unresolved, not unmet. An evaluator pass is not an award.
6
7use crate::modalities::capability_gap::{
8    capability_gap, learning_path_cost, requirements_met, MAX_CAP_NODES,
9};
10use crate::q_hash;
11use crate::semantic_instruments::attestation::{
12    issue_capability_award, CapabilityAward, InstrumentAttestation,
13};
14use crate::semantic_instruments::errors::InstrumentError;
15
16/// How a held capability was evidenced. All four bases count as held when available.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum EvidenceBasis {
19    Formal,
20    PriorLearning,
21    Experiential,
22    PeerAttested,
23}
24
25/// One evidence row. `capability` is an IRI hashed with [`q_hash`].
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct EvidenceItem {
28    pub capability: String,
29    pub basis: EvidenceBasis,
30    pub available: bool,
31    pub private: bool,
32}
33
34/// Honest gap report. `equivalent` is authorised closeMatch, never unauthorised.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct GapResult {
37    pub satisfied: Vec<String>,
38    pub equivalent: Vec<String>,
39    pub unresolved: Vec<String>,
40    pub unmet: Vec<String>,
41    pub learning_path_cost: Option<u32>,
42}
43
44/// Classify required IRIs against RPL evidence. `out_scratch` is the caller
45/// buffer for [`capability_gap`].
46pub fn evaluate_rpl(
47    required: &[String],
48    evidence: &[EvidenceItem],
49    authorised_equivalences: &[(String, String)],
50    unauthorised_equivalences: &[(String, String)],
51    prereq_edges: &[(String, String, u32)],
52    goal: Option<&str>,
53    out_scratch: &mut [u64],
54) -> Result<GapResult, InstrumentError> {
55    let req_h: Vec<u64> = required.iter().map(|iri| q_hash(iri)).collect();
56    let mut held_h = Vec::new();
57    let mut unresolved_h = Vec::new();
58    for item in evidence {
59        let h = q_hash(&item.capability);
60        if item.available {
61            push_unique(&mut held_h, h);
62        } else {
63            push_unique(&mut unresolved_h, h);
64        }
65    }
66    let auth_eq: Vec<(u64, u64)> = authorised_equivalences
67        .iter()
68        .map(|(r, h)| (q_hash(r), q_hash(h)))
69        .collect();
70
71    for (req_iri, held_iri) in unauthorised_equivalences {
72        let r = q_hash(req_iri);
73        let h = q_hash(held_iri);
74        if req_h.contains(&r) && held_h.contains(&h) && !is_held(r, &held_h, &auth_eq) {
75            return Err(InstrumentError::UnauthorisedEquivalence);
76        }
77    }
78
79    let _gap_n = capability_gap(&req_h, &held_h, &auth_eq, out_scratch);
80    let closed = requirements_met(&req_h, &held_h, &auth_eq);
81
82    let mut satisfied = Vec::new();
83    let mut equivalent = Vec::new();
84    let mut unresolved = Vec::new();
85    let mut unmet = Vec::new();
86    for (iri, &h) in required.iter().zip(req_h.iter()) {
87        if satisfied.contains(iri)
88            || equivalent.contains(iri)
89            || unresolved.contains(iri)
90            || unmet.contains(iri)
91        {
92            continue;
93        }
94        if held_h.contains(&h) {
95            satisfied.push(iri.clone());
96        } else if is_held(h, &held_h, &auth_eq) {
97            equivalent.push(iri.clone());
98        } else if unresolved_h.contains(&h) {
99            unresolved.push(iri.clone());
100        } else {
101            unmet.push(iri.clone());
102        }
103    }
104
105    let learning_path_cost = if prereq_edges.is_empty() {
106        None
107    } else {
108        path_cost(
109            required,
110            evidence,
111            prereq_edges,
112            goal,
113            &held_h,
114            closed,
115            &unmet,
116            &unresolved,
117        )
118    };
119
120    Ok(GapResult {
121        satisfied,
122        equivalent,
123        unresolved,
124        unmet,
125        learning_path_cost,
126    })
127}
128
129/// Issue only when an authorised issuer acts. A runner pass is not issuance.
130pub fn maybe_issue_award(
131    proposed_pass: bool,
132    issuer_authorised: bool,
133    award: CapabilityAward,
134    public_omit_private: bool,
135    evidence: &[EvidenceItem],
136) -> Result<InstrumentAttestation, InstrumentError> {
137    if proposed_pass && !issuer_authorised {
138        return Err(InstrumentError::EvaluatorPassIsNotIssuance);
139    }
140    if public_omit_private && evidence.iter().any(|item| item.private) {
141        return Err(InstrumentError::PrivateEvidence);
142    }
143    issue_capability_award(award)
144}
145
146fn is_held(cap: u64, held: &[u64], equivalences: &[(u64, u64)]) -> bool {
147    held.contains(&cap)
148        || equivalences
149            .iter()
150            .any(|&(req, h)| req == cap && held.contains(&h))
151}
152
153fn push_unique(ids: &mut Vec<u64>, id: u64) {
154    if !ids.contains(&id) {
155        ids.push(id);
156    }
157}
158
159fn path_cost(
160    required: &[String],
161    evidence: &[EvidenceItem],
162    prereq_edges: &[(String, String, u32)],
163    goal: Option<&str>,
164    held_h: &[u64],
165    closed: bool,
166    unmet: &[String],
167    unresolved: &[String],
168) -> Option<u32> {
169    let goal_iri = goal
170        .map(str::to_owned)
171        .or_else(|| unmet.first().cloned())
172        .or_else(|| unresolved.first().cloned())
173        .or_else(|| required.first().cloned())?;
174    let goal_h = q_hash(&goal_iri);
175    if closed || held_h.contains(&goal_h) {
176        return learning_path_cost_for(required, evidence, prereq_edges, goal_h, held_h)
177            .or(Some(0));
178    }
179    learning_path_cost_for(required, evidence, prereq_edges, goal_h, held_h)
180}
181
182fn learning_path_cost_for(
183    required: &[String],
184    evidence: &[EvidenceItem],
185    prereq_edges: &[(String, String, u32)],
186    goal_h: u64,
187    held_h: &[u64],
188) -> Option<u32> {
189    let mut nodes = Vec::new();
190    for iri in required {
191        push_unique(&mut nodes, q_hash(iri));
192    }
193    for item in evidence {
194        push_unique(&mut nodes, q_hash(&item.capability));
195    }
196    let mut edges = Vec::with_capacity(prereq_edges.len());
197    for (from, to, cost) in prereq_edges {
198        let f = q_hash(from);
199        let t = q_hash(to);
200        push_unique(&mut nodes, f);
201        push_unique(&mut nodes, t);
202        edges.push((f, t, *cost));
203    }
204    push_unique(&mut nodes, goal_h);
205    if nodes.len() > MAX_CAP_NODES {
206        return None;
207    }
208    learning_path_cost(&nodes, &edges, held_h, goal_h)
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    const FORMAL: &str = "cap:formalDegree";
216    const EXPERIENTIAL: &str = "cap:apprenticeship";
217    const WELDING: &str = "cap:welding";
218    const FAB: &str = "cap:fabrication";
219    const ROBOTICS: &str = "cap:robotics";
220    const DIGEST: &str = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
221
222    fn item(cap: &str, basis: EvidenceBasis, available: bool) -> EvidenceItem {
223        EvidenceItem {
224            capability: cap.into(),
225            basis,
226            available,
227            private: false,
228        }
229    }
230
231    fn sample_award() -> CapabilityAward {
232        CapabilityAward {
233            learner: "did:example:learner".into(),
234            assessment_release_id: "https://ns.webizen.org/demo/unit-convert/releases/1.0.0".into(),
235            content_digest: DIGEST.into(),
236            issuer: "did:example:issuer".into(),
237            capability: "https://ns.webizen.org/demo/concepts/units".into(),
238            issued_at: 1_700_000_000,
239            valid_until: 1_800_000_000,
240        }
241    }
242
243    #[test]
244    fn formal_evidence_satisfies() {
245        let required = vec![FORMAL.into()];
246        let evidence = [item(FORMAL, EvidenceBasis::Formal, true)];
247        let got =
248            evaluate_rpl(&required, &evidence, &[], &[], &[], None, &mut [0u64; 8]).expect("rpl");
249        assert_eq!(got.satisfied, vec![FORMAL.to_string()]);
250        assert!(got.equivalent.is_empty());
251        assert!(got.unresolved.is_empty());
252        assert!(got.unmet.is_empty());
253        assert_eq!(got.learning_path_cost, None);
254    }
255
256    #[test]
257    fn experiential_authorised_equivalence_satisfies_required_formal() {
258        let required = vec![FORMAL.into()];
259        let evidence = [item(EXPERIENTIAL, EvidenceBasis::Experiential, true)];
260        let auth = [(FORMAL.into(), EXPERIENTIAL.into())];
261        let got =
262            evaluate_rpl(&required, &evidence, &auth, &[], &[], None, &mut [0u64; 8]).expect("rpl");
263        assert!(got.satisfied.is_empty());
264        assert_eq!(got.equivalent, vec![FORMAL.to_string()]);
265        assert!(got.unmet.is_empty());
266        assert!(got.unresolved.is_empty());
267    }
268
269    #[test]
270    fn unauthorised_equivalence_errors() {
271        let required = vec![FORMAL.into()];
272        let evidence = [item(EXPERIENTIAL, EvidenceBasis::Experiential, true)];
273        let unauth = [(FORMAL.into(), EXPERIENTIAL.into())];
274        let err = evaluate_rpl(
275            &required,
276            &evidence,
277            &[],
278            &unauth,
279            &[],
280            None,
281            &mut [0u64; 8],
282        )
283        .expect_err("must fail closed");
284        assert_eq!(err, InstrumentError::UnauthorisedEquivalence);
285    }
286
287    #[test]
288    fn unavailable_evidence_is_unresolved_not_unmet() {
289        let required = vec![FORMAL.into()];
290        let evidence = [item(FORMAL, EvidenceBasis::PriorLearning, false)];
291        let got =
292            evaluate_rpl(&required, &evidence, &[], &[], &[], None, &mut [0u64; 8]).expect("rpl");
293        assert_eq!(got.unresolved, vec![FORMAL.to_string()]);
294        assert!(!got.unmet.contains(&FORMAL.to_string()));
295        assert!(got.satisfied.is_empty());
296    }
297
298    #[test]
299    fn learning_path_cost_some_when_edges_provided() {
300        let required = vec![ROBOTICS.into()];
301        let evidence = [item(WELDING, EvidenceBasis::PeerAttested, true)];
302        let edges = [
303            (WELDING.into(), FAB.into(), 2u32),
304            (FAB.into(), ROBOTICS.into(), 3u32),
305            (WELDING.into(), ROBOTICS.into(), 10u32),
306        ];
307        let got = evaluate_rpl(
308            &required,
309            &evidence,
310            &[],
311            &[],
312            &edges,
313            Some(ROBOTICS),
314            &mut [0u64; 8],
315        )
316        .expect("rpl");
317        assert_eq!(got.learning_path_cost, Some(5));
318        assert_eq!(got.unmet, vec![ROBOTICS.to_string()]);
319    }
320
321    #[test]
322    fn evaluator_pass_without_issuer_is_not_issuance() {
323        let err = maybe_issue_award(true, false, sample_award(), false, &[])
324            .expect_err("pass is not issuance");
325        assert_eq!(err, InstrumentError::EvaluatorPassIsNotIssuance);
326        let issued = maybe_issue_award(true, true, sample_award(), false, &[]).expect("issue");
327        assert_ne!(issued.award_subject, issued.assessment_release_id);
328    }
329
330    #[test]
331    fn private_evidence_blocked_on_public_award() {
332        let mut private = item(FORMAL, EvidenceBasis::Formal, true);
333        private.private = true;
334        let err = maybe_issue_award(true, true, sample_award(), true, &[private])
335            .expect_err("must omit private");
336        assert_eq!(err, InstrumentError::PrivateEvidence);
337    }
338}