Skip to main content

qualia_core_db/semantic_instruments/
demo.rs

1//! Labelled demo instruments that seed an environment for demonstration
2//! and development. They are `si:Demo`, never Operational.
3
4use super::category::ContentCategory;
5use super::errors::InstrumentError;
6use super::manifest::{InstrumentManifest, COLLECTABLE_FORMAT_VERSION};
7use super::package::{build_collectable, CollectableParts};
8use super::visual::{demo_badge_10d, VISUAL_MEDIA_TYPE};
9
10const UNIT_N3: &str =
11    include_str!("../../../../core-ontologies/fixtures/semantic-instruments/positive-small.n3");
12const WATER_N3: &str = include_str!(
13    "../../../../core-ontologies/fixtures/semantic-instruments/positive-icon-dependency.n3"
14);
15const RPL_N3: &str = include_str!(
16    "../../../../core-ontologies/fixtures/semantic-instruments/positive-rpl-requirement.n3"
17);
18const NUTRITION_EVIDENCE_N3: &str = include_str!(
19    "../../../../core-ontologies/fixtures/semantic-instruments/demo-nutrition-evidence-review.n3"
20);
21const MEAL_CONSIDERATION_N3: &str = include_str!(
22    "../../../../core-ontologies/fixtures/semantic-instruments/demo-meal-consideration-review.n3"
23);
24const CLINICAL_MECHANISM_N3: &str = include_str!(
25    "../../../../core-ontologies/fixtures/semantic-instruments/demo-clinical-mechanism-review.n3"
26);
27
28/// One demo seed in the catalogue used to populate a development environment.
29#[derive(Debug, Clone, Copy)]
30pub struct DemoSeed {
31    pub slug: &'static str,
32    pub instrument_id: &'static str,
33    pub release_id: &'static str,
34    pub name: &'static str,
35    pub purpose: &'static str,
36    pub domain: &'static str,
37    pub entry_point: &'static str,
38    pub definition_n3: &'static str,
39}
40
41/// Built-in demo catalogue. Order is deterministic.
42pub fn demo_catalog() -> &'static [DemoSeed] {
43    &[
44        DemoSeed {
45            slug: "unit-convert",
46            instrument_id: "https://ns.webizen.org/demo/unit-convert",
47            release_id: "https://ns.webizen.org/demo/unit-convert/releases/1.0.0",
48            name: "Unit conversion (demo)",
49            purpose: "demonstration-and-development",
50            domain: "https://ns.webizen.org/demo/concepts/units",
51            entry_point: "assess",
52            definition_n3: UNIT_N3,
53        },
54        DemoSeed {
55            slug: "community-water",
56            instrument_id: "https://ns.webizen.org/demo/community-water",
57            release_id: "https://ns.webizen.org/demo/community-water/releases/1.0.0",
58            name: "Community water assessment (demo)",
59            purpose: "demonstration-and-development",
60            domain: "https://ns.webizen.org/demo/concepts/water-quality",
61            entry_point: "assess",
62            definition_n3: WATER_N3,
63        },
64        DemoSeed {
65            slug: "community-infra-rpl",
66            instrument_id: "https://ns.webizen.org/demo/community-infra-role",
67            release_id: "https://ns.webizen.org/demo/community-infra-role/releases/1.0.0",
68            name: "Community infrastructure role (demo)",
69            purpose: "demonstration-and-development",
70            domain: "https://ns.webizen.org/demo/concepts/community-infrastructure",
71            entry_point: "recognise",
72            definition_n3: RPL_N3,
73        },
74        DemoSeed {
75            slug: "nutrition-evidence-review",
76            instrument_id: "https://ns.webizen.org/demo/nutrition-evidence-review",
77            release_id: "https://ns.webizen.org/demo/nutrition-evidence-review/releases/1.0.0",
78            name: "Nutrition evidence review template (demo)",
79            purpose: "expert-authored-template-and-demonstration",
80            domain: "https://ns.webizen.org/food-evidence/",
81            entry_point: "assess",
82            definition_n3: NUTRITION_EVIDENCE_N3,
83        },
84        DemoSeed {
85            slug: "meal-consideration-review",
86            instrument_id: "https://ns.webizen.org/demo/meal-consideration-review",
87            release_id: "https://ns.webizen.org/demo/meal-consideration-review/releases/1.0.0",
88            name: "Meal consideration review template (demo)",
89            purpose: "expert-authored-template-and-demonstration",
90            domain: "https://ns.webizen.org/meal-evidence/",
91            entry_point: "assess",
92            definition_n3: MEAL_CONSIDERATION_N3,
93        },
94        DemoSeed {
95            slug: "clinical-mechanism-review",
96            instrument_id: "https://ns.webizen.org/demo/clinical-mechanism-review",
97            release_id: "https://ns.webizen.org/demo/clinical-mechanism-review/releases/1.0.0",
98            name: "Clinical nutrition mechanism review template (demo)",
99            purpose: "expert-authored-template-and-demonstration",
100            domain: "https://ns.webizen.org/clinical-nutrition/",
101            entry_point: "assess",
102            definition_n3: CLINICAL_MECHANISM_N3,
103        },
104    ]
105}
106
107/// Demo seed by slug.
108pub fn seed_by_slug(slug: &str) -> Option<&'static DemoSeed> {
109    demo_catalog().iter().find(|s| s.slug == slug)
110}
111
112fn manifest_for(seed: &DemoSeed) -> InstrumentManifest {
113    InstrumentManifest {
114        format_version: COLLECTABLE_FORMAT_VERSION.into(),
115        instrument_id: seed.instrument_id.into(),
116        release_id: seed.release_id.into(),
117        version: "1.0.0".into(),
118        name: seed.name.into(),
119        purpose: seed.purpose.into(),
120        content_category: ContentCategory::Demo,
121        prohibited_interpretation: "operational-clinical-or-legal-use".into(),
122        domain: seed.domain.into(),
123        ontology_reference: "https://ns.webizen.org/semantic-instrument/".into(),
124        entry_point: seed.entry_point.into(),
125        citation: "https://ns.webizen.org/demo/citations/seed-catalogue".into(),
126        honesty_notice: "Demo instrument for demonstration and development. Labelled seed. Not operational, clinical, or legal advice.".into(),
127        incomplete_input: "held".into(),
128        result_kind: "demo-claim".into(),
129        licence: "https://spdx.org/licenses/CC-BY-4.0.html".into(),
130        authored_by: "did:webizen:agent:demo-seed".into(),
131        accessible_text: seed.name.into(),
132        visual_media_type: VISUAL_MEDIA_TYPE.into(),
133        content_digest: String::new(),
134        extra: {
135            let mut extra = std::collections::BTreeMap::new();
136            extra.insert("slug".into(), serde_json::json!(seed.slug));
137            extra.insert("catalog".into(), serde_json::json!("si:Demo"));
138            if seed.slug == "nutrition-evidence-review"
139                || seed.slug == "meal-consideration-review"
140                || seed.slug == "clinical-mechanism-review"
141            {
142                extra.insert(
143                    "authoring_status".into(),
144                    serde_json::json!("template-awaiting-qualified-subject-matter-expert"),
145                );
146                extra.insert(
147                    "review_status".into(),
148                    serde_json::json!("awaiting-independent-review"),
149                );
150                extra.insert(
151                    "source_workbook".into(),
152                    serde_json::json!("food_organ_system_evidence_v2.xlsx"),
153                );
154            }
155            extra
156        },
157    }
158}
159
160/// Compile definition N3 to a small native `.q42` (path writer + RAII cleanup).
161#[cfg(not(target_arch = "wasm32"))]
162fn small_q42_from_n3(n3: &str) -> Result<Vec<u8>, InstrumentError> {
163    use crate::modalities::logic::n3_parser::{N3Event, N3Parser, Term};
164    use crate::q42::q42_volume::write_sorted_quins_volume;
165    use crate::{q_hash, NQuin};
166
167    fn term_hash(term: Term<'_>) -> u64 {
168        match term {
169            Term::Uri(s) | Term::Literal(s) | Term::Variable(s) | Term::Formula(s) => q_hash(s),
170        }
171    }
172
173    let mut quins = Vec::new();
174    let mut parser = N3Parser::new(n3);
175    parser
176        .parse_all(|event| {
177            if let N3Event::StaticTriple(t) = event {
178                let subject_s = match t.subject {
179                    Term::Uri(s) => s,
180                    _ => "",
181                };
182                if subject_s.starts_with('@') {
183                    return Ok(());
184                }
185                let subject = term_hash(t.subject);
186                let predicate = term_hash(t.predicate);
187                let object = term_hash(t.object);
188                let context = 0u64;
189                let metadata = 0u64;
190                quins.push(NQuin {
191                    subject,
192                    predicate,
193                    object,
194                    context,
195                    metadata,
196                    parity: NQuin::calculate_parity(subject, predicate, object, context, metadata),
197                });
198            }
199            Ok(())
200        })
201        .map_err(|e| InstrumentError::Graph(e.to_string()))?;
202    if quins.is_empty() {
203        return Err(InstrumentError::Graph("no triples in definition".into()));
204    }
205    let dir = tempfile::TempDir::new().map_err(|e| InstrumentError::Graph(e.to_string()))?;
206    let path = dir.path().join("instrument.q42");
207    write_sorted_quins_volume(&path, &quins).map_err(|e| InstrumentError::Graph(e.to_string()))?;
208    let bytes = std::fs::read(&path).map_err(|e| InstrumentError::Graph(e.to_string()))?;
209    drop(dir);
210    Ok(bytes)
211}
212
213/// Build one labelled demo collectable (HMC).
214pub fn build_demo(slug: &str) -> Result<Vec<u8>, InstrumentError> {
215    let seed = seed_by_slug(slug).ok_or(InstrumentError::MissingField("demo slug"))?;
216    let manifest = manifest_for(seed);
217    let small_q42 = {
218        #[cfg(not(target_arch = "wasm32"))]
219        {
220            Some(small_q42_from_n3(seed.definition_n3)?)
221        }
222        #[cfg(target_arch = "wasm32")]
223        {
224            None
225        }
226    };
227    build_collectable(CollectableParts {
228        hcf: super::package::hcf_from_manifest(&manifest),
229        definition_n3: seed.definition_n3.as_bytes().to_vec(),
230        visual_10d: demo_badge_10d().to_vec(),
231        small_q42,
232        manifest,
233    })
234}
235
236/// Build every demo in catalogue order.
237pub fn build_demo_catalog() -> Result<Vec<(String, Vec<u8>)>, InstrumentError> {
238    let mut out = Vec::with_capacity(demo_catalog().len());
239    for seed in demo_catalog() {
240        out.push((seed.slug.to_string(), build_demo(seed.slug)?));
241    }
242    Ok(out)
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use crate::semantic_instruments::package::open_collectable;
249
250    #[test]
251    fn catalog_has_labelled_demos() {
252        assert_eq!(demo_catalog().len(), 6);
253        for seed in demo_catalog() {
254            assert!(seed.definition_n3.contains("si:Demo"));
255        }
256    }
257
258    #[test]
259    fn each_demo_builds_and_opens() {
260        for seed in demo_catalog() {
261            let bytes = build_demo(seed.slug).expect(seed.slug);
262            let opened = open_collectable(&bytes).expect(seed.slug);
263            assert_eq!(opened.manifest.content_category, ContentCategory::Demo);
264            assert_eq!(opened.manifest.instrument_id, seed.instrument_id);
265            assert!(opened
266                .manifest
267                .honesty_notice
268                .to_ascii_lowercase()
269                .contains("demo"));
270            #[cfg(not(target_arch = "wasm32"))]
271            assert!(opened.small_q42.is_some(), "{}", seed.slug);
272        }
273    }
274
275    #[test]
276    fn nutrition_templates_require_expert_authoring_and_hold_incomplete_inputs() {
277        for slug in [
278            "nutrition-evidence-review",
279            "meal-consideration-review",
280            "clinical-mechanism-review",
281        ] {
282            let bytes = build_demo(slug).expect(slug);
283            let opened = open_collectable(&bytes).expect(slug);
284            assert_eq!(opened.manifest.entry_point, "assess");
285            assert_eq!(
286                opened.manifest.extra["authoring_status"],
287                "template-awaiting-qualified-subject-matter-expert"
288            );
289            assert_eq!(
290                opened.manifest.extra["review_status"],
291                "awaiting-independent-review"
292            );
293            let definition = std::str::from_utf8(&opened.definition_n3).expect("fixture is UTF-8");
294            assert!(definition.contains("holdsWhenMissing"));
295            assert!(definition.contains("prohibitedInterpretation"));
296            if slug == "clinical-mechanism-review" {
297                assert!(definition.contains("professional-view"));
298                assert!(definition.contains("mechanism-of-action"));
299                assert!(definition.contains("person-view"));
300            }
301        }
302    }
303
304    #[test]
305    fn tempfile_q42_is_cleaned_on_success() {
306        let bytes = build_demo("unit-convert").unwrap();
307        assert!(!bytes.is_empty());
308        // TempDir in small_q42_from_n3 drops before return; no leftover path is
309        // part of the collectable API. The HMC bytes are caller-owned.
310        let opened = open_collectable(&bytes).unwrap();
311        assert!(opened.bundle_digest.starts_with("sha256:"));
312    }
313}