1use qualia_core_db::modalities;
15use qualia_core_db::NQuin;
16use serde_json::{json, Value};
17use wasm_bindgen::prelude::*;
18
19mod session;
20
21const LATEST_PROTOCOL_VERSION: &str = "2025-11-25";
22const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18", "2025-03-26"];
23pub(crate) const MAX_INPUT_QUINS: usize = 4_096;
24pub(crate) const MAX_QUERY_RESULTS: usize = 512;
25pub(crate) const MAX_N3_EVENTS: usize = 512;
26
27#[wasm_bindgen]
32pub fn mcp_jsonrpc(message: &str) -> String {
33 let req: Value = match serde_json::from_str(message) {
34 Ok(value) => value,
35 Err(_) => return rpc_error(Value::Null, -32700, "Parse error"),
36 };
37
38 if req.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
39 return rpc_error(
40 req.get("id").cloned().unwrap_or(Value::Null),
41 -32600,
42 "Invalid Request",
43 );
44 }
45
46 let method = req.get("method").and_then(Value::as_str).unwrap_or("");
47 if req.get("id").is_none() {
48 return String::new();
49 }
50
51 let id = req.get("id").cloned().unwrap_or(Value::Null);
52 match method {
53 "initialize" => initialize(id, req.get("params")),
54 "ping" => rpc_ok(id, json!({})),
55 "tools/list" => rpc_ok(id, json!({ "tools": tool_catalog() })),
56 "tools/call" => {
57 let params = req.get("params").cloned().unwrap_or(Value::Null);
58 let name = params.get("name").and_then(Value::as_str).unwrap_or("");
59 let args = params
60 .get("arguments")
61 .cloned()
62 .unwrap_or_else(|| json!({}));
63 match call_tool(name, &args) {
64 Ok(result) => tool_result(id, result, false),
65 Err(message) => tool_result(id, json!({ "error": message }), true),
66 }
67 }
68 _ => rpc_error(id, -32601, "Method not found"),
69 }
70}
71
72#[wasm_bindgen]
74pub fn version() -> String {
75 env!("CARGO_PKG_VERSION").to_string()
76}
77
78fn initialize(id: Value, params: Option<&Value>) -> String {
79 let requested = params
80 .and_then(|p| p.get("protocolVersion"))
81 .and_then(Value::as_str);
82 let negotiated = requested
83 .filter(|version| SUPPORTED_PROTOCOL_VERSIONS.contains(version))
84 .unwrap_or(LATEST_PROTOCOL_VERSION);
85
86 rpc_ok(
87 id,
88 json!({
89 "protocolVersion": negotiated,
90 "capabilities": { "tools": { "listChanged": false } },
91 "serverInfo": {
92 "name": "webizen-lite-wasm",
93 "title": "Qualia Ontology MCP",
94 "version": env!("CARGO_PKG_VERSION")
95 },
96 "instructions": "Browser-local, read-only ontology parsing, bounded Quin queries, SHACL checks, and modal reasoning. u64 Quin fields are returned as decimal strings."
97 }),
98 )
99}
100
101fn call_tool(name: &str, args: &Value) -> Result<Value, String> {
102 match name {
103 "ontology_capabilities" => ontology_capabilities(),
104 "hash_iri" => hash_iri(args),
105 "parse_n3" => parse_n3(args),
106 "query_quins" => query_quins(args),
107 "validate_shacl" => validate_shacl(args),
108 "evaluate_deontic" => evaluate_deontic(args),
109 "evaluate_epistemic" => evaluate_epistemic(args),
110 "route_paraconsistent" => route_paraconsistent(args),
111 "evaluate_ltl" => evaluate_ltl(args),
112 "check_subsumption" => check_subsumption(args),
113 "deontic_govern" => deontic_govern(args),
114 "namespace_discovery_help" => namespace_discovery_help(args),
116 "catalog_summarize" => catalog_summarize(args),
117 "corpus_summarize" => corpus_summarize(args),
118 "resolve_dataset_urls" => resolve_dataset_urls(args),
119 "export_graph" => export_graph(args),
120 "load_graph" => session::load_graph(args),
122 "load_q42" => session::load_q42(args),
123 "load_yaml_ld_q42" => session::load_yaml_ld_q42(args),
124 "list_graphs" => session::list_graphs(args),
125 "unload_graph" => session::unload_graph(args),
126 "query_graph" => session::query_graph(args),
127 "query_sparql" => session::query_sparql(args),
128 "export_q42lite" => session::export_q42lite(args),
129 "compile_deontic_norms" => session::compile_deontic_norms(args),
130 "evaluate_deontic_session" => session::evaluate_deontic_session(args),
131 _ => Err(format!("unknown tool: {name}")),
132 }
133}
134
135fn namespace_discovery_help(args: &Value) -> Result<Value, String> {
137 let base = args
138 .get("baseUrl")
139 .and_then(Value::as_str)
140 .unwrap_or("https://ns.webcivics.net")
141 .trim_end_matches('/');
142 Ok(json!({
143 "profile": "wasm-ontology / webizen-lite-wasm",
144 "network": "none — fetch documents with the host HTTP client, then call parse_n3 / catalog_summarize",
145 "bootstrap": {
146 "llmsTxt": format!("{base}/llms.txt"),
147 "catalogJson": format!("{base}/catalog.json"),
148 "catalogTurtle": format!("{base}/catalog.ttl"),
149 "contextJsonLd": format!("{base}/context.jsonld"),
150 "aiUsePolicy": format!("{base}/ai-use-policy.json"),
151 "agentMcpGuide": format!("{base}/agent-mcp-guide.md"),
152 "agentLegislationGuide": format!("{base}/agent-legislation-guide.md"),
153 "agentConformance": format!("{base}/agent-conformance.md"),
154 "auLegislationCorpus": format!("{base}/au-legislation-corpus.json"),
155 "titleIndex": format!("{base}/search/title-index.json"),
156 "auTitleIndex": format!("{base}/search/au-title-index.json"),
157 "wasmLite": format!("{base}/wasm/webizen-lite/")
158 },
159 "urlContract": {
160 "html": format!("{base}/institutions/un/{{slug}}/"),
161 "n3": format!("{base}/institutions/un/{{slug}}.n3"),
162 "turtle": format!("{base}/institutions/un/{{slug}}.ttl"),
163 "jsonld": format!("{base}/institutions/un/{{slug}}.jsonld"),
164 "coreExample": format!("{base}/core/agency/"),
165 "directoryIndexes": [
166 format!("{base}/institutions/"),
167 format!("{base}/institutions/un/"),
168 format!("{base}/institutions/au-fed-legislation/")
169 ],
170 "notes": [
171 "Trailing slash marks the HTML documentation page.",
172 "Extension paths (.n3/.ttl/.jsonld) are machine RDF projections.",
173 "Directory paths list child instruments (no leaf .n3).",
174 "Older /ontologies/... URLs redirect to short paths.",
175 "Prefer title indexes for keyword discovery before loading large acts."
176 ]
177 },
178 "exportFormats": {
179 "jsonld": "Default for agents (application/ld+json)",
180 "rdfjson": "W3C RDF/JSON Note (application/rdf+json) for bots without JSON-LD context",
181 "turtle": "text/turtle",
182 "n3": "text/n3 — use when N3 logic/rules/variables must be preserved",
183 "yamlld": "YAML encoding of the same JSON-LD document model"
184 },
185 "logicLayers": {
186 "A_ground": "Ground RDF triples — any serialisation",
187 "B_as_data": "CML norms / LogicApplication as RDF (logicMode=as-data)",
188 "C_executable": "N3 rules or .q42 + evaluate_* tools — not full fidelity in pure RDF/JSON"
189 },
190 "recommendedAgentFlow": [
191 "1. GET ai-use-policy.json and llms.txt (policy first).",
192 "2. Load WASM; tools/call namespace_discovery_help.",
193 "3. GET catalog.json and/or au-legislation-corpus.json / search/*-index.json.",
194 "4. tools/call catalog_summarize or corpus_summarize with titleContains (offline).",
195 "5. Host GET preferred .n3 (or .q42 when published); prefer RDF over multi-MB HTML.",
196 "6. parse_n3 / query_quins / evaluate_deontic as needed; export_graph for bot-readable RDF.",
197 "7. Cite catalog canonicalUrl + official Register/ELI; treat cml:Proposed as hypothesis."
198 ],
199 "plan": "https://github.com/webcivics/qualia / docs/plans/wasm-lite-agent-query-plan.md (Qualia monorepo)",
200 "mcp": {
201 "transport": "in-process WASM (mcp_jsonrpc)",
202 "methods": ["initialize", "ping", "tools/list", "tools/call"],
203 "protocolVersions": SUPPORTED_PROTOCOL_VERSIONS
204 }
205 }))
206}
207
208fn catalog_summarize(args: &Value) -> Result<Value, String> {
210 let catalog_str = required_str(args, "catalogJson")?;
211 let catalog: Value = serde_json::from_str(catalog_str)
212 .map_err(|e| format!("catalogJson is not valid JSON: {e}"))?;
213 let category_filter = args
214 .get("categoryPrefix")
215 .and_then(Value::as_str)
216 .map(|s| s.trim_matches('/').to_string());
217 let title_contains = args
218 .get("titleContains")
219 .and_then(Value::as_str)
220 .map(|s| s.to_ascii_lowercase());
221 let id_prefix = args
222 .get("idPrefix")
223 .and_then(Value::as_str)
224 .map(|s| s.to_string());
225 let limit = args
226 .get("limit")
227 .and_then(Value::as_u64)
228 .unwrap_or(64)
229 .min(512) as usize;
230
231 let datasets = catalog
232 .get("datasets")
233 .and_then(Value::as_array)
234 .ok_or_else(|| "catalogJson.datasets must be an array".to_string())?;
235
236 let mut categories: std::collections::BTreeMap<String, usize> =
237 std::collections::BTreeMap::new();
238 let mut selected = Vec::new();
239 let mut matched = 0usize;
240
241 for ds in datasets {
242 let category = ds
243 .get("category")
244 .and_then(Value::as_str)
245 .unwrap_or("uncategorized")
246 .to_string();
247 *categories.entry(category.clone()).or_insert(0) += 1;
248
249 if let Some(ref prefix) = category_filter {
250 if category != *prefix && !category.starts_with(&format!("{prefix}/")) {
251 continue;
252 }
253 }
254 let id = ds.get("id").and_then(Value::as_str).unwrap_or("");
255 if let Some(ref pref) = id_prefix {
256 if !id.starts_with(pref.as_str()) {
257 continue;
258 }
259 }
260 let title = ds.get("title").and_then(Value::as_str).unwrap_or("");
261 if let Some(ref needle) = title_contains {
262 if !title.to_ascii_lowercase().contains(needle.as_str()) {
263 continue;
264 }
265 }
266 matched += 1;
267 if selected.len() < limit {
268 selected.push(json!({
269 "id": ds.get("id"),
270 "title": ds.get("title"),
271 "category": category,
272 "canonicalUrl": ds.get("canonicalUrl"),
273 "n3Url": ds.get("n3Url"),
274 "turtleUrl": ds.get("turtleUrl"),
275 "jsonldUrl": ds.get("jsonldUrl"),
276 "tripleCount": ds.get("tripleCount"),
277 "registerId": ds.get("registerId")
278 }));
279 }
280 }
281
282 Ok(json!({
283 "title": catalog.get("title"),
284 "baseUrl": catalog.get("baseUrl"),
285 "generatedAt": catalog.get("generatedAt"),
286 "datasetCount": catalog.get("datasetCount").cloned().unwrap_or(json!(datasets.len())),
287 "categoryCounts": categories,
288 "categoryFilter": category_filter,
289 "titleContains": title_contains,
290 "idPrefix": id_prefix,
291 "matchedCount": matched,
292 "returnedCount": selected.len(),
293 "truncated": matched > selected.len(),
294 "datasets": selected,
295 "queryMeta": {
296 "tool": "catalog_summarize",
297 "projectedFromN3": false,
298 "logicMode": "none"
299 }
300 }))
301}
302
303fn corpus_summarize(args: &Value) -> Result<Value, String> {
307 let corpus_str = required_str(args, "corpusJson")?;
308 let corpus: Value = serde_json::from_str(corpus_str)
309 .map_err(|e| format!("corpusJson is not valid JSON: {e}"))?;
310 let title_contains = args
311 .get("titleContains")
312 .and_then(Value::as_str)
313 .map(|s| s.to_ascii_lowercase());
314 let id_prefix = args
315 .get("idPrefix")
316 .and_then(Value::as_str)
317 .map(|s| s.to_string());
318 let limit = args
319 .get("limit")
320 .and_then(Value::as_u64)
321 .unwrap_or(64)
322 .min(512) as usize;
323
324 let datasets: &[Value] = if let Some(arr) = corpus.get("datasets").and_then(Value::as_array) {
325 arr
326 } else if let Some(arr) = corpus.as_array() {
327 arr
328 } else {
329 return Err("corpusJson must be an object with datasets[] or a bare array".into());
330 };
331
332 let mut selected = Vec::new();
333 let mut matched = 0usize;
334 for ds in datasets {
335 let id = ds
336 .get("id")
337 .or_else(|| ds.get("registerId"))
338 .and_then(Value::as_str)
339 .unwrap_or("");
340 if let Some(ref pref) = id_prefix {
341 if !id.starts_with(pref.as_str()) {
342 continue;
343 }
344 }
345 let title = ds.get("title").and_then(Value::as_str).unwrap_or("");
346 if let Some(ref needle) = title_contains {
347 if !title.to_ascii_lowercase().contains(needle.as_str()) {
348 continue;
349 }
350 }
351 matched += 1;
352 if selected.len() < limit {
353 selected.push(json!({
354 "id": ds.get("id").or_else(|| ds.get("registerId")),
355 "registerId": ds.get("registerId"),
356 "title": ds.get("title"),
357 "canonicalUrl": ds.get("canonicalUrl"),
358 "n3Url": ds.get("n3Url"),
359 "officialSource": ds.get("officialSource"),
360 "rdfTriples": ds.get("rdfTriples").or_else(|| ds.get("tripleCount")),
361 "n3Bytes": ds.get("n3Bytes"),
362 "curationStatus": ds.get("curationStatus")
363 }));
364 }
365 }
366
367 Ok(json!({
368 "jurisdiction": corpus.get("jurisdiction"),
369 "datasetCount": corpus.get("datasetCount").cloned().unwrap_or(json!(datasets.len())),
370 "titleContains": title_contains,
371 "idPrefix": id_prefix,
372 "matchedCount": matched,
373 "returnedCount": selected.len(),
374 "truncated": matched > selected.len(),
375 "datasets": selected,
376 "queryMeta": {
377 "tool": "corpus_summarize",
378 "projectedFromN3": false,
379 "logicMode": "none"
380 }
381 }))
382}
383
384fn export_graph(args: &Value) -> Result<Value, String> {
389 let format = args
390 .get("format")
391 .and_then(Value::as_str)
392 .unwrap_or("jsonld")
393 .to_ascii_lowercase();
394 let logic_mode = args
395 .get("logicMode")
396 .and_then(Value::as_str)
397 .unwrap_or("none")
398 .to_ascii_lowercase();
399 if !matches!(
400 logic_mode.as_str(),
401 "none" | "as-data" | "evaluate" | "native-n3"
402 ) {
403 return Err("logicMode must be none|as-data|evaluate|native-n3".into());
404 }
405 let context_url = args
406 .get("contextUrl")
407 .and_then(Value::as_str)
408 .unwrap_or("https://ns.webcivics.net/context.jsonld");
409 let triples_raw = args
410 .get("triples")
411 .and_then(Value::as_array)
412 .ok_or_else(|| "triples must be an array".to_string())?;
413 if triples_raw.len() > MAX_QUERY_RESULTS {
414 return Err(format!(
415 "triples exceeds the {MAX_QUERY_RESULTS}-item export bound"
416 ));
417 }
418
419 let mut triples = Vec::with_capacity(triples_raw.len());
420 for (i, t) in triples_raw.iter().enumerate() {
421 triples.push(parse_export_triple(t, i)?);
422 }
423
424 let dropped = match logic_mode.as_str() {
425 "none" | "as-data" => vec![
426 "n3:formulae".to_string(),
427 "n3:variables".to_string(),
428 "n3:=> rules".to_string(),
429 ],
430 "evaluate" => vec!["n3:formulae".to_string(), "n3:variables".to_string()],
431 "native-n3" => Vec::new(),
432 _ => Vec::new(),
433 };
434
435 let (media_type, body) = match format.as_str() {
436 "jsonld" | "application/ld+json" => {
437 ("application/ld+json", export_jsonld(&triples, context_url)?)
438 }
439 "rdfjson" | "rdf/json" | "application/rdf+json" | "rj" => {
440 ("application/rdf+json", export_rdf_json(&triples)?)
441 }
442 "turtle" | "ttl" | "text/turtle" => ("text/turtle", Value::String(export_turtle(&triples))),
443 "n3" | "text/n3" => ("text/n3", Value::String(export_n3(&triples))),
444 "yamlld" | "yaml-ld" | "application/ld+yaml" => {
445 let jsonld = export_jsonld(&triples, context_url)?;
446 (
447 "application/ld+yaml",
448 Value::String(json_to_yaml_like(&jsonld)),
449 )
450 }
451 other => {
452 return Err(format!(
453 "unsupported format '{other}' (use jsonld|rdfjson|turtle|n3|yamlld)"
454 ))
455 }
456 };
457
458 Ok(json!({
459 "format": format,
460 "mediaType": media_type,
461 "tripleCount": triples.len(),
462 "body": body,
463 "queryMeta": {
464 "tool": "export_graph",
465 "graphFormat": media_type,
466 "logicMode": logic_mode,
467 "projectedFromN3": logic_mode != "native-n3",
468 "dropped": dropped,
469 "truncated": false,
470 "note": "Ground triples only. N3 logic/rules require format=n3 with logicMode=native-n3 or evaluate_* tools on Quins/.q42."
471 }
472 }))
473}
474
475#[derive(Clone)]
476struct ExportTerm {
477 kind: ExportTermKind,
478 value: String,
479 lang: Option<String>,
480 datatype: Option<String>,
481}
482
483#[derive(Clone, Copy, PartialEq, Eq)]
484enum ExportTermKind {
485 Uri,
486 Literal,
487 BNode,
488}
489
490struct ExportTriple {
491 s: ExportTerm,
492 p: ExportTerm,
493 o: ExportTerm,
494}
495
496fn parse_export_triple(value: &Value, index: usize) -> Result<ExportTriple, String> {
497 let obj = value
498 .as_object()
499 .ok_or_else(|| format!("triples[{index}] must be an object"))?;
500 let s = parse_export_term(
501 obj.get("s")
502 .or_else(|| obj.get("subject"))
503 .ok_or_else(|| format!("triples[{index}].s is required"))?,
504 true,
505 )?;
506 let p = parse_export_term(
507 obj.get("p")
508 .or_else(|| obj.get("predicate"))
509 .ok_or_else(|| format!("triples[{index}].p is required"))?,
510 true,
511 )?;
512 let o = parse_export_term(
513 obj.get("o")
514 .or_else(|| obj.get("object"))
515 .ok_or_else(|| format!("triples[{index}].o is required"))?,
516 false,
517 )?;
518 if p.kind != ExportTermKind::Uri {
519 return Err(format!("triples[{index}].p must be a URI"));
520 }
521 if s.kind == ExportTermKind::Literal {
522 return Err(format!("triples[{index}].s cannot be a literal"));
523 }
524 Ok(ExportTriple { s, p, o })
525}
526
527fn parse_export_term(value: &Value, prefer_uri: bool) -> Result<ExportTerm, String> {
528 if let Some(s) = value.as_str() {
529 if s.starts_with("_:") {
530 return Ok(ExportTerm {
531 kind: ExportTermKind::BNode,
532 value: s.to_string(),
533 lang: None,
534 datatype: None,
535 });
536 }
537 if prefer_uri
538 || s.starts_with("http://")
539 || s.starts_with("https://")
540 || s.starts_with("urn:")
541 {
542 return Ok(ExportTerm {
543 kind: ExportTermKind::Uri,
544 value: s.to_string(),
545 lang: None,
546 datatype: None,
547 });
548 }
549 return Ok(ExportTerm {
550 kind: ExportTermKind::Literal,
551 value: s.to_string(),
552 lang: None,
553 datatype: None,
554 });
555 }
556 let obj = value
557 .as_object()
558 .ok_or_else(|| "term must be a string or object".to_string())?;
559 let raw_type = obj
560 .get("type")
561 .and_then(Value::as_str)
562 .unwrap_or(if prefer_uri { "uri" } else { "literal" });
563 let kind = match raw_type {
564 "uri" | "iri" | "url" => ExportTermKind::Uri,
565 "literal" => ExportTermKind::Literal,
566 "bnode" | "blank" => ExportTermKind::BNode,
567 other => return Err(format!("unsupported term type '{other}'")),
568 };
569 let term_value = obj
570 .get("value")
571 .and_then(Value::as_str)
572 .ok_or_else(|| "term.value must be a string".to_string())?
573 .to_string();
574 Ok(ExportTerm {
575 kind,
576 value: term_value,
577 lang: obj
578 .get("lang")
579 .or_else(|| obj.get("language"))
580 .and_then(Value::as_str)
581 .map(|s| s.to_string()),
582 datatype: obj
583 .get("datatype")
584 .and_then(Value::as_str)
585 .map(|s| s.to_string()),
586 })
587}
588
589fn export_jsonld(triples: &[ExportTriple], context_url: &str) -> Result<Value, String> {
590 use std::collections::BTreeMap;
591 let mut by_subject: BTreeMap<String, BTreeMap<String, Vec<Value>>> = BTreeMap::new();
592 for t in triples {
593 let s_key = match t.s.kind {
594 ExportTermKind::Uri | ExportTermKind::BNode => t.s.value.clone(),
595 ExportTermKind::Literal => return Err("subject literal in JSON-LD export".into()),
596 };
597 let p_key = t.p.value.clone();
598 let o_val = match t.o.kind {
599 ExportTermKind::Uri => json!({ "@id": t.o.value }),
600 ExportTermKind::BNode => json!({ "@id": t.o.value }),
601 ExportTermKind::Literal => {
602 let mut lit = json!({ "@value": t.o.value });
603 if let Some(ref lang) = t.o.lang {
604 lit["@language"] = json!(lang);
605 } else if let Some(ref dt) = t.o.datatype {
606 lit["@type"] = json!(dt);
607 }
608 lit
609 }
610 };
611 by_subject
612 .entry(s_key)
613 .or_default()
614 .entry(p_key)
615 .or_default()
616 .push(o_val);
617 }
618 let mut graph = Vec::new();
619 for (s, preds) in by_subject {
620 let mut node = json!({ "@id": s });
621 for (p, objs) in preds {
622 if objs.len() == 1 {
623 node[p] = objs[0].clone();
624 } else {
625 node[p] = Value::Array(objs);
626 }
627 }
628 graph.push(node);
629 }
630 Ok(json!({
631 "@context": context_url,
632 "@graph": graph
633 }))
634}
635
636fn export_rdf_json(triples: &[ExportTriple]) -> Result<Value, String> {
637 use std::collections::BTreeMap;
638 let mut root: BTreeMap<String, BTreeMap<String, Vec<Value>>> = BTreeMap::new();
640 for t in triples {
641 let s_key = t.s.value.clone();
642 let p_key = t.p.value.clone();
643 let o_obj = match t.o.kind {
644 ExportTermKind::Uri => json!({ "type": "uri", "value": t.o.value }),
645 ExportTermKind::BNode => json!({ "type": "bnode", "value": t.o.value }),
646 ExportTermKind::Literal => {
647 let mut o = json!({ "type": "literal", "value": t.o.value });
648 if let Some(ref lang) = t.o.lang {
649 o["lang"] = json!(lang);
650 }
651 if let Some(ref dt) = t.o.datatype {
652 o["datatype"] = json!(dt);
653 }
654 o
655 }
656 };
657 root.entry(s_key)
658 .or_default()
659 .entry(p_key)
660 .or_default()
661 .push(o_obj);
662 }
663 let mut out = serde_json::Map::new();
664 for (s, preds) in root {
665 let mut pred_obj = serde_json::Map::new();
666 for (p, arr) in preds {
667 pred_obj.insert(p, Value::Array(arr));
668 }
669 out.insert(s, Value::Object(pred_obj));
670 }
671 Ok(Value::Object(out))
672}
673
674fn turtle_escape_iri(iri: &str) -> String {
675 format!("<{}>", iri.replace('>', "\\>"))
676}
677
678fn turtle_escape_literal(s: &str) -> String {
679 let escaped = s
680 .replace('\\', "\\\\")
681 .replace('"', "\\\"")
682 .replace('\n', "\\n")
683 .replace('\r', "\\r");
684 format!("\"{escaped}\"")
685}
686
687fn term_turtle(t: &ExportTerm) -> String {
688 match t.kind {
689 ExportTermKind::Uri => turtle_escape_iri(&t.value),
690 ExportTermKind::BNode => {
691 if t.value.starts_with("_:") {
692 t.value.clone()
693 } else {
694 format!("_:{}", t.value)
695 }
696 }
697 ExportTermKind::Literal => {
698 let mut lit = turtle_escape_literal(&t.value);
699 if let Some(ref lang) = t.lang {
700 lit.push('@');
701 lit.push_str(lang);
702 } else if let Some(ref dt) = t.datatype {
703 lit.push_str("^^");
704 lit.push_str(&turtle_escape_iri(dt));
705 }
706 lit
707 }
708 }
709}
710
711fn export_turtle(triples: &[ExportTriple]) -> String {
712 let mut out = String::new();
713 for t in triples {
714 out.push_str(&term_turtle(&t.s));
715 out.push(' ');
716 out.push_str(&term_turtle(&t.p));
717 out.push(' ');
718 out.push_str(&term_turtle(&t.o));
719 out.push_str(" .\n");
720 }
721 out
722}
723
724fn export_n3(triples: &[ExportTriple]) -> String {
725 export_turtle(triples)
727}
728
729fn json_to_yaml_like(value: &Value) -> String {
731 fn emit(value: &Value, indent: usize, out: &mut String) {
732 let pad = " ".repeat(indent);
733 match value {
734 Value::Null => out.push_str("null"),
735 Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
736 Value::Number(n) => out.push_str(&n.to_string()),
737 Value::String(s) => {
738 if s.contains('\n') || s.contains(':') || s.contains('#') {
739 out.push('"');
740 out.push_str(&s.replace('\\', "\\\\").replace('"', "\\\""));
741 out.push('"');
742 } else {
743 out.push_str(s);
744 }
745 }
746 Value::Array(arr) => {
747 if arr.is_empty() {
748 out.push_str("[]");
749 return;
750 }
751 for (i, item) in arr.iter().enumerate() {
752 if i > 0 {
753 out.push('\n');
754 out.push_str(&pad);
755 }
756 out.push_str("- ");
757 match item {
758 Value::Object(_) | Value::Array(_) => {
759 out.push('\n');
760 emit(item, indent + 1, out);
761 }
762 _ => emit(item, indent + 1, out),
763 }
764 }
765 }
766 Value::Object(map) => {
767 if map.is_empty() {
768 out.push_str("{}");
769 return;
770 }
771 for (i, (k, v)) in map.iter().enumerate() {
772 if i > 0 {
773 out.push('\n');
774 out.push_str(&pad);
775 }
776 out.push_str(k);
777 out.push(':');
778 match v {
779 Value::Object(_) | Value::Array(_) => {
780 out.push('\n');
781 out.push_str(&" ".repeat(indent + 1));
782 emit(v, indent + 1, out);
783 }
784 _ => {
785 out.push(' ');
786 emit(v, indent + 1, out);
787 }
788 }
789 }
790 }
791 }
792 }
793 let mut out = String::new();
794 emit(value, 0, &mut out);
795 out.push('\n');
796 out
797}
798
799fn resolve_dataset_urls(args: &Value) -> Result<Value, String> {
801 let base = args
802 .get("baseUrl")
803 .and_then(Value::as_str)
804 .unwrap_or("https://ns.webcivics.net")
805 .trim_end_matches('/');
806 let mut path = required_str(args, "path")?.trim().to_string();
807 if path.is_empty() {
808 return Err("path must be non-empty".into());
809 }
810 if !path.starts_with('/') {
811 path = format!("/{path}");
812 }
813 let stem = path
815 .trim_end_matches('/')
816 .trim_end_matches(".n3")
817 .trim_end_matches(".ttl")
818 .trim_end_matches(".jsonld")
819 .trim_end_matches(".json");
820 Ok(json!({
821 "dataPath": stem,
822 "htmlUrl": format!("{base}{stem}/"),
823 "n3Url": format!("{base}{stem}.n3"),
824 "turtleUrl": format!("{base}{stem}.ttl"),
825 "jsonldUrl": format!("{base}{stem}.jsonld"),
826 "rawN3Url": format!("{base}/raw/ontologies{stem}.n3"),
827 "note": "Directory indexes use the trailing-slash HTML URL only; leaf documents also publish RDF extensions."
828 }))
829}
830
831fn ontology_capabilities() -> Result<Value, String> {
832 Ok(json!({
833 "profile": qualia_core_db::wasm_capabilities::compiled_profile(),
834 "capabilities": qualia_core_db::wasm_capabilities::compiled_capabilities(),
835 "limits": {
836 "inputQuins": MAX_INPUT_QUINS,
837 "queryResults": MAX_QUERY_RESULTS,
838 "n3Events": MAX_N3_EVENTS
839 },
840 "excluded": [
841 "portal-renderer",
842 "webgpu",
843 "scientific-solvers",
844 "llm-inference",
845 "native-daemon",
846 "network-stack",
847 "filesystem-storage"
848 ]
849 }))
850}
851
852fn hash_iri(args: &Value) -> Result<Value, String> {
853 let iri = required_str(args, "iri")?;
854 Ok(json!({
855 "iri": iri,
856 "hash": qualia_core_db::q_hash(iri).to_string()
857 }))
858}
859
860fn parse_n3(args: &Value) -> Result<Value, String> {
861 use modalities::logic::n3_parser::{N3Parser, StackEvent, Term};
862
863 let source = required_str(args, "source")?;
864 let mut events = Vec::new();
865 let mut truncated = false;
866 let mut parser = N3Parser::new(source);
867 parser
868 .parse_all_zero_heap(|event| {
869 if events.len() >= MAX_N3_EVENTS {
870 truncated = true;
871 return Ok(());
872 }
873 let value = match event {
874 StackEvent::StaticTriple(t) => json!({
875 "type": "triple",
876 "subject": term_json(t.subject),
877 "predicate": term_json(t.predicate),
878 "object": term_json(t.object)
879 }),
880 StackEvent::LogicRule(rule) => json!({
881 "type": "rule",
882 "ruleType": format!("{:?}", rule.rule_type),
883 "weight": rule.weight,
884 "premiseCount": rule.premise.len,
885 "conclusionCount": rule.conclusion.len
886 }),
887 StackEvent::AspBlock(block) => {
888 json!({ "type": "asp", "source": block })
889 }
890 StackEvent::DiffuseBlock(block) => {
891 json!({ "type": "diffuse", "source": block })
892 }
893 };
894 events.push(value);
895 Ok(())
896 })
897 .map_err(|error| error.to_string())?;
898
899 fn term_json(term: Term<'_>) -> Value {
900 match term {
901 Term::Uri(value) => json!({ "kind": "iri", "value": value }),
902 Term::Variable(value) => json!({ "kind": "variable", "value": value }),
903 Term::Literal(value) => json!({ "kind": "literal", "value": value }),
904 Term::Formula(value) => json!({ "kind": "formula", "value": value }),
905 }
906 }
907
908 Ok(json!({
909 "eventCount": events.len(),
910 "truncated": truncated,
911 "events": events
912 }))
913}
914
915fn query_quins(args: &Value) -> Result<Value, String> {
916 let quins = parse_quins(args)?;
917 let subject = optional_u64(args, "subject")?;
918 let predicate = optional_u64(args, "predicate")?;
919 let object = optional_u64(args, "object")?;
920 let context = optional_u64(args, "context")?;
921 let limit = args
922 .get("limit")
923 .and_then(Value::as_u64)
924 .unwrap_or(64)
925 .min(MAX_QUERY_RESULTS as u64) as usize;
926
927 let mut matches = Vec::new();
928 let mut match_count = 0usize;
929 for quin in &quins {
930 if subject.is_some_and(|value| quin.subject != value)
931 || predicate.is_some_and(|value| quin.predicate != value)
932 || object.is_some_and(|value| quin.object != value)
933 || context.is_some_and(|value| quin.context != value)
934 {
935 continue;
936 }
937 match_count += 1;
938 if matches.len() < limit {
939 matches.push(quin_json(quin));
940 }
941 }
942
943 Ok(json!({
944 "matchCount": match_count,
945 "returnedCount": matches.len(),
946 "truncated": match_count > matches.len(),
947 "matches": matches
948 }))
949}
950
951fn validate_shacl(args: &Value) -> Result<Value, String> {
952 use qualia_core_db::shacl_compiler::{validate_shacl_property, ShaclConstraint, ShaclDatatype};
953
954 let quins = parse_quins(args)?;
955 let target_subject = required_u64(args, "targetSubject")?;
956 let target_property = required_u64(args, "targetProperty")?;
957 let raw_constraints = args
958 .get("constraints")
959 .and_then(Value::as_array)
960 .ok_or_else(|| "constraints must be an array".to_string())?;
961 if raw_constraints.len() > 32 {
962 return Err("constraints exceeds the 32-item bound".to_string());
963 }
964
965 let mut constraints = Vec::with_capacity(raw_constraints.len());
966 for raw in raw_constraints {
967 let kind = raw
968 .get("type")
969 .and_then(Value::as_str)
970 .ok_or_else(|| "constraint.type must be a string".to_string())?;
971 let constraint = match kind {
972 "datatype" => {
973 let datatype = match required_str(raw, "datatype")? {
974 "string" => ShaclDatatype::String,
975 "integer" => ShaclDatatype::Integer,
976 "decimal" => ShaclDatatype::Decimal,
977 "boolean" => ShaclDatatype::Boolean,
978 "dateTime" => ShaclDatatype::DateTime,
979 other => return Err(format!("unsupported datatype: {other}")),
980 };
981 ShaclConstraint::Datatype(datatype)
982 }
983 "minCount" => ShaclConstraint::MinCount(required_u32(raw, "value")?),
984 "maxCount" => ShaclConstraint::MaxCount(required_u32(raw, "value")?),
985 "minLength" => ShaclConstraint::MinLength(required_u32(raw, "value")?),
986 "maxLength" => ShaclConstraint::MaxLength(required_u32(raw, "value")?),
987 "deonticObligate" => ShaclConstraint::DeonticObligate,
988 "deonticPermit" => ShaclConstraint::DeonticPermit,
989 "deonticForbid" => ShaclConstraint::DeonticForbid,
990 "deonticNotExpired" => ShaclConstraint::DeonticNotExpired {
991 now_unix: required_u32(raw, "nowUnix")?,
992 },
993 "epistemicKnowledge" => ShaclConstraint::EpistemicKnowledge {
994 min_certainty: required_u8(raw, "minCertainty")?,
995 },
996 "epistemicBelief" => ShaclConstraint::EpistemicBelief {
997 min_certainty: required_u8(raw, "minCertainty")?,
998 },
999 "commonKnowledge" => ShaclConstraint::CommonKnowledge,
1000 "in" => {
1001 let values = raw
1002 .get("values")
1003 .and_then(Value::as_array)
1004 .ok_or_else(|| "in.values must be an array".to_string())?;
1005 if values.len() > 8 {
1006 return Err("in.values exceeds the 8-item inline bound".to_string());
1007 }
1008 let mut inline = [0u64; 8];
1009 for (index, value) in values.iter().enumerate() {
1010 inline[index] = parse_u64(value, "in.values")?;
1011 }
1012 ShaclConstraint::In {
1013 count: values.len() as u8,
1014 values: inline,
1015 }
1016 }
1017 other => return Err(format!("unsupported SHACL constraint: {other}")),
1018 };
1019 constraints.push(constraint);
1020 }
1021
1022 Ok(json!({
1023 "conforms": validate_shacl_property(
1024 &quins,
1025 target_subject,
1026 target_property,
1027 &constraints
1028 )
1029 }))
1030}
1031
1032fn evaluate_deontic(args: &Value) -> Result<Value, String> {
1033 use modalities::logic::deontic::{evaluate_deontic_contract, DeonticVerdict};
1034
1035 let quins = parse_quins(args)?;
1036 let now = required_u32(args, "nowUnix")?;
1037 let mut out = vec![DeonticVerdict::default(); quins.len()];
1038 let count = evaluate_deontic_contract(&quins, now, &mut out)
1039 .map_err(|error| format!("deontic evaluation failed: {error:?}"))?;
1040 let verdicts: Vec<Value> = out[..count]
1041 .iter()
1042 .map(|verdict| {
1043 json!({
1044 "status": format!("{:?}", verdict.status),
1045 "opcode": verdict.opcode,
1046 "defeatKind": format!("{:?}", verdict.defeat_kind),
1047 "norm": quin_json(&verdict.norm)
1048 })
1049 })
1050 .collect();
1051 Ok(json!({ "verdictCount": count, "verdicts": verdicts }))
1052}
1053
1054fn evaluate_epistemic(args: &Value) -> Result<Value, String> {
1055 use modalities::epistemic::{evaluate_epistemic_frame, EpistemicStatus, EpistemicVerdict};
1056
1057 let quins = parse_quins(args)?;
1058 let agent = optional_u64(args, "agent")?.unwrap_or(0);
1059 let world = optional_u64(args, "world")?.unwrap_or(0);
1060 let empty = EpistemicVerdict {
1061 claim: NQuin::default(),
1062 status: EpistemicStatus::Skipped,
1063 certainty: 0,
1064 };
1065 let mut out = vec![empty; quins.len()];
1066 let count = evaluate_epistemic_frame(&quins, agent, world, &mut out)
1067 .map_err(|error| format!("epistemic evaluation failed: {error:?}"))?;
1068 let verdicts: Vec<Value> = out[..count]
1069 .iter()
1070 .map(|verdict| {
1071 json!({
1072 "status": format!("{:?}", verdict.status),
1073 "certainty": verdict.certainty,
1074 "claim": quin_json(&verdict.claim)
1075 })
1076 })
1077 .collect();
1078 Ok(json!({ "verdictCount": count, "verdicts": verdicts }))
1079}
1080
1081fn route_paraconsistent(args: &Value) -> Result<Value, String> {
1082 let quins = parse_quins(args)?;
1083 let mut consistent = vec![NQuin::default(); quins.len()];
1084 let mut isolated = vec![NQuin::default(); quins.len()];
1085 let (consistent_count, isolated_count) =
1086 modalities::paraconsistent::route_paraconsistent(&quins, &mut consistent, &mut isolated)
1087 .map_err(|error| format!("paraconsistent routing failed: {error:?}"))?;
1088
1089 Ok(json!({
1090 "consistent": consistent[..consistent_count].iter().map(quin_json).collect::<Vec<_>>(),
1091 "isolated": isolated[..isolated_count].iter().map(quin_json).collect::<Vec<_>>()
1092 }))
1093}
1094
1095fn evaluate_ltl(args: &Value) -> Result<Value, String> {
1096 use modalities::temporal_ltl::{evaluate_ltl_trace, LtlFormula};
1097
1098 let trace = parse_named_quins(args, "trace")?;
1099 let formula = args
1100 .get("formula")
1101 .ok_or_else(|| "formula is required".to_string())?;
1102 let kind = required_str(formula, "kind")?;
1103 let parsed = match kind {
1104 "globally" => LtlFormula::Globally(required_u64(formula, "property")?),
1105 "finally" => LtlFormula::Finally(required_u64(formula, "property")?),
1106 "next" => LtlFormula::Next(required_u64(formula, "property")?),
1107 "until" => LtlFormula::Until {
1108 ante: required_u64(formula, "ante")?,
1109 consequent: required_u64(formula, "consequent")?,
1110 },
1111 "release" => LtlFormula::Release {
1112 trigger: required_u64(formula, "trigger")?,
1113 invariant: required_u64(formula, "invariant")?,
1114 },
1115 other => return Err(format!("unsupported LTL formula kind: {other}")),
1116 };
1117 Ok(json!({ "holds": evaluate_ltl_trace(&trace, &parsed) }))
1118}
1119
1120fn check_subsumption(args: &Value) -> Result<Value, String> {
1121 let tbox = parse_named_quins(args, "tbox")?;
1122 let sub = required_u64(args, "subClass")?;
1123 let sup = required_u64(args, "superClass")?;
1124 Ok(json!({
1125 "subsumed": modalities::dl::check_subsumption_quin(sub, sup, &tbox)
1126 }))
1127}
1128
1129fn deontic_govern(args: &Value) -> Result<Value, String> {
1130 use modalities::interaction_governance::{map_policy, permits_execution, Governance};
1131 use modalities::logic::deontic::DeonticStatus;
1132
1133 let status = match required_str(args, "status")?.to_ascii_lowercase().as_str() {
1134 "active" => DeonticStatus::Active,
1135 "defeated" => DeonticStatus::Defeated,
1136 "expired" => DeonticStatus::Expired,
1137 "pending" => DeonticStatus::Pending,
1138 "violated" => DeonticStatus::Violated,
1139 "discharged" => DeonticStatus::Discharged,
1140 "malformed" => DeonticStatus::Malformed,
1141 other => return Err(format!("invalid deontic status: {other}")),
1142 };
1143 let flag = |key: &str| args.get(key).and_then(Value::as_bool).unwrap_or(false);
1144 let mode = map_policy(
1145 status,
1146 Governance {
1147 non_derogable: flag("nonDerogable"),
1148 humanitarian: flag("humanitarian"),
1149 ambiguous: flag("ambiguous"),
1150 },
1151 );
1152 Ok(json!({
1153 "status": format!("{status:?}"),
1154 "policyMode": format!("{mode:?}"),
1155 "permitsExecution": permits_execution(mode)
1156 }))
1157}
1158
1159fn parse_quins(args: &Value) -> Result<Vec<NQuin>, String> {
1160 parse_named_quins(args, "quins")
1161}
1162
1163fn parse_named_quins(args: &Value, field: &str) -> Result<Vec<NQuin>, String> {
1164 let values = args
1165 .get(field)
1166 .and_then(Value::as_array)
1167 .ok_or_else(|| format!("{field} must be an array"))?;
1168 if values.len() > MAX_INPUT_QUINS {
1169 return Err(format!("{field} exceeds the {MAX_INPUT_QUINS}-Quin bound"));
1170 }
1171 values
1172 .iter()
1173 .map(|value| parse_quin(value, field))
1174 .collect()
1175}
1176
1177pub(crate) fn parse_quin(value: &Value, field: &str) -> Result<NQuin, String> {
1179 if let Some(items) = value.as_array() {
1180 if items.len() != 6 {
1181 return Err(format!("{field} Quin arrays must contain six fields"));
1182 }
1183 return Ok(NQuin {
1184 subject: parse_u64(&items[0], "subject")?,
1185 predicate: parse_u64(&items[1], "predicate")?,
1186 object: parse_u64(&items[2], "object")?,
1187 context: parse_u64(&items[3], "context")?,
1188 metadata: parse_u64(&items[4], "metadata")?,
1189 parity: parse_u64(&items[5], "parity")?,
1190 });
1191 }
1192
1193 let object = value
1194 .as_object()
1195 .ok_or_else(|| format!("{field} entries must be objects or six-item arrays"))?;
1196 let get = |name: &str| {
1197 object
1198 .get(name)
1199 .ok_or_else(|| format!("Quin.{name} is required"))
1200 .and_then(|value| parse_u64(value, name))
1201 };
1202 let subject = get("subject")?;
1203 let predicate = get("predicate")?;
1204 let object_value = get("object")?;
1205 let context = get("context")?;
1206 let metadata = object
1207 .get("metadata")
1208 .map(|value| parse_u64(value, "metadata"))
1209 .transpose()?
1210 .unwrap_or(0);
1211 let parity = object
1212 .get("parity")
1213 .map(|value| parse_u64(value, "parity"))
1214 .transpose()?
1215 .unwrap_or(subject ^ predicate ^ object_value ^ context);
1216 Ok(NQuin {
1217 subject,
1218 predicate,
1219 object: object_value,
1220 context,
1221 metadata,
1222 parity,
1223 })
1224}
1225
1226pub(crate) fn quin_json(quin: &NQuin) -> Value {
1228 json!({
1229 "subject": quin.subject.to_string(),
1230 "predicate": quin.predicate.to_string(),
1231 "object": quin.object.to_string(),
1232 "context": quin.context.to_string(),
1233 "metadata": quin.metadata.to_string(),
1234 "parity": quin.parity.to_string()
1235 })
1236}
1237
1238pub(crate) fn required_str<'a>(object: &'a Value, field: &str) -> Result<&'a str, String> {
1240 object
1241 .get(field)
1242 .and_then(Value::as_str)
1243 .ok_or_else(|| format!("{field} must be a string"))
1244}
1245
1246pub(crate) fn required_u64(object: &Value, field: &str) -> Result<u64, String> {
1248 object
1249 .get(field)
1250 .ok_or_else(|| format!("{field} is required"))
1251 .and_then(|value| parse_u64(value, field))
1252}
1253
1254pub(crate) fn optional_u64(object: &Value, field: &str) -> Result<Option<u64>, String> {
1256 object
1257 .get(field)
1258 .map(|value| parse_u64(value, field))
1259 .transpose()
1260}
1261
1262pub(crate) fn required_u32(object: &Value, field: &str) -> Result<u32, String> {
1264 let value = required_u64(object, field)?;
1265 u32::try_from(value).map_err(|_| format!("{field} exceeds u32"))
1266}
1267
1268fn required_u8(object: &Value, field: &str) -> Result<u8, String> {
1269 let value = required_u64(object, field)?;
1270 u8::try_from(value).map_err(|_| format!("{field} exceeds u8"))
1271}
1272
1273pub(crate) fn parse_u64(value: &Value, field: &str) -> Result<u64, String> {
1275 if let Some(number) = value.as_u64() {
1276 return Ok(number);
1277 }
1278 let text = value
1279 .as_str()
1280 .ok_or_else(|| format!("{field} must be a u64 number or string"))?;
1281 if let Some(hex) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
1282 u64::from_str_radix(hex, 16).map_err(|_| format!("{field} is not valid hexadecimal"))
1283 } else {
1284 text.parse::<u64>()
1285 .map_err(|_| format!("{field} is not a valid u64"))
1286 }
1287}
1288
1289fn tool_result(id: Value, result: Value, is_error: bool) -> String {
1290 let text = result.to_string();
1291 rpc_ok(
1292 id,
1293 json!({
1294 "content": [{ "type": "text", "text": text }],
1295 "structuredContent": result,
1296 "isError": is_error
1297 }),
1298 )
1299}
1300
1301fn rpc_ok(id: Value, result: Value) -> String {
1302 json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string()
1303}
1304
1305fn rpc_error(id: Value, code: i64, message: &str) -> String {
1306 json!({
1307 "jsonrpc": "2.0",
1308 "id": id,
1309 "error": { "code": code, "message": message }
1310 })
1311 .to_string()
1312}
1313
1314fn tool_catalog() -> Value {
1315 json!([
1316 tool("ontology_capabilities", "List the exact capabilities and exclusions of this ontology WASM profile.", json!({ "type": "object" })),
1317 tool("hash_iri", "Hash an IRI with Qualia's canonical masked FNV-1a q_hash.", json!({
1318 "type": "object", "required": ["iri"], "properties": { "iri": { "type": "string" } }
1319 })),
1320 tool("parse_n3", "Parse bounded N3 triples, rules, ASP blocks, and diffuse blocks without network access.", json!({
1321 "type": "object", "required": ["source"], "properties": { "source": { "type": "string" } }
1322 })),
1323 tool("query_quins", "Filter an in-memory Quin array by optional subject, predicate, object, and context.", quin_tool_schema()),
1324 tool("validate_shacl", "Validate an in-memory Quin property against the WASM-safe SHACL constraint subset.", json!({
1325 "type": "object",
1326 "required": ["quins", "targetSubject", "targetProperty", "constraints"],
1327 "properties": {
1328 "quins": quin_array_schema(),
1329 "targetSubject": u64_schema(),
1330 "targetProperty": u64_schema(),
1331 "constraints": { "type": "array", "maxItems": 32, "items": { "type": "object" } }
1332 }
1333 })),
1334 tool("evaluate_deontic", "Evaluate obligation, permission, prohibition, expiry, and defeater Quins.", json!({
1335 "type": "object", "required": ["quins", "nowUnix"],
1336 "properties": { "quins": quin_array_schema(), "nowUnix": u64_schema() }
1337 })),
1338 tool("evaluate_epistemic", "Evaluate knowledge, belief, and common-knowledge Quins with optional agent/world filters.", json!({
1339 "type": "object", "required": ["quins"],
1340 "properties": {
1341 "quins": quin_array_schema(), "agent": u64_schema(), "world": u64_schema()
1342 }
1343 })),
1344 tool("route_paraconsistent", "Partition contradictory Quins into consistent and deterministic isolated contexts.", json!({
1345 "type": "object", "required": ["quins"], "properties": { "quins": quin_array_schema() }
1346 })),
1347 tool("evaluate_ltl", "Evaluate one stack-allocated LTL formula against a Quin trace.", json!({
1348 "type": "object", "required": ["trace", "formula"],
1349 "properties": { "trace": quin_array_schema(), "formula": { "type": "object" } }
1350 })),
1351 tool("check_subsumption", "Check transitive rdfs:subClassOf subsumption over a Quin TBox.", json!({
1352 "type": "object", "required": ["tbox", "subClass", "superClass"],
1353 "properties": {
1354 "tbox": quin_array_schema(), "subClass": u64_schema(), "superClass": u64_schema()
1355 }
1356 })),
1357 tool("deontic_govern", "Map a deontic verdict and governance flags to a Webizen policy mode.", json!({
1358 "type": "object", "required": ["status"],
1359 "properties": {
1360 "status": { "type": "string", "enum": ["active","defeated","expired","pending","violated","discharged","malformed"] },
1361 "nonDerogable": { "type": "boolean" },
1362 "humanitarian": { "type": "boolean" },
1363 "ambiguous": { "type": "boolean" }
1364 }
1365 })),
1366 tool("namespace_discovery_help", "Return the offline URL contract and recommended agent flow for ns.webcivics.net (or another baseUrl).", json!({
1367 "type": "object",
1368 "properties": { "baseUrl": { "type": "string", "description": "Default https://ns.webcivics.net" } }
1369 })),
1370 tool("catalog_summarize", "Summarise a fetched DCAT catalog.json string: category/title/id filters and dataset URLs (no network).", json!({
1371 "type": "object",
1372 "required": ["catalogJson"],
1373 "properties": {
1374 "catalogJson": { "type": "string" },
1375 "categoryPrefix": { "type": "string", "description": "e.g. institutions/un" },
1376 "titleContains": { "type": "string", "description": "Case-insensitive title substring" },
1377 "idPrefix": { "type": "string", "description": "Dataset id prefix match" },
1378 "limit": { "type": "integer", "minimum": 1, "maximum": 512 }
1379 }
1380 })),
1381 tool("corpus_summarize", "Summarise a fetched legislation corpus JSON (e.g. au-legislation-corpus.json) by title/id (no network).", json!({
1382 "type": "object",
1383 "required": ["corpusJson"],
1384 "properties": {
1385 "corpusJson": { "type": "string" },
1386 "titleContains": { "type": "string" },
1387 "idPrefix": { "type": "string" },
1388 "limit": { "type": "integer", "minimum": 1, "maximum": 512 }
1389 }
1390 })),
1391 tool("export_graph", "Serialise ground RDF triples as jsonld (default), rdfjson, turtle, n3, or yamlld for bot consumers.", json!({
1392 "type": "object",
1393 "required": ["triples"],
1394 "properties": {
1395 "triples": {
1396 "type": "array",
1397 "maxItems": MAX_QUERY_RESULTS,
1398 "items": {
1399 "type": "object",
1400 "required": ["s", "p", "o"],
1401 "properties": {
1402 "s": {},
1403 "p": {},
1404 "o": {},
1405 "subject": {},
1406 "predicate": {},
1407 "object": {}
1408 }
1409 }
1410 },
1411 "format": {
1412 "type": "string",
1413 "enum": ["jsonld", "rdfjson", "turtle", "n3", "yamlld"],
1414 "description": "Default jsonld"
1415 },
1416 "logicMode": {
1417 "type": "string",
1418 "enum": ["none", "as-data", "evaluate", "native-n3"],
1419 "description": "Affects queryMeta.dropped honesty flags"
1420 },
1421 "contextUrl": {
1422 "type": "string",
1423 "description": "JSON-LD @context URL (default ns.webcivics.net/context.jsonld)"
1424 }
1425 }
1426 })),
1427 tool("resolve_dataset_urls", "Expand a short path like /institutions/un/api-1977 into HTML/N3/TTL/JSON-LD URLs.", json!({
1428 "type": "object",
1429 "required": ["path"],
1430 "properties": {
1431 "path": { "type": "string" },
1432 "baseUrl": { "type": "string" }
1433 }
1434 })),
1435 tool("load_graph", "Load N3, Quin JSON, Q42L bytes, or yaml-ld-q42 into a session graph (no network).", json!({
1436 "type": "object",
1437 "properties": {
1438 "format": { "type": "string", "enum": ["n3", "quins", "q42lite", "q42", "yaml-ld-q42"] },
1439 "source": { "type": "string", "description": "N3 text when format=n3; YAML when format=yaml-ld-q42" },
1440 "quins": quin_array_schema(),
1441 "bytesBase64": { "type": "string", "description": "Q42L payload when format=q42lite" },
1442 "graphId": { "type": "string" },
1443 "label": { "type": "string" },
1444 "namespace": u64_schema(),
1445 "lamportClock": u64_schema()
1446 }
1447 })),
1448 tool("load_yaml_ld_q42", "Compile yaml-ld-q42 (WebizenWorkspace pages/panes or HCF HypermediaDocument) into a session graph. Media type application/yaml-ld-q42.", json!({
1449 "type": "object",
1450 "required": ["source"],
1451 "properties": {
1452 "source": { "type": "string", "description": "yaml-ld-q42 YAML text (workspace or HCF)" },
1453 "graphId": { "type": "string" },
1454 "label": { "type": "string" },
1455 "namespace": u64_schema(),
1456 "lamportClock": u64_schema()
1457 }
1458 })),
1459 tool("load_q42", "Load Q42L (wasm-safe) volume bytes; native Q42 v3 is rejected with guidance.", json!({
1460 "type": "object",
1461 "required": ["bytesBase64"],
1462 "properties": {
1463 "bytesBase64": { "type": "string" },
1464 "graphId": { "type": "string" },
1465 "label": { "type": "string" },
1466 "format": { "type": "string" }
1467 }
1468 })),
1469 tool("list_graphs", "List session-scoped graphs.", json!({ "type": "object" })),
1470 tool("unload_graph", "Drop a session graph by graphId.", json!({
1471 "type": "object", "required": ["graphId"],
1472 "properties": { "graphId": { "type": "string" } }
1473 })),
1474 tool("query_graph", "Filter a session graph by optional S/P/O/C hashes and label/object substring (lexicon).", json!({
1475 "type": "object",
1476 "required": ["graphId"],
1477 "properties": {
1478 "graphId": { "type": "string" },
1479 "subject": u64_schema(),
1480 "predicate": u64_schema(),
1481 "object": u64_schema(),
1482 "context": u64_schema(),
1483 "labelContains": { "type": "string" },
1484 "objectContains": { "type": "string" },
1485 "limit": { "type": "integer", "minimum": 1, "maximum": MAX_QUERY_RESULTS }
1486 }
1487 })),
1488 tool("query_sparql", "SELECT-only SPARQL subset over a session graph (simple ?s ?p ?o BGP + optional FILTER CONTAINS on ?o).", json!({
1489 "type": "object",
1490 "required": ["graphId", "query"],
1491 "properties": {
1492 "graphId": { "type": "string" },
1493 "query": { "type": "string" },
1494 "limit": { "type": "integer", "minimum": 1, "maximum": MAX_QUERY_RESULTS }
1495 }
1496 })),
1497 tool("export_q42lite", "Serialise a session graph to Q42L base64 for transfer/tests.", json!({
1498 "type": "object",
1499 "required": ["graphId"],
1500 "properties": { "graphId": { "type": "string" } }
1501 })),
1502 tool("compile_deontic_norms", "Compile structured obligation/permit/forbid norms into Quins (optional storeAsGraph).", json!({
1503 "type": "object",
1504 "required": ["norms"],
1505 "properties": {
1506 "norms": { "type": "array", "maxItems": 256, "items": { "type": "object" } },
1507 "storeAsGraph": { "type": "boolean" },
1508 "graphId": { "type": "string" },
1509 "label": { "type": "string" }
1510 }
1511 })),
1512 tool("evaluate_deontic_session", "evaluate_deontic over a session graphId or quins array.", json!({
1513 "type": "object",
1514 "required": ["nowUnix"],
1515 "properties": {
1516 "nowUnix": u64_schema(),
1517 "graphId": { "type": "string" },
1518 "quins": quin_array_schema()
1519 }
1520 }))
1521 ])
1522}
1523
1524fn tool(name: &str, description: &str, input_schema: Value) -> Value {
1525 json!({ "name": name, "description": description, "inputSchema": input_schema })
1526}
1527
1528fn u64_schema() -> Value {
1529 json!({
1530 "oneOf": [
1531 { "type": "string", "pattern": "^(0[xX][0-9a-fA-F]+|[0-9]+)$" },
1532 { "type": "integer", "minimum": 0 }
1533 ]
1534 })
1535}
1536
1537fn quin_array_schema() -> Value {
1538 json!({
1539 "type": "array",
1540 "maxItems": MAX_INPUT_QUINS,
1541 "items": {
1542 "type": "object",
1543 "required": ["subject", "predicate", "object", "context"],
1544 "properties": {
1545 "subject": u64_schema(),
1546 "predicate": u64_schema(),
1547 "object": u64_schema(),
1548 "context": u64_schema(),
1549 "metadata": u64_schema(),
1550 "parity": u64_schema()
1551 }
1552 }
1553 })
1554}
1555
1556fn quin_tool_schema() -> Value {
1557 json!({
1558 "type": "object",
1559 "required": ["quins"],
1560 "properties": {
1561 "quins": quin_array_schema(),
1562 "subject": u64_schema(),
1563 "predicate": u64_schema(),
1564 "object": u64_schema(),
1565 "context": u64_schema(),
1566 "limit": { "type": "integer", "minimum": 0, "maximum": MAX_QUERY_RESULTS }
1567 }
1568 })
1569}
1570
1571#[cfg(test)]
1572mod tests {
1573 use super::*;
1574
1575 fn call(name: &str, arguments: Value) -> Value {
1576 let response: Value = serde_json::from_str(&mcp_jsonrpc(
1577 &json!({
1578 "jsonrpc": "2.0",
1579 "id": 1,
1580 "method": "tools/call",
1581 "params": { "name": name, "arguments": arguments }
1582 })
1583 .to_string(),
1584 ))
1585 .unwrap();
1586 response["result"]["structuredContent"].clone()
1587 }
1588
1589 #[test]
1590 fn lists_the_ontology_profile() {
1591 let result = call("ontology_capabilities", json!({}));
1592 assert_eq!(result["profile"], "ontology-mcp-kernel");
1593 assert!(result["capabilities"]
1594 .as_array()
1595 .unwrap()
1596 .iter()
1597 .any(|value| value == "deontic-logic"));
1598 }
1599
1600 #[test]
1601 fn namespace_discovery_help_lists_bootstrap_urls() {
1602 let result = call("namespace_discovery_help", json!({}));
1603 assert!(result["bootstrap"]["catalogJson"]
1604 .as_str()
1605 .unwrap()
1606 .contains("catalog.json"));
1607 assert!(result["recommendedAgentFlow"].as_array().unwrap().len() >= 4);
1608 }
1609
1610 #[test]
1611 fn catalog_summarize_filters_by_category_prefix() {
1612 let catalog = json!({
1613 "title": "Test",
1614 "baseUrl": "https://ns.webcivics.net",
1615 "datasetCount": 2,
1616 "datasets": [
1617 {
1618 "id": "a",
1619 "title": "A",
1620 "category": "institutions/un",
1621 "canonicalUrl": "https://ns.webcivics.net/institutions/un/a/",
1622 "n3Url": "https://ns.webcivics.net/institutions/un/a.n3"
1623 },
1624 {
1625 "id": "b",
1626 "title": "B",
1627 "category": "core",
1628 "canonicalUrl": "https://ns.webcivics.net/core/b/",
1629 "n3Url": "https://ns.webcivics.net/core/b.n3"
1630 }
1631 ]
1632 });
1633 let result = call(
1634 "catalog_summarize",
1635 json!({
1636 "catalogJson": catalog.to_string(),
1637 "categoryPrefix": "institutions/un"
1638 }),
1639 );
1640 assert_eq!(result["matchedCount"], 1);
1641 assert_eq!(result["datasets"][0]["id"], "a");
1642 }
1643
1644 #[test]
1645 fn resolve_dataset_urls_builds_extension_paths() {
1646 let result = call(
1647 "resolve_dataset_urls",
1648 json!({ "path": "institutions/un/api-1977" }),
1649 );
1650 assert_eq!(
1651 result["htmlUrl"],
1652 "https://ns.webcivics.net/institutions/un/api-1977/"
1653 );
1654 assert_eq!(
1655 result["n3Url"],
1656 "https://ns.webcivics.net/institutions/un/api-1977.n3"
1657 );
1658 }
1659
1660 #[test]
1661 fn exact_u64_strings_round_trip_through_query() {
1662 let result = call(
1663 "query_quins",
1664 json!({
1665 "quins": [{
1666 "subject": "18446744073709551615",
1667 "predicate": "2",
1668 "object": "3",
1669 "context": "4"
1670 }],
1671 "subject": "18446744073709551615"
1672 }),
1673 );
1674 assert_eq!(result["matchCount"], 1);
1675 assert_eq!(result["matches"][0]["subject"], "18446744073709551615");
1676 }
1677
1678 #[test]
1679 fn parses_n3_static_triple() {
1680 let result = call("parse_n3", json!({ "source": "<urn:s> <urn:p> <urn:o> ." }));
1681 assert_eq!(result["eventCount"], 1);
1682 assert_eq!(result["events"][0]["type"], "triple");
1683 }
1684
1685 #[test]
1686 fn notifications_do_not_return_json_rpc_responses() {
1687 let response =
1688 mcp_jsonrpc(r#"{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}"#);
1689 assert!(response.is_empty());
1690 }
1691
1692 #[test]
1693 fn catalog_summarize_filters_by_title_contains() {
1694 let catalog = json!({
1695 "datasets": [
1696 { "id": "priv", "title": "Privacy Act 1988", "category": "institutions/au-fed-legislation",
1697 "canonicalUrl": "https://ns.webcivics.net/institutions/au-fed-legislation/priv/",
1698 "n3Url": "https://ns.webcivics.net/institutions/au-fed-legislation/priv.n3" },
1699 { "id": "crimes", "title": "Crimes Act", "category": "institutions/au-fed-legislation",
1700 "canonicalUrl": "https://ns.webcivics.net/institutions/au-fed-legislation/crimes/",
1701 "n3Url": "https://ns.webcivics.net/institutions/au-fed-legislation/crimes.n3" }
1702 ]
1703 });
1704 let result = call(
1705 "catalog_summarize",
1706 json!({
1707 "catalogJson": catalog.to_string(),
1708 "titleContains": "privacy"
1709 }),
1710 );
1711 assert_eq!(result["matchedCount"], 1);
1712 assert_eq!(result["datasets"][0]["id"], "priv");
1713 }
1714
1715 #[test]
1716 fn corpus_summarize_finds_consumer_data_right() {
1717 let corpus = json!({
1718 "jurisdiction": "AU",
1719 "datasetCount": 2,
1720 "datasets": [
1721 {
1722 "id": "C2019A00063",
1723 "title": "Treasury Laws Amendment (Consumer Data Right) Act 2019",
1724 "n3Url": "https://ns.webcivics.net/institutions/au-fed-legislation/C2019A00063.n3",
1725 "officialSource": "https://www.legislation.gov.au/C2019A00063/latest/downloads"
1726 },
1727 {
1728 "id": "C1915A00006",
1729 "title": "Crimes Act 1915",
1730 "n3Url": "https://ns.webcivics.net/institutions/au-fed-legislation/C1915A00006.n3"
1731 }
1732 ]
1733 });
1734 let result = call(
1735 "corpus_summarize",
1736 json!({
1737 "corpusJson": corpus.to_string(),
1738 "titleContains": "Consumer Data Right"
1739 }),
1740 );
1741 assert_eq!(result["matchedCount"], 1);
1742 assert_eq!(result["datasets"][0]["id"], "C2019A00063");
1743 }
1744
1745 #[test]
1746 fn export_graph_jsonld_and_rdfjson() {
1747 let triples = json!([{
1748 "s": "https://example.org/about",
1749 "p": "http://purl.org/dc/terms/title",
1750 "o": { "type": "literal", "value": "Anna's Homepage", "lang": "en" }
1751 }]);
1752 let jsonld = call(
1753 "export_graph",
1754 json!({ "triples": triples, "format": "jsonld" }),
1755 );
1756 assert_eq!(jsonld["mediaType"], "application/ld+json");
1757 assert_eq!(jsonld["tripleCount"], 1);
1758 assert!(jsonld["body"]["@graph"].as_array().unwrap().len() == 1);
1759
1760 let rdfjson = call(
1761 "export_graph",
1762 json!({ "triples": triples, "format": "rdfjson" }),
1763 );
1764 assert_eq!(rdfjson["mediaType"], "application/rdf+json");
1765 let about = &rdfjson["body"]["https://example.org/about"];
1766 assert!(
1767 about["http://purl.org/dc/terms/title"].as_array().unwrap()[0]["value"]
1768 .as_str()
1769 .unwrap()
1770 .contains("Anna")
1771 );
1772 }
1773
1774 #[test]
1775 fn export_graph_turtle_n3_yamlld() {
1776 let triples = json!([{
1777 "s": "urn:s",
1778 "p": "urn:p",
1779 "o": "urn:o"
1780 }]);
1781 let ttl = call(
1782 "export_graph",
1783 json!({ "triples": triples, "format": "turtle" }),
1784 );
1785 assert!(ttl["body"].as_str().unwrap().contains("<urn:s>"));
1786 let n3 = call(
1787 "export_graph",
1788 json!({ "triples": triples, "format": "n3" }),
1789 );
1790 assert_eq!(n3["mediaType"], "text/n3");
1791 let yaml = call(
1792 "export_graph",
1793 json!({ "triples": triples, "format": "yamlld" }),
1794 );
1795 assert_eq!(yaml["mediaType"], "application/ld+yaml");
1796 assert!(yaml["body"].as_str().unwrap().contains("@graph"));
1797 }
1798
1799 #[test]
1800 fn load_n3_query_graph_and_sparql_subset() {
1801 let loaded = call(
1802 "load_graph",
1803 json!({
1804 "format": "n3",
1805 "graphId": "demo-access",
1806 "label": "demo",
1807 "source": "<urn:entity> <urn:p/prefLabel> <urn:label/APP12-access-to-personal-information> . <urn:entity> <urn:p/note> <urn:label/must-provide-access-to-personal-information> . <urn:other> <urn:p/prefLabel> <urn:label/Crimes-Act> ."
1809 }),
1810 );
1811 assert_eq!(loaded["graphId"], "demo-access");
1812 assert!(
1813 loaded["quinCount"].as_u64().unwrap() >= 2,
1814 "load_graph result: {loaded}"
1815 );
1816
1817 let hits = call(
1818 "query_graph",
1819 json!({
1820 "graphId": "demo-access",
1821 "objectContains": "access-to-personal",
1822 "limit": 10
1823 }),
1824 );
1825 assert!(
1826 hits["matchCount"].as_u64().unwrap() >= 1,
1827 "query_graph: {hits}"
1828 );
1829
1830 let sparql = call(
1831 "query_sparql",
1832 json!({
1833 "graphId": "demo-access",
1834 "query": "SELECT * WHERE { ?s ?p ?o } FILTER(CONTAINS(LCASE(STR(?o)), \"access-to-personal\")) LIMIT 20"
1835 }),
1836 );
1837 assert!(
1838 sparql["matchCount"].as_u64().unwrap() >= 1,
1839 "query_sparql: {sparql}"
1840 );
1841
1842 let listed = call("list_graphs", json!({}));
1843 assert!(listed["graphCount"].as_u64().unwrap() >= 1);
1844
1845 let unloaded = call("unload_graph", json!({ "graphId": "demo-access" }));
1846 assert_eq!(unloaded["removed"], true);
1847 }
1848
1849 #[test]
1850 fn q42lite_round_trip_and_deontic_bridge() {
1851 let loaded = call(
1852 "load_graph",
1853 json!({
1854 "format": "n3",
1855 "graphId": "q42-src",
1856 "source": "<urn:a> <urn:p> <urn:b> ."
1857 }),
1858 );
1859 assert_eq!(loaded["quinCount"], 1);
1860 let exported = call("export_q42lite", json!({ "graphId": "q42-src" }));
1861 let b64 = exported["bytesBase64"].as_str().unwrap();
1862 assert!(!b64.is_empty());
1863
1864 let reloaded = call(
1865 "load_q42",
1866 json!({
1867 "bytesBase64": b64,
1868 "graphId": "q42-dst",
1869 "label": "roundtrip"
1870 }),
1871 );
1872 assert_eq!(reloaded["quinCount"], 1);
1873
1874 let compiled = call(
1876 "compile_deontic_norms",
1877 json!({
1878 "storeAsGraph": true,
1879 "graphId": "norms-1",
1880 "norms": [{
1881 "partyIri": "did:example:holder",
1882 "propertyIri": "https://ns.webcivics.net/values/requires",
1883 "actionIri": "urn:action:give-access",
1884 "contractIri": "urn:contract:app12",
1885 "opcode": "obligate",
1886 "expiryUnix": 0
1887 }]
1888 }),
1889 );
1890 assert_eq!(compiled["normCount"], 1);
1891 let verdicts = call(
1892 "evaluate_deontic_session",
1893 json!({ "graphId": "norms-1", "nowUnix": 1_700_000_000u64 }),
1894 );
1895 assert_eq!(verdicts["verdictCount"], 1);
1896 let status = verdicts["verdicts"][0]["status"].as_str().unwrap();
1897 assert!(
1898 status == "active" || status == "Active",
1899 "expected active, got {status}"
1900 );
1901
1902 let expired = call(
1904 "compile_deontic_norms",
1905 json!({
1906 "norms": [{
1907 "partyIri": "did:example:holder",
1908 "propertyIri": "urn:prop",
1909 "actionIri": "urn:act",
1910 "opcode": "obligate",
1911 "expiryUnix": 100
1912 }]
1913 }),
1914 );
1915 let v2 = call(
1916 "evaluate_deontic_session",
1917 json!({
1918 "quins": expired["quins"],
1919 "nowUnix": 1_000_000u64
1920 }),
1921 );
1922 let st2 = v2["verdicts"][0]["status"]
1923 .as_str()
1924 .unwrap()
1925 .to_ascii_lowercase();
1926 assert_eq!(st2, "expired");
1927
1928 let with_def = call(
1930 "compile_deontic_norms",
1931 json!({
1932 "storeAsGraph": true,
1933 "graphId": "norms-def",
1934 "norms": [
1935 {
1936 "partyIri": "did:example:holder",
1937 "propertyIri": "urn:disclose",
1938 "actionIri": "urn:data",
1939 "contractIri": "urn:c",
1940 "opcode": "obligate",
1941 "expiryUnix": 0
1942 },
1943 {
1944 "partyIri": "did:example:holder",
1945 "propertyIri": "urn:disclose",
1946 "actionIri": "urn:data",
1947 "contractIri": "urn:c",
1948 "opcode": "permit",
1949 "isDefeater": true,
1950 "expiryUnix": 0
1951 }
1952 ]
1953 }),
1954 );
1955 assert_eq!(with_def["normCount"], 2);
1956 let v3 = call(
1957 "evaluate_deontic_session",
1958 json!({ "graphId": "norms-def", "nowUnix": 1 }),
1959 );
1960 let statuses: Vec<String> = v3["verdicts"]
1961 .as_array()
1962 .unwrap()
1963 .iter()
1964 .map(|v| v["status"].as_str().unwrap().to_ascii_lowercase())
1965 .collect();
1966 assert!(
1967 statuses.iter().any(|s| s == "defeated"),
1968 "expected a defeated verdict, got {statuses:?}"
1969 );
1970
1971 let _ = call("unload_graph", json!({ "graphId": "q42-src" }));
1972 let _ = call("unload_graph", json!({ "graphId": "q42-dst" }));
1973 let _ = call("unload_graph", json!({ "graphId": "norms-1" }));
1974 let _ = call("unload_graph", json!({ "graphId": "norms-def" }));
1975 }
1976
1977 #[test]
1978 fn load_yaml_ld_q42_hcf_minimal_fixture() {
1979 let yaml = r#"
1980"@id": "doc:civics_au_writing"
1981"@type": "HypermediaDocument"
1982"title": "Civics.au Writing"
1983"author": "Timothy Holborn"
1984"tags": ["civics", "hcf"]
1985"content":
1986 - heading: "Lead"
1987 blocks:
1988 - text: "HCF HypermediaDocument is the source of truth."
1989 markdown: "Optional **Markdown** projector."
1990"#;
1991 let loaded = call(
1992 "load_yaml_ld_q42",
1993 json!({
1994 "source": yaml,
1995 "graphId": "hcf-civics",
1996 "label": "civics-writing",
1997 "namespace": 7,
1998 "lamportClock": 1
1999 }),
2000 );
2001 assert_eq!(loaded["graphId"], "hcf-civics", "load: {loaded}");
2002 assert_eq!(loaded["sourceFormat"], "yaml-ld-q42/hcf");
2003 assert!(
2004 loaded["quinCount"].as_u64().unwrap() >= 3,
2005 "expected title/heading/text quins: {loaded}"
2006 );
2007 assert!(
2008 loaded["lexiconCount"].as_u64().unwrap() >= 3,
2009 "expected lexicon surfaces: {loaded}"
2010 );
2011
2012 let hits = call(
2013 "query_graph",
2014 json!({
2015 "graphId": "hcf-civics",
2016 "objectContains": "source of truth",
2017 "limit": 10
2018 }),
2019 );
2020 assert!(
2021 hits["matchCount"].as_u64().unwrap() >= 1,
2022 "query_graph after HCF load: {hits}"
2023 );
2024
2025 let aliased = call(
2027 "load_graph",
2028 json!({
2029 "format": "yaml-ld-q42",
2030 "source": yaml,
2031 "graphId": "hcf-alias"
2032 }),
2033 );
2034 assert_eq!(aliased["sourceFormat"], "yaml-ld-q42/hcf");
2035
2036 let _ = call("unload_graph", json!({ "graphId": "hcf-civics" }));
2037 let _ = call("unload_graph", json!({ "graphId": "hcf-alias" }));
2038 }
2039
2040 #[test]
2041 fn tools_list_includes_load_yaml_ld_q42() {
2042 let response: Value = serde_json::from_str(&mcp_jsonrpc(
2043 &json!({
2044 "jsonrpc": "2.0",
2045 "id": 1,
2046 "method": "tools/list"
2047 })
2048 .to_string(),
2049 ))
2050 .unwrap();
2051 let tools = response["result"]["tools"].as_array().unwrap();
2052 assert!(
2053 tools.iter().any(|t| t["name"] == "load_yaml_ld_q42"),
2054 "tools/list missing load_yaml_ld_q42"
2055 );
2056 }
2057}