1use futures_core::Stream;
2use std::fs::File;
3use std::pin::Pin;
4use std::task::{Context, Poll};
5use zeroize::Zeroize;
6
7#[cfg(all(
8 target_arch = "wasm32",
9 feature = "wasm-ontology",
10 any(
11 feature = "portal",
12 feature = "wasm-logic",
13 feature = "wasm-scientific",
14 feature = "wasm-llm",
15 feature = "wasm-playground",
16 feature = "wasm-full"
17 )
18))]
19compile_error!(
20 "wasm-ontology is an exclusive lite profile; build heavier WASM products separately"
21);
22
23pub mod services;
25#[cfg(not(target_arch = "wasm32"))]
26pub use services::chat_relay_daemon;
27#[cfg(not(target_arch = "wasm32"))]
28pub use services::daemon;
29#[cfg(not(target_arch = "wasm32"))]
30pub use services::daemon_graph;
31#[cfg(not(target_arch = "wasm32"))]
32pub use services::daemon_query;
33#[cfg(not(target_arch = "wasm32"))]
34pub use services::daemon_swarm;
35#[cfg(not(target_arch = "wasm32"))]
36pub use services::daemon_tensor;
37#[cfg(not(target_arch = "wasm32"))]
38pub use services::ilp_dispatcher;
39#[cfg(not(target_arch = "wasm32"))]
40pub use services::rpc;
41pub use services::solid_ldp;
42#[cfg(not(target_arch = "wasm32"))]
43pub use services::webizen_server;
44#[cfg(not(target_arch = "wasm32"))]
45pub use services::webtorrent_routes;
46#[cfg(not(target_arch = "wasm32"))]
47pub use services::webtorrent_seeder;
48pub mod medical;
50#[cfg(not(target_arch = "wasm32"))]
51pub use medical::comorbidity_eval;
52#[cfg(not(target_arch = "wasm32"))]
53pub use medical::dicom;
54#[cfg(not(target_arch = "wasm32"))]
55pub use medical::dicom_ingest;
56pub mod query;
58pub use query::cbor_compiler;
59pub use query::graph_index;
60#[cfg(not(target_arch = "wasm32"))]
61pub use query::graph_proof;
62pub use query::indexing;
63#[cfg(not(target_arch = "wasm32"))]
64pub use query::ingest;
65#[cfg(any(
66 not(target_arch = "wasm32"),
67 feature = "wasm-logic",
68 feature = "wasm-scientific",
69 feature = "wasm-full"
70))]
71pub use query::ingestion;
72pub use query::lexicon;
73pub use query::mini_parser;
74#[cfg(not(target_arch = "wasm32"))]
75pub use query::ontology_loader;
76#[cfg(any(
77 not(target_arch = "wasm32"),
78 feature = "wasm-logic",
79 feature = "wasm-scientific",
80 feature = "wasm-full"
81))]
82pub use query::query_compiler;
83pub use query::query_engine;
84pub use query::rdf_star;
85pub use query::resolve;
86pub use query::resolver;
87#[cfg(any(
88 not(target_arch = "wasm32"),
89 feature = "wasm-ontology",
90 feature = "wasm-logic",
91 feature = "wasm-scientific",
92 feature = "wasm-full"
93))]
94pub use query::shacl_compiler;
95pub use query::spawn_decay;
96pub use query::temporal_graph;
97pub use query::temporal_scrub;
98pub mod platform;
100#[cfg(not(target_arch = "wasm32"))]
101pub use platform::device_benchmark;
102pub use platform::git_bridge;
103#[cfg(not(target_arch = "wasm32"))]
104pub use platform::hardware_passport;
105#[cfg(target_os = "android")]
106pub use platform::jni_bridge;
107pub use platform::kml_bridge;
108#[cfg(not(target_arch = "wasm32"))]
109pub use platform::local_scheduler;
110#[cfg(not(target_arch = "wasm32"))]
111pub use platform::npu_ffi;
112#[cfg(not(target_arch = "wasm32"))]
113pub use platform::platform_scheduler;
114pub use platform::tee_ffi;
115pub mod inference;
117pub use inference::agent;
119#[cfg(not(target_arch = "wasm32"))]
120pub use inference::ambient_orchestration;
121pub use inference::application_profile;
122pub use inference::application_profile::{
123 active_application_profile, apply_application_profile, bootstrap_application_profile,
124 set_application_profile, ApplicationProfile,
125};
126pub use inference::compute_universe;
127#[cfg(all(not(target_arch = "wasm32"), feature = "cuda"))]
128pub use inference::cuda_lane::{
129 cache_dense_weight, clear_weight_cache, dense_weight_cached, device_kv_ready,
130 ensure_device_kv_cache, preload_q4k_soa_weights, q4k_device_weight_count, try_cuda_batch_gemv,
131 try_cuda_batch_gemv_cached, try_cuda_batch_gemv_cached_only, try_cuda_mega_pass,
132 try_q4k_soa_attention_device, try_q4k_soa_ffn_block, try_q4k_soa_ffn_block_residual,
133 try_q4k_soa_fused_swiglu, try_q4k_soa_gemv, try_q4k_soa_qkv, warm_cuda_context,
134 weight_cache_len, weight_fingerprint, MegaPassLayerDims, MegaPassLayerWeights, MAX_DENSE_ELEMS,
135};
136#[cfg(target_os = "windows")]
137pub use inference::directml_bridge;
138#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
139pub use inference::ggml_quants;
140#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
141pub use inference::gguf_sharder;
142#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
143pub use inference::inference_agent;
144#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
145pub use inference::inference_agent as llm_agent;
146pub use inference::inference_awq;
147pub use inference::inference_awq as llm_awq;
148#[cfg(not(target_arch = "wasm32"))]
149pub use inference::inference_bench;
150#[cfg(not(target_arch = "wasm32"))]
151pub use inference::inference_bench as llm_bench;
152#[cfg(all(target_arch = "wasm32", feature = "wasm-llm"))]
153pub use inference::inference_bench_wasm as llm_bench;
154pub use inference::inference_eval;
155pub use inference::inference_eval as llm_eval;
156#[cfg(any(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
157pub use inference::inference_gpu_profiler;
158#[cfg(any(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
159pub use inference::inference_gpu_profiler as llm_gpu_profiler;
160pub use inference::inference_kernel_parity;
161pub use inference::inference_kernel_parity as llm_kernel_parity;
162pub use inference::inference_modes;
163pub use inference::inference_modes::{
164 active_inference_mode, apply_mode_toggles, bootstrap_inference_mode, fast_verify_html_default,
165 post_turn_verify_enabled, prefer_tensor_core_gemm, quant_graph_grounding_enabled,
166 rights_mode_enabled, sentinel_mid_decode_enabled, set_inference_mode, InferenceMode,
167};
168#[cfg(not(target_arch = "wasm32"))]
169pub use inference::inference_path_selector;
170#[cfg(not(target_arch = "wasm32"))]
171pub use inference::inference_path_selector::{
172 apply_inference_path_plan, bootstrap_optimal_inference_path, format_path_plan,
173 last_inference_path_plan, path_auto_enabled, resolve_inference_path_plan, run_path_select_cli,
174 ComputeLane, InferencePathPlan, QuantProfile,
175};
176#[cfg(not(target_arch = "wasm32"))]
177pub use inference::kv_capture;
178#[cfg(not(target_arch = "wasm32"))]
179pub use inference::kv_dict;
180#[cfg(all(target_arch = "wasm32", feature = "wasm-llm"))]
181pub use inference::kv_dict;
182#[cfg(not(target_arch = "wasm32"))]
183pub use inference::kv_dict_runtime;
184#[cfg(not(target_arch = "wasm32"))]
185pub use inference::lab;
186#[cfg(not(target_arch = "wasm32"))]
187pub use inference::lab::{
188 append_run_csv, audit_hot_path, calibrate_device_roof, default_search_space,
189 format_lockin_summary, run_ablation_matrix, run_auto_improve, run_decode_timeline,
190 run_q4k_soa_microbench, AblationRow, AutoImproveConfig, DecodeTimeline, DeviceRoof,
191 ExperimentRun, HotPathAudit, LabConfig, LockInPackage, MicrobenchResult, TrialResult,
192 CSV_HEADER,
193};
194#[cfg(any(target_os = "macos", target_os = "ios"))]
195pub use inference::metal_bridge;
196#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
197pub use inference::neuro_symbolic_sieve;
198#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
199pub use inference::orchestrator;
200pub use inference::post_turn_verify;
201pub use inference::post_turn_verify::{
202 maybe_verify_turn, return_html_as_text, verify_and_heal_turn, VerifiedTurn, VerifyCheck,
203};
204pub use inference::prompt_lookup;
205pub use inference::qualia_hybrid;
206pub use inference::qualia_hybrid::{
207 apply_graph_logit_bias, force_fact_tokens, graph_force_enabled, prepare_hybrid_decode,
208 propose_best_draft, propose_fact_draft, publish_graph_route_from_prompt,
209 publish_grounding_obligation, publish_prompt_query_tensor, GRAPH_LOGIT_BIAS,
210};
211pub use inference::quant_graph_grounding;
212pub use inference::quant_graph_grounding::{
213 export_fact_quins, fact_count, ground_generation, load_facts_from_tsv, lookup_capital_object,
214 maybe_ground_generation, register_capital_fact, register_fact, reset_fact_store_to_defaults,
215 seed_facts_from_bundled, GroundingFact, GroundingResult, CTX_GROUNDING, P_CAPITAL_OF,
216};
217#[cfg(not(target_arch = "wasm32"))]
218pub use inference::residency_planner;
219#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
220pub use inference::resident_model;
221#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
222pub use inference::safetensor;
223pub use inference::sampler;
224pub use inference::semantic_culler;
225pub use inference::spatial_sieve;
226#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
227pub use inference::tensor_roles;
228#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
229pub use inference::ternary;
230#[cfg(not(target_arch = "wasm32"))]
231pub use inference::ternary_gpu;
232#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
233pub use inference::topk;
234#[cfg(not(target_arch = "wasm32"))]
237pub use inference::thermal_telemetry;
238#[cfg(not(target_arch = "wasm32"))]
239pub use inference::topk_gpu;
240#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
241pub mod lora;
242pub mod q42;
244pub use q42::design_encode;
245pub use q42::execution_profile;
246pub use q42::machine_gpu_profile;
247pub use q42::model_helper;
248#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
249pub use q42::p64_weight;
250#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
253pub use q42::p64_weight as q42_weight;
254#[cfg(not(target_arch = "wasm32"))]
255pub use q42::q42_lexicon;
256#[cfg(not(target_arch = "wasm32"))]
257pub use q42::q42_reader;
258#[cfg(not(target_arch = "wasm32"))]
259pub use q42::q42_volume;
260pub use q42::yaml_ld_q42;
261pub mod extensions;
263#[cfg(any(
264 not(target_arch = "wasm32"),
265 feature = "wasm-logic",
266 feature = "wasm-scientific",
267 feature = "wasm-full"
268))]
269pub use extensions::extension_bus;
270pub use extensions::extension_manifest;
271#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
272pub use extensions::resource_catalog;
273#[cfg(all(
274 target_arch = "wasm32",
275 feature = "wasm-ontology",
276 not(any(
277 feature = "wasm-logic",
278 feature = "wasm-scientific",
279 feature = "wasm-full"
280 ))
281))]
282#[path = "modalities_lite/mod.rs"]
283pub mod modalities;
284#[cfg(any(
285 not(target_arch = "wasm32"),
286 feature = "wasm-logic",
287 feature = "wasm-scientific",
288 feature = "wasm-full"
289))]
290pub mod modalities;
291pub mod identity;
293pub use identity::agency;
294pub use identity::identifier;
295#[cfg(not(target_arch = "wasm32"))]
296pub use identity::key_vault;
297#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
298pub use identity::profiles;
299pub use identity::vault_manifest;
300pub use identity::webizen_identifiers;
301pub mod gpu_context;
302pub mod shaders;
303#[cfg(all(not(target_arch = "wasm32"), feature = "wgsl-forge"))]
304pub mod wgsl_forge;
305pub mod foundation;
307#[cfg(any(
308 not(target_arch = "wasm32"),
309 feature = "wasm-logic",
310 feature = "wasm-scientific",
311 feature = "wasm-full"
312))]
313pub use foundation::crdt;
314pub use foundation::frame_layout;
315pub use foundation::fuzz_testing;
316pub use foundation::telemetry;
317#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
318pub use foundation::topology_draft;
319pub mod net;
321#[cfg(not(target_arch = "wasm32"))]
322pub use net::acoustic_ble_mesh;
323#[cfg(not(target_arch = "wasm32"))]
324pub use net::ebpf_filter;
325#[cfg(not(target_arch = "wasm32"))]
326pub use net::ebpf_firewall;
327#[cfg(not(target_arch = "wasm32"))]
328pub use net::host_topology;
329#[cfg(not(target_arch = "wasm32"))]
330pub use net::nym_adapter;
331pub use net::sonic_token;
332pub mod audio;
333pub mod bundle;
337pub mod container_10d;
342pub mod tensor;
343#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
347pub use crate::solvers::geometric_algebra;
348pub mod governance;
350pub use governance::illocution;
351pub use governance::modal_kind;
352pub use governance::provenance;
353#[cfg(not(target_arch = "wasm32"))]
354pub use governance::web_civics;
355#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
356pub use governance::webizen;
357#[cfg(any(
358 not(target_arch = "wasm32"),
359 any(feature = "wasm-scientific", feature = "wasm-logic")
360))]
361pub use governance::webizen_bytecode;
362#[cfg(not(target_arch = "wasm32"))]
363pub use governance::webizen_sync;
364pub use governance::webizen_validator;
365pub mod sparql_library;
366pub use sparql_library::*;
367
368#[cfg(not(target_arch = "wasm32"))]
369pub mod q42_lex;
370#[cfg(target_arch = "wasm32")]
371pub mod q42_lex {
372 pub struct Q42LexMmap<'a> {
373 _marker: std::marker::PhantomData<&'a ()>,
374 }
375 impl<'a> Q42LexMmap<'a> {
376 pub fn from_bytes(_data: &'a [u8]) -> Result<Self, String> {
377 Err("Not supported on WASM".to_string())
378 }
379 pub fn lookup_embedded_triple(&self, _id: u64) -> Option<[u64; 3]> {
380 None
381 }
382 pub fn lookup_hash(&self, _id: u64) -> Option<&'a str> {
383 None
384 }
385 }
386 pub struct Q42LexFile {}
387 impl Q42LexFile {
388 pub fn open(_p: &std::path::Path) -> Result<Self, String> {
389 Err("Not supported on WASM".to_string())
390 }
391 pub fn view(&self) -> Q42LexMmap<'_> {
392 Q42LexMmap {
393 _marker: std::marker::PhantomData,
394 }
395 }
396 }
397}
398#[cfg(not(target_arch = "wasm32"))]
399pub mod clinical_engine;
400#[cfg(target_arch = "wasm32")]
401pub mod clinical_engine {
402 pub struct GeneExpressionResult {
403 pub fold_change: f64,
404 pub log2_fold_change: f64,
405 pub is_significant: bool,
406 }
407 pub fn evaluate_gene_expression(
408 _gene_id: u64,
409 _baseline: f64,
410 _treatment: f64,
411 _fc_threshold: f64,
412 ) -> GeneExpressionResult {
413 GeneExpressionResult {
414 fold_change: 0.0,
415 log2_fold_change: 0.0,
416 is_significant: false,
417 }
418 }
419}
420pub mod entity_view;
422pub mod hypermedia;
425pub mod qubo_compiler;
426pub mod render;
427#[cfg(all(target_arch = "wasm32", feature = "portal"))]
428pub mod spatial_wasm;
429#[cfg(all(
430 target_arch = "wasm32",
431 any(
432 feature = "wasm-logic",
433 feature = "wasm-scientific",
434 feature = "wasm-full",
435 feature = "wasm-playground"
436 )
437))]
438pub mod wasm_bridge;
439#[cfg(not(target_arch = "wasm32"))]
440pub mod wasm_bridge;
441#[cfg(all(
442 target_arch = "wasm32",
443 feature = "portal",
444 not(any(
445 feature = "wasm-logic",
446 feature = "wasm-scientific",
447 feature = "wasm-full",
448 feature = "wasm-playground"
449 ))
450))]
451pub mod wasm_bridge_core;
452#[cfg(all(target_arch = "wasm32", feature = "wasm-llm"))]
453pub mod wasm_llm;
454#[cfg(all(target_arch = "wasm32", feature = "portal"))]
455pub use render::portal::QualiaPortal;
456#[cfg(all(target_arch = "wasm32", feature = "portal"))]
457pub use render::portal_wasm::{create_canvas, init_panic_hook, WebEngine};
458#[cfg(all(target_arch = "wasm32", feature = "portal"))]
459pub use spatial_wasm::{
460 design_encode_wasm, export_tensor_buffer_wasm, export_tensor_slice_wasm,
461 geosparql_operation_wasm, sample_browser_telemetry_wasm, spatial_encode_wasm,
462};
463#[cfg(all(
464 target_arch = "wasm32",
465 any(
466 feature = "wasm-logic",
467 feature = "wasm-scientific",
468 feature = "wasm-full",
469 feature = "wasm-playground"
470 )
471))]
472pub use wasm_bridge::{parse_cbor_ld_wasm, parse_json_wasm, parse_n3logic_wasm, parse_turtle_wasm};
473#[cfg(all(
474 target_arch = "wasm32",
475 feature = "portal",
476 not(any(
477 feature = "wasm-logic",
478 feature = "wasm-scientific",
479 feature = "wasm-full",
480 feature = "wasm-playground"
481 ))
482))]
483pub use wasm_bridge_core::{parse_cbor_ld_wasm, parse_json_wasm};
484pub mod storage_driver;
485#[cfg(all(
486 target_arch = "wasm32",
487 any(feature = "wasm-playground", feature = "wasm-full")
488))]
489pub mod wasm_playground;
490#[cfg(not(target_arch = "wasm32"))]
491pub mod zns_storage;
492pub mod crypto;
494#[cfg(feature = "zk-culling")]
495pub use crypto::deontic_circuit;
496pub use crypto::fiduciary_crypto;
497#[cfg(feature = "pq-kem")]
498pub use crypto::pq_kem_shim;
499#[cfg(not(target_arch = "wasm32"))]
500#[cfg(feature = "sanctuary-crypto")]
501pub use crypto::sanctuary_crypto;
502pub use crypto::verifiable_credential;
503pub use crypto::zk_proofs;
504#[cfg(not(target_arch = "wasm32"))]
505pub mod csd_storage;
506#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
508pub mod specialized_libs;
509
510pub mod wasm_capabilities;
521
522pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
527
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
532pub struct CapabilityDescriptor {
533 pub name: &'static str,
534 pub domain: &'static str,
535 pub operations: &'static [&'static str],
538 pub mcp_tools: &'static [&'static str],
539 pub maturity: &'static str,
541 pub surfaces: &'static [&'static str],
543}
544
545pub const CAPABILITY_DESCRIPTORS: &[CapabilityDescriptor] = &[
546 CapabilityDescriptor {
547 name: "CapabilityDiscovery",
548 domain: "runtime",
549 operations: &[
550 "list capability families",
551 "inspect operations",
552 "inspect maturity",
553 "inspect runtime surfaces",
554 ],
555 mcp_tools: &["list_capabilities"],
556 maturity: "stable",
557 surfaces: &["native", "wasm", "mcp", "cli", "chat"],
558 },
559 CapabilityDescriptor {
560 name: "SHACL",
561 domain: "ontology",
562 operations: &[
563 "validate shapes",
564 "route decentralized shapes",
565 "credential gate",
566 "degrade violations",
567 ],
568 mcp_tools: &["validate_shacl", "shacl_route"],
569 maturity: "stable",
570 surfaces: &["native", "wasm-logic", "mcp", "webizen"],
571 },
572 CapabilityDescriptor {
573 name: "GraphDatabase",
574 domain: "ontology",
575 operations: &[
576 "graph query",
577 "SPARQL query",
578 "identifier resolution",
579 "ontology ingest",
580 "RDF parse and serialize",
581 ],
582 mcp_tools: &["query_graph", "query_sparql", "graph_resolve"],
583 maturity: "stable",
584 surfaces: &["native", "wasm-ontology", "mcp"],
585 },
586 CapabilityDescriptor {
587 name: "DeonticLogic",
588 domain: "logic",
589 operations: &[
590 "obligation",
591 "permission",
592 "prohibition",
593 "defeaters",
594 "expiry",
595 "jural correlation",
596 "policy governance",
597 ],
598 mcp_tools: &["evaluate_modality", "deontic_govern", "jural_correlate"],
599 maturity: "stable",
600 surfaces: &["native", "wasm-logic", "mcp", "webizen"],
601 },
602 CapabilityDescriptor {
603 name: "EpistemicLogic",
604 domain: "logic",
605 operations: &[
606 "knowledge",
607 "belief",
608 "common knowledge",
609 "certainty",
610 "possible-world filtering",
611 ],
612 mcp_tools: &["evaluate_modality"],
613 maturity: "stable",
614 surfaces: &["native", "wasm-logic", "mcp", "webizen"],
615 },
616 CapabilityDescriptor {
617 name: "ParaconsistentLogic",
618 domain: "logic",
619 operations: &[
620 "contradiction detection",
621 "context isolation",
622 "non-explosive merge",
623 ],
624 mcp_tools: &["evaluate_modality"],
625 maturity: "stable",
626 surfaces: &["native", "wasm-logic", "mcp", "webizen"],
627 },
628 CapabilityDescriptor {
629 name: "TemporalAndDescriptionLogic",
630 domain: "logic",
631 operations: &[
632 "LTL globally/finally/next/until/release",
633 "CTL path operators",
634 "description-logic subsumption",
635 "interval reasoning",
636 ],
637 mcp_tools: &["evaluate_modality"],
638 maturity: "partial",
639 surfaces: &["native", "wasm-logic", "mcp"],
640 },
641 CapabilityDescriptor {
642 name: "SymbolicAndDefeasibleLogic",
643 domain: "logic",
644 operations: &[
645 "bounded SAT",
646 "defeasible forward chaining",
647 "ASP stable models",
648 "argumentation semantics",
649 "abductive reasoning",
650 ],
651 mcp_tools: &["symbolic_logic_infer", "evaluate_modality"],
652 maturity: "partial",
653 surfaces: &["native", "mcp", "webizen"],
654 },
655 CapabilityDescriptor {
656 name: "SymbolicAlgebra",
657 domain: "mathematics",
658 operations: &[
659 "parse/evaluate expressions",
660 "simplify",
661 "expand",
662 "differentiate",
663 "symbolic integration",
664 "limits",
665 "assumptions",
666 "trigonometric simplification",
667 "Taylor series",
668 "polynomial roots",
669 "symbolic ODE/PDE",
670 ],
671 mcp_tools: &["cas", "algebra_solve_polynomial"],
672 maturity: "partial",
673 surfaces: &["native", "mcp"],
674 },
675 CapabilityDescriptor {
676 name: "LinearAlgebra",
677 domain: "mathematics",
678 operations: &[
679 "matrix multiply",
680 "transpose",
681 "inverse",
682 "linear solve",
683 "determinant",
684 "LU",
685 "QR",
686 "Cholesky",
687 "SVD",
688 "general eigenvalues",
689 "symmetric eigensystem",
690 "tensor contraction",
691 ],
692 mcp_tools: &["matrix_operation", "algebra_matrix_analyze"],
693 maturity: "stable",
694 surfaces: &["native", "mcp", "webizen"],
695 },
696 CapabilityDescriptor {
697 name: "NumericalCalculus",
698 domain: "mathematics",
699 operations: &[
700 "RK4",
701 "BDF1/BDF2",
702 "Verlet/Ruth/Yoshida symplectic integration",
703 "shooting BVP",
704 "Simpson/trapezoid integration",
705 "sensitivity analysis",
706 "interpolation",
707 "splines",
708 "least-squares polynomial fit",
709 ],
710 mcp_tools: &[],
711 maturity: "stable",
712 surfaces: &["native", "library", "webizen"],
713 },
714 CapabilityDescriptor {
715 name: "Optimization",
716 domain: "mathematics",
717 operations: &[
718 "Nelder-Mead",
719 "bounded Newton-Raphson",
720 "Levenberg-Marquardt",
721 "hill climbing",
722 "simulated annealing",
723 "artificial bee colony",
724 ],
725 mcp_tools: &[],
726 maturity: "stable",
727 surfaces: &["native", "library"],
728 },
729 CapabilityDescriptor {
730 name: "GeometricAlgebra",
731 domain: "mathematics",
732 operations: &[
733 "dot/cross/angle",
734 "geometric product",
735 "outer product",
736 "rotors",
737 "translators",
738 "multivectors",
739 "SIMD kernels",
740 ],
741 mcp_tools: &["geometric_algebra_op"],
742 maturity: "partial",
743 surfaces: &["native", "mcp", "webizen"],
744 },
745 CapabilityDescriptor {
746 name: "ComputationalGeometry",
747 domain: "geometry",
748 operations: &[
749 "robust geometric predicates",
750 "convex hulls",
751 "half-edge topology graphs",
752 "10D geometry feature encoding",
753 ".10d quantized mesh geometry",
754 "Delaunay triangulation",
755 "Voronoi diagrams",
756 "nearest-site query",
757 "primitive generation (box, sphere, cylinder, plane)",
758 "T·R·S transform composition",
759 "scene graph assembly",
760 ".10d asset export with μ provenance",
761 "VR filtration + persistent homology",
762 "CkNN graph Laplacian",
763 "natural-neighbour interpolation",
764 ],
765 mcp_tools: &["computational_geometry", "geometry_manifests"],
766 maturity: "partial",
767 surfaces: &["native", "wasm-scientific", "mcp", "webizen", "renderer"],
768 },
769 CapabilityDescriptor {
770 name: "ComputerVision",
771 domain: "vision",
772 operations: &[
773 "classical CV (blur, edges, features, flow, morph)",
774 "classical + tiled super-resolution (nearest/bilinear/bicubic/lanczos)",
775 "Forge shared_gpu nearest + bicubic resize when Cool",
776 "bio histopathology / radiomics / DICOM-lite",
777 "MeshIR export / quality cleanup / class→σ map",
778 "local CBIR proxy embeddings (aHash/dHash/hist)",
779 ],
780 mcp_tools: &["computer_vision"],
781 maturity: "partial",
782 surfaces: &["native", "mcp", "webizen", "qualia-vision"],
783 },
784 CapabilityDescriptor {
785 name: "NumberTheory",
786 domain: "mathematics",
787 operations: &[
788 "primality",
789 "factorization",
790 "divisors",
791 "GCD/LCM",
792 "modular powers/inverses",
793 "Chinese remainder theorem",
794 "totient",
795 "Mobius",
796 "partitions",
797 "Stirling numbers",
798 "Catalan numbers",
799 ],
800 mcp_tools: &[],
801 maturity: "stable",
802 surfaces: &["native", "library"],
803 },
804 CapabilityDescriptor {
805 name: "SpecialFunctionsAndTransforms",
806 domain: "mathematics",
807 operations: &[
808 "Bessel",
809 "Airy",
810 "zeta",
811 "Legendre",
812 "Chebyshev",
813 "Hermite",
814 "Laguerre",
815 "DFT/IDFT",
816 "Laplace transform",
817 "Z-transform",
818 "unit conversion",
819 "dimensional analysis",
820 "vector calculus",
821 ],
822 mcp_tools: &[],
823 maturity: "stable",
824 surfaces: &["native", "library"],
825 },
826 CapabilityDescriptor {
827 name: "Statistics",
828 domain: "statistics",
829 operations: &[
830 "descriptive statistics",
831 "robust statistics",
832 "Pearson/Spearman/Kendall correlation",
833 "histograms",
834 "linear regression",
835 "normal/t/chi-square/F distributions",
836 "t-tests",
837 "ANOVA",
838 "chi-square tests",
839 "non-parametric tests",
840 "multiple testing",
841 "anomaly detection",
842 "entropy/KL/mutual information",
843 ],
844 mcp_tools: &["statistical_analysis"],
845 maturity: "partial",
846 surfaces: &["native", "mcp", "library"],
847 },
848 CapabilityDescriptor {
849 name: "MachineLearning",
850 domain: "machine-learning",
851 operations: &[
858 "linear/ridge/lasso/Bayesian regression",
859 "KNN/naive Bayes/SVM/discriminant classification",
860 "k-means/GMM/hierarchical clustering",
861 "decision trees/random forests/boosting/BART",
862 "PCA/SOM",
863 "Gaussian processes",
864 "HMM/Kalman",
865 "survival analysis",
866 "MCMC/variational inference",
867 "resampling",
868 "active learning",
869 "bandits",
870 "knowledge-graph embeddings",
871 ],
872 mcp_tools: &["ml_inference"],
873 maturity: "fail-closed",
874 surfaces: &["native", "library"],
875 },
876 CapabilityDescriptor {
877 name: "PhysicsAndODE",
878 domain: "physics",
879 operations: &[
880 "thermodynamics",
881 "CFD",
882 "molecular dynamics",
883 "RK4 ODE",
884 "Thomas-Fermi DFT",
885 "PINN binding affinity",
886 "distributed simulation",
887 ],
888 mcp_tools: &["ode_solve", "qpu_dft"],
889 maturity: "partial",
890 surfaces: &["native", "mcp", "webizen"],
891 },
892 CapabilityDescriptor {
893 name: "Bioinformatics",
894 domain: "bioscience",
895 operations: &[
896 "Smith-Waterman",
897 "Needleman-Wunsch",
898 "DNA/protein alignment",
899 "k-mer frequencies",
900 "MinHash/Jaccard",
901 "UPGMA",
902 "FASTA validation",
903 "DNA translation",
904 "isoelectric point",
905 "peptide cleavage",
906 "fingerprint similarity",
907 ],
908 mcp_tools: &["bioinformatics_align"],
909 maturity: "partial",
910 surfaces: &["native", "mcp", "webizen"],
911 },
912 CapabilityDescriptor {
913 name: "OrganicChemistry",
914 domain: "chemistry",
915 operations: &[
916 "SMILES/InChI validation",
917 "formula and molecular weight",
918 "LogP/TPSA",
919 "Lipinski/Veber/Ghose/Egan",
920 "functional groups",
921 "pKa",
922 "chiral centers",
923 "circular fingerprints",
924 "reaction kinetics",
925 "equilibrium",
926 "green metrics",
927 "BBB permeation",
928 "isotope distributions",
929 ],
930 mcp_tools: &["chemical_analysis", "chemical_descriptors"],
931 maturity: "partial",
932 surfaces: &["native", "mcp", "webizen"],
933 },
934 CapabilityDescriptor {
935 name: "ClinicalRisk",
936 domain: "clinical",
937 operations: &[
938 "Framingham",
939 "CHA2DS2-VASc",
940 "SCORE2",
941 "SOFA",
942 "eGFR/creatinine clearance",
943 "drug interactions",
944 "contraindications",
945 "FHIR validation",
946 "longitudinal trends",
947 "gene expression",
948 "one-compartment pharmacokinetics",
949 ],
950 mcp_tools: &["medical_score", "clinical_risk"],
951 maturity: "partial",
952 surfaces: &["native", "mcp", "webizen"],
953 },
954 CapabilityDescriptor {
955 name: "FinancialModeling",
956 domain: "economics",
957 operations: &[
958 "Black-Scholes option pricing and Greeks",
959 "portfolio VaR",
960 "Sharpe/Sortino",
961 "maximum drawdown",
962 "Monte Carlo risk",
963 ],
964 mcp_tools: &["financial_model"],
965 maturity: "partial",
966 surfaces: &["native", "mcp", "webizen"],
967 },
968 CapabilityDescriptor {
969 name: "EngineeringAnalysis",
970 domain: "engineering",
971 operations: &[
972 "structural analysis",
973 "thermal conduction",
974 "linear dynamics",
975 "stress/displacement",
976 "fatigue",
977 "fluid analysis",
978 ],
979 mcp_tools: &["engineering_analysis_op"],
980 maturity: "partial",
981 surfaces: &["native", "mcp"],
982 },
983 CapabilityDescriptor {
984 name: "CausalFuzzyAndControl",
985 domain: "reasoning",
986 operations: &[
987 "causal reachability",
988 "but-for and overdetermined cause",
989 "do-intervention",
990 "counterfactuals",
991 "fuzzy t-norms/conorms",
992 "Mamdani/Sugeno inference",
993 "type-2 fuzzy sets",
994 "PID/control feedback",
995 ],
996 mcp_tools: &[],
997 maturity: "stable",
998 surfaces: &["native", "library", "webizen"],
999 },
1000 CapabilityDescriptor {
1001 name: "ContractsIdentityAndConsensus",
1002 domain: "governance",
1003 operations: &[
1004 "contract formation",
1005 "capacity",
1006 "delegation/revocation",
1007 "responsibility",
1008 "jural chains",
1009 "value flow",
1010 "identity fabric",
1011 "BFT quorum",
1012 "Lamport/vector clocks",
1013 "legal composition",
1014 ],
1015 mcp_tools: &[
1016 "values_check",
1017 "values_evaluate",
1018 "jural_correlate",
1019 "deontic_govern",
1020 "mcp_cooperate",
1021 ],
1022 maturity: "partial",
1023 surfaces: &["native", "wasm-logic", "mcp", "webizen"],
1024 },
1025 CapabilityDescriptor {
1026 name: "QuantumAndCryptographic",
1027 domain: "quantum-security",
1028 operations: &[
1029 "QUBO formulation",
1030 "classical pre-solve",
1031 "QAOA/SPSA",
1032 "QPU job dispatch",
1033 "DFT bridge",
1034 "sign/encrypt/verify",
1035 "ML-DSA credentials",
1036 "zero-knowledge proof plumbing",
1037 "quantum biology orchestration",
1038 ],
1039 mcp_tools: &["qpu_optimize", "qpu_dft", "qpu_status"],
1040 maturity: "experimental",
1041 surfaces: &["native", "mcp", "webizen"],
1042 },
1043];
1044
1045#[repr(C, align(16))]
1048#[derive(
1049 Debug,
1050 Default,
1051 Clone,
1052 Copy,
1053 PartialEq,
1054 Eq,
1055 PartialOrd,
1056 Ord,
1057 Zeroize,
1058 bytemuck::Pod,
1059 bytemuck::Zeroable,
1060 serde::Serialize,
1061 serde::Deserialize,
1062)]
1063pub struct NQuin {
1064 pub subject: u64,
1066 pub predicate: u64,
1068 pub object: u64,
1070 pub context: u64,
1072 pub metadata: u64,
1074 pub parity: u64,
1076}
1077
1078impl NQuin {
1079 const NESTED_BIT_MASK: u64 = 1 << 63;
1080
1081 #[inline(always)]
1082 pub fn is_subject_nested(&self) -> bool {
1083 (self.subject & Self::NESTED_BIT_MASK) != 0
1084 }
1085
1086 #[inline(always)]
1087 pub fn get_subject_literal_id(&self) -> u64 {
1088 self.subject & !Self::NESTED_BIT_MASK
1089 }
1090
1091 const LANE_MASK: u64 = 0b11 << 61;
1102 const SHIFT_LANE: u32 = 61;
1103
1104 #[inline(always)]
1105 pub fn identify_routing_lane(&self) -> PermissiveRoutingLane {
1106 let metadata = self.metadata;
1112 let lane_bits = (metadata & Self::LANE_MASK) >> Self::SHIFT_LANE;
1113 match lane_bits {
1114 0x01 => PermissiveRoutingLane::EnforcePermissiveCommons,
1115 0x02 => PermissiveRoutingLane::EnforceBilateralMicroCommons,
1116 0x03 => PermissiveRoutingLane::SpatiotemporalAmbiguous,
1117 _ => PermissiveRoutingLane::PassthroughStandard,
1118 }
1119 }
1120
1121 pub const SENSITIVITY_PUBLIC: u8 = 0x00;
1122 pub const SENSITIVITY_RESTRICTED: u8 = 0x01;
1123 pub const SENSITIVITY_CLASSIFIED: u8 = 0x02;
1124
1125 #[inline(always)]
1126 pub fn get_sensitivity_byte(&self) -> u8 {
1127 (self.context >> 56) as u8
1128 }
1129
1130 #[inline(always)]
1131 pub fn set_sensitivity_byte(&mut self, sensitivity: u8) {
1132 self.context &= 0x00FF_FFFF_FFFF_FFFF;
1134 self.context |= (sensitivity as u64) << 56;
1136 }
1137
1138 #[inline(always)]
1144 pub fn get_quin_type(&self) -> u8 {
1145 crate::frame_layout::quin_type(self.metadata)
1146 }
1147
1148 #[inline(always)]
1150 pub fn set_quin_type(&mut self, quin_type: u8) {
1151 self.metadata = crate::frame_layout::with_quin_type(self.metadata, quin_type);
1152 }
1153
1154 pub const SENSITIVITY_TIER_PUBLIC: u8 = 0x00;
1157 pub const SENSITIVITY_TIER_PROFESSIONAL: u8 = 0x01;
1158 pub const SENSITIVITY_TIER_LEGAL: u8 = 0x02;
1159 pub const SENSITIVITY_TIER_MEDICAL: u8 = 0x03;
1160 pub const SENSITIVITY_TIER_FIDUCIARY: u8 = 0x04;
1161
1162 #[inline(always)]
1164 pub fn get_sensitivity_tier(&self) -> u8 {
1165 ((self.metadata >> 56) & 0xF) as u8
1166 }
1167
1168 #[inline(always)]
1170 pub fn set_sensitivity_tier(&mut self, tier: u8) {
1171 self.metadata = (self.metadata & !(0xFu64 << 56)) | ((tier as u64 & 0xF) << 56);
1172 }
1173
1174 #[inline(always)]
1178 pub fn extract_lamport_clock(&self) -> u32 {
1179 (self.metadata & 0xFFFF_FFFF) as u32
1180 }
1181
1182 #[inline(always)]
1184 pub fn set_lamport_clock(&mut self, clock: u32) {
1185 self.metadata = (self.metadata & !0xFFFF_FFFFu64) | (clock as u64);
1186 }
1187
1188 #[inline(always)]
1192 pub fn extract_clean_metadata_value(&self) -> u64 {
1193 self.metadata & 0xFFFF_FFFF
1194 }
1195
1196 #[inline(always)]
1199 pub fn calculate_parity(
1200 subject: u64,
1201 predicate: u64,
1202 object: u64,
1203 context: u64,
1204 metadata: u64,
1205 ) -> u64 {
1206 subject ^ predicate ^ object ^ context ^ metadata
1207 }
1208
1209 #[inline(always)]
1210 pub fn verify_ecc_parity(&self) -> bool {
1211 self.parity
1212 == Self::calculate_parity(
1213 self.subject,
1214 self.predicate,
1215 self.object,
1216 self.context,
1217 self.metadata,
1218 )
1219 }
1220
1221 #[inline(always)]
1223 pub fn recalculate_parity(&mut self) {
1224 self.parity = Self::calculate_parity(
1225 self.subject,
1226 self.predicate,
1227 self.object,
1228 self.context,
1229 self.metadata,
1230 );
1231 }
1232
1233 #[inline(always)]
1234 pub fn new_conduct_violation(reason: &[u8]) -> Self {
1235 let mut quin = Self::default();
1236 quin.predicate = 0x42_0000_0000_0000; let mut obj_bytes = [0u8; 8];
1238 let len = core::cmp::min(reason.len(), 8);
1239 obj_bytes[..len].copy_from_slice(&reason[..len]);
1240 quin.object = u64::from_le_bytes(obj_bytes);
1241 quin.parity = Self::calculate_parity(
1242 quin.subject,
1243 quin.predicate,
1244 quin.object,
1245 quin.context,
1246 quin.metadata,
1247 );
1248 quin
1249 }
1250}
1251
1252pub const MODALITY_FLAG_LLM_TENSOR: u8 = 0b1001;
1253pub const MODALITY_FLAG_DENSE_PHYSICS: u8 = 0b1000;
1254pub const MODALITY_FLAG_VISION_TENSOR: u8 = 0b1010;
1256
1257pub trait QuinPointerExt {
1258 fn extract_modality_flag(&self) -> u8;
1259 fn extract_byte_offset(&self) -> u64;
1260}
1261
1262impl QuinPointerExt for NQuin {
1263 #[inline(always)]
1264 fn extract_modality_flag(&self) -> u8 {
1265 (self.object >> 60) as u8
1266 }
1267
1268 #[inline(always)]
1269 fn extract_byte_offset(&self) -> u64 {
1270 self.object & 0x0FFF_FFFF_FFFF_FFFF
1271 }
1272}
1273
1274pub const QUINS_PER_BLOCK: usize = 850;
1275pub const BLOCK_MULTIPLIER_SIZE: usize = 40960; #[repr(C, align(4096))]
1278pub struct QualiaSuperBlock {
1279 pub block_sequence_id: u64,
1281 pub storage_owner_did: u64,
1283 pub active_quin_count: u64,
1285 pub validation_checksum: u32,
1287 pub hardware_profile_flags: u32,
1289 pub fea_mesh_index_id: u64,
1291 pub layout_padding: [u8; 120], pub quin_ledger: [NQuin; QUINS_PER_BLOCK],
1295}
1296
1297pub mod archive;
1298
1299#[repr(u8)]
1301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1302
1303pub enum PermissiveRoutingLane {
1305 PassthroughStandard = 0x00,
1307 EnforcePermissiveCommons = 0x01,
1309 EnforceBilateralMicroCommons = 0x02,
1311 SpatiotemporalAmbiguous = 0x03,
1313}
1314
1315pub const MASK_AUTHENTICATED_NATURAL_PERSON: u16 = 0b0000_0001;
1317pub const MASK_BILATERAL_IDENTITY_LOCKED: u16 = 0b0000_0010;
1318pub const MASK_COMMERCIAL_BILLABLE_GATE: u16 = 0b0000_0100;
1319pub const MASK_WORK_OBLIGATION_SATISFIED: u16 = 0b0000_1000;
1320
1321#[inline(always)]
1322pub fn evaluate_permissive_runtime_gate(
1323 entry_policy_mask: u16,
1324 requesting_agent_signature_flags: u16,
1325) -> bool {
1326 if (entry_policy_mask & MASK_WORK_OBLIGATION_SATISFIED) != 0 {
1328 return true;
1329 }
1330
1331 if (requesting_agent_signature_flags & MASK_COMMERCIAL_BILLABLE_GATE) != 0
1333 && (entry_policy_mask & MASK_COMMERCIAL_BILLABLE_GATE) != 0
1334 {
1335 return false;
1336 }
1337
1338 if (entry_policy_mask & MASK_BILATERAL_IDENTITY_LOCKED) != 0
1340 && (requesting_agent_signature_flags & MASK_AUTHENTICATED_NATURAL_PERSON) == 0
1341 {
1342 return false;
1343 }
1344
1345 true
1346}
1347
1348pub struct QuinIncrementalScanner<'a> {
1349 pub file_descriptor: &'a File,
1350 pub block_sector_offsets: &'a [u64],
1351 pub current_cursor: usize,
1352 pub agent_signature_attributes: u16,
1353 pub allocated_working_buffer: QualiaSuperBlock,
1355}
1356
1357impl<'a> Stream for QuinIncrementalScanner<'a> {
1358 type Item = Result<Vec<NQuin>, std::io::Error>;
1359
1360 fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1361 if self.current_cursor >= self.block_sector_offsets.len() {
1362 return Poll::Ready(None); }
1364
1365 let file_offset = self.block_sector_offsets[self.current_cursor];
1366 if file_offset == 0 {
1367 return Poll::Ready(None);
1368 }
1369
1370 #[cfg(target_family = "unix")]
1371 {
1372 use std::os::unix::fs::FileExt;
1373
1374 let destination_ptr = &mut self.allocated_working_buffer as *mut _ as *mut u8;
1376 let byte_slice =
1377 unsafe { std::slice::from_raw_parts_mut(destination_ptr, BLOCK_MULTIPLIER_SIZE) };
1378
1379 if let Err(e) = self.file_descriptor.read_exact_at(byte_slice, file_offset) {
1380 return Poll::Ready(Some(Err(e)));
1381 }
1382 }
1383
1384 #[cfg(target_family = "windows")]
1385 {
1386 use std::os::windows::fs::FileExt;
1387
1388 let destination_ptr = &mut self.allocated_working_buffer as *mut _ as *mut u8;
1389 let byte_slice =
1390 unsafe { std::slice::from_raw_parts_mut(destination_ptr, BLOCK_MULTIPLIER_SIZE) };
1391
1392 let mut bytes_read = 0;
1393 while bytes_read < BLOCK_MULTIPLIER_SIZE {
1394 match self.file_descriptor.seek_read(
1395 &mut byte_slice[bytes_read..],
1396 file_offset + bytes_read as u64,
1397 ) {
1398 Ok(0) => {
1399 return Poll::Ready(Some(Err(std::io::Error::new(
1400 std::io::ErrorKind::UnexpectedEof,
1401 "failed to fill whole buffer",
1402 ))))
1403 }
1404 Ok(n) => bytes_read += n,
1405 Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1406 Err(e) => return Poll::Ready(Some(Err(e))),
1407 }
1408 }
1409 }
1410
1411 let sampling_quin = self.allocated_working_buffer.quin_ledger[0];
1416
1417 if !sampling_quin.verify_ecc_parity() {
1418 return Poll::Ready(Some(Err(std::io::Error::new(
1419 std::io::ErrorKind::InvalidData,
1420 "Quin failed ECC parity check - Sector corrupted",
1421 ))));
1422 }
1423
1424 match sampling_quin.identify_routing_lane() {
1425 PermissiveRoutingLane::EnforcePermissiveCommons => {
1426 let bitmask = sampling_quin.extract_clean_metadata_value() as u16;
1427 if !evaluate_permissive_runtime_gate(bitmask, self.agent_signature_attributes) {
1428 return Poll::Ready(Some(Err(std::io::Error::new(
1429 std::io::ErrorKind::PermissionDenied,
1430 "Target resource permissive commons access criteria unfulfilled",
1431 ))));
1432 }
1433 }
1434 PermissiveRoutingLane::EnforceBilateralMicroCommons => {
1435 let _relation_token = sampling_quin.extract_clean_metadata_value();
1436 if (self.agent_signature_attributes & MASK_AUTHENTICATED_NATURAL_PERSON) == 0 {
1438 return Poll::Ready(Some(Err(std::io::Error::new(
1439 std::io::ErrorKind::PermissionDenied,
1440 "Protected Bilateral Micro-Commons authorization token missing",
1441 ))));
1442 }
1443 }
1444 PermissiveRoutingLane::PassthroughStandard => {
1445 }
1447 PermissiveRoutingLane::SpatiotemporalAmbiguous => {
1448 }
1450 }
1451
1452 self.current_cursor += 1;
1453 let elements_in_frame = self.allocated_working_buffer.active_quin_count as usize;
1454
1455 let mut emitted_vector_slice = Vec::with_capacity(elements_in_frame);
1461 for i in 0..elements_in_frame {
1462 emitted_vector_slice.push(self.allocated_working_buffer.quin_ledger[i]);
1463 }
1464
1465 Poll::Ready(Some(Ok(emitted_vector_slice)))
1466 }
1467}
1468
1469impl Drop for QualiaSuperBlock {
1470 fn drop(&mut self) {
1471 unsafe {
1473 std::ptr::write_volatile(self as *mut _, std::mem::zeroed());
1474 }
1475 }
1476}
1477
1478#[cfg(any(
1482 not(target_arch = "wasm32"),
1483 feature = "wasm-scientific",
1484 feature = "wasm-full"
1485))]
1486pub mod deontic_logic;
1487#[cfg(any(
1488 not(target_arch = "wasm32"),
1489 feature = "wasm-logic",
1490 feature = "wasm-scientific",
1491 feature = "wasm-full"
1492))]
1493pub mod epistemic;
1494pub mod storage;
1495#[cfg(not(target_arch = "wasm32"))]
1496pub mod sync;
1497#[cfg(any(
1498 not(target_arch = "wasm32"),
1499 feature = "wasm-logic",
1500 feature = "wasm-scientific",
1501 feature = "wasm-full"
1502))]
1503pub mod wal;
1504
1505#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
1511pub mod gguf_bridge;
1512#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
1513pub use gguf_bridge as inference_runtime;
1514pub mod mcp;
1534#[cfg(any(
1535 not(target_arch = "wasm32"),
1536 feature = "wasm-logic",
1537 feature = "wasm-scientific",
1538 feature = "wasm-full"
1539))]
1540pub use mcp::mcp_cooperation;
1541#[cfg(not(target_arch = "wasm32"))]
1542pub use mcp::mcp_server;
1543#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
1544pub mod ode_solver;
1545#[cfg(not(target_arch = "wasm32"))]
1546pub mod qpu_ingress;
1547#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
1548pub mod quantum_dft;
1549
1550#[cfg(target_arch = "wasm32")]
1551pub mod wasm_edge;
1552
1553#[cfg(target_arch = "wasm32")]
1554pub mod wasm_storage;
1555
1556pub const fn q_hash(s: &str) -> u64 {
1565 let mut hash: u64 = 0xcbf29ce484222325;
1566 let bytes = s.as_bytes();
1567 let mut i = 0;
1568 while i < bytes.len() {
1569 hash = hash ^ (bytes[i] as u64);
1570 hash = hash.wrapping_mul(0x100000001b3);
1571 i += 1;
1572 }
1573 hash & 0x0FFF_FFFF_FFFF_FFFF
1575}
1576
1577#[macro_export]
1581macro_rules! q_turtle {
1582 ($s:expr, $p:expr, $o:expr) => {
1583 $crate::NQuin {
1584 subject: $crate::q_hash($s),
1585 predicate: $crate::q_hash($p),
1586 object: $crate::q_hash($o),
1587 context: 0,
1588 metadata: 0b01 << 61, parity: 0,
1590 }
1591 };
1592}
1593
1594#[cfg(test)]
1596mod tests {
1597 use super::*;
1598
1599 #[test]
1600 fn qualia_spatial_val() {
1601 use crate::domains::geospatial::spatial::{embed_h3_context, SpatiotemporalQuadTree};
1602
1603 let h3_index = 0x000a1072b59ffff; let context_val = embed_h3_context(h3_index, 10, 42);
1605 let expected_context =
1606 ((10u64 & 0x0F) << 59) | ((42u64 & 0x7F) << 52) | (h3_index & 0x000F_FFFF_FFFF_FFFF);
1607 assert_eq!(
1608 context_val, expected_context,
1609 "Failed to embed H3 index into context"
1610 );
1611
1612 let quad_tree = SpatiotemporalQuadTree::new((0.0, 0.0, 100.0, 100.0));
1613
1614 let results = quad_tree.query_region(10.0, 10.0, 20.0, 20.0, 0, 0);
1615 assert_eq!(
1617 results.len(),
1618 0,
1619 "SpatiotemporalQuadTree placeholder query failed"
1620 );
1621 }
1622
1623 #[test]
1624 fn qualia_logic_val() {
1625 use crate::modalities::logic::core::{WebizenCompiler, WebizenVM};
1626 let q = NQuin {
1627 subject: 0,
1628 predicate: 100,
1629 object: 18,
1630 context: 0,
1631 metadata: 0,
1632 parity: 0,
1633 };
1634
1635 let mut vm = WebizenVM::new();
1636 let bytecode = WebizenCompiler::compile_mock_constraint();
1639 vm.load_bytecode(&bytecode);
1640
1641 let result = vm.execute_constraint(&q);
1642 assert_eq!(
1643 result, true,
1644 "Webizen VM failed to validate constraint byte-code"
1645 );
1646 }
1647
1648 #[test]
1649 fn qualia_webizen_guardianship() {
1650 use crate::modalities::logic::core::{WebizenOpcode, WebizenVM};
1651
1652 let q = NQuin {
1654 subject: 0,
1655 predicate: 0,
1656 object: 0,
1657 context: 0,
1658 metadata: 0b11 << 61 | 500,
1659 parity: 0,
1660 };
1661
1662 let mut vm = WebizenVM::new();
1663 let bytecode = vec![
1664 WebizenOpcode::EvalMetadataMask(499), WebizenOpcode::HaltIfFalse,
1666 ];
1667 vm.load_bytecode(&bytecode);
1668
1669 let result = vm.execute_constraint(&q);
1670 assert_eq!(
1671 result, false,
1672 "Webizen VM failed to deny mismatched EvalMetadataMask"
1673 );
1674 }
1675
1676 #[test]
1677 fn qualia_ldp_rdf_star_mapping() {
1678 use crate::solid_ldp::SolidLdpFacade;
1679 let q = NQuin {
1680 subject: 1,
1681 predicate: 2,
1682 object: 3,
1683 context: 4,
1684 metadata: 0b11 << 61 | 555,
1685 parity: 0,
1686 };
1687
1688 let rdf_output = SolidLdpFacade::serialize_to_rdf_star(&q);
1689
1690 assert!(rdf_output.contains("GRAPH <urn:qualia:context:4>"));
1692 assert!(rdf_output.contains("geo:asWKT"));
1694 assert!(rdf_output.contains("qualia:hardwareIntegrity \"VERIFIED_ECC_PASS\""));
1695 }
1696
1697 #[test]
1698 fn qualia_vector_density() {
1699 use crate::domains::mathematical::geometric::{
1700 extract_spatial_projection, VectorSectorMap,
1701 };
1702 let q = NQuin {
1703 subject: 0,
1704 predicate: 0,
1705 object: 0,
1706 context: 0,
1707 metadata: 42,
1708 parity: 0,
1709 };
1710 let projection = extract_spatial_projection(&q);
1711
1712 let sector_map = VectorSectorMap {
1713 sector_id: 2,
1714 active: true,
1715 }; assert_eq!(
1717 sector_map.contains(projection),
1718 true,
1719 "VectorSectorMap failed to include point within bounding hull"
1720 );
1721
1722 let out_of_bounds_map = VectorSectorMap {
1723 sector_id: 3,
1724 active: true,
1725 };
1726 assert_eq!(
1727 out_of_bounds_map.contains(projection),
1728 false,
1729 "VectorSectorMap failed to prune out-of-bounds point"
1730 );
1731 }
1732
1733 #[test]
1734 fn qualia_validate_volatile_drop() {
1735 let mut block = Box::new(unsafe { std::mem::zeroed::<QualiaSuperBlock>() });
1736 block.block_sequence_id = 12345;
1737 assert_eq!(block.block_sequence_id, 12345);
1738 drop(block);
1739 }
1740
1741 #[test]
1742 fn qualia_validate_quin() {
1743 assert_eq!(
1744 std::mem::size_of::<NQuin>(),
1745 48,
1746 "NQuin must be exactly 48 bytes"
1747 );
1748 }
1749
1750 #[test]
1751 fn qualia_validate_ecc() {
1752 let mut q = NQuin {
1753 subject: 0,
1754 predicate: 0,
1755 object: 0,
1756 context: 0,
1757 metadata: 0,
1758 parity: 0,
1759 };
1760 assert_eq!(q.verify_ecc_parity(), true, "Valid ECC parity should pass");
1761
1762 q.parity = u64::MAX;
1763 assert_eq!(
1764 q.verify_ecc_parity(),
1765 false,
1766 "Corrupted ECC parity should fail"
1767 );
1768 }
1769
1770 #[test]
1771 fn qualia_validate_alignment() {
1772 assert_eq!(
1773 std::mem::size_of::<QualiaSuperBlock>(),
1774 40960,
1775 "QualiaSuperBlock must be exactly 40960 bytes (10 sectors)"
1776 );
1777 assert_eq!(
1778 std::mem::align_of::<QualiaSuperBlock>(),
1779 4096,
1780 "QualiaSuperBlock must be page aligned (4096 bytes)"
1781 );
1782 }
1783
1784 #[test]
1785 fn qualia_validate_routing() {
1786 let q1 = NQuin {
1790 subject: 0,
1791 predicate: 0,
1792 object: 0,
1793 context: 0,
1794 metadata: 0b00u64 << 61 | 12345,
1795 parity: 0,
1796 };
1797 assert_eq!(
1798 q1.identify_routing_lane(),
1799 PermissiveRoutingLane::PassthroughStandard
1800 );
1801 assert_eq!(q1.extract_lamport_clock(), 12345);
1802
1803 let q2 = NQuin {
1804 subject: 0,
1805 predicate: 0,
1806 object: 0,
1807 context: 0,
1808 metadata: 0b01u64 << 61 | 67890,
1809 parity: 0,
1810 };
1811 assert_eq!(
1812 q2.identify_routing_lane(),
1813 PermissiveRoutingLane::EnforcePermissiveCommons
1814 );
1815 assert_eq!(q2.extract_lamport_clock(), 67890);
1816
1817 let q3 = NQuin {
1818 subject: 0,
1819 predicate: 0,
1820 object: 0,
1821 context: 0,
1822 metadata: 0b10u64 << 61 | 42,
1823 parity: 0,
1824 };
1825 assert_eq!(
1826 q3.identify_routing_lane(),
1827 PermissiveRoutingLane::EnforceBilateralMicroCommons
1828 );
1829 assert_eq!(q3.extract_lamport_clock(), 42);
1830
1831 let q4 = NQuin {
1832 subject: 0,
1833 predicate: 0,
1834 object: 0,
1835 context: 0,
1836 metadata: 0b11u64 << 61 | 999,
1837 parity: 0,
1838 };
1839 assert_eq!(
1840 q4.identify_routing_lane(),
1841 PermissiveRoutingLane::SpatiotemporalAmbiguous
1842 );
1843 assert_eq!(q4.extract_lamport_clock(), 999);
1844 }
1845
1846 #[test]
1847 fn nquin_metadata_v3_layout() {
1848 let mut q = NQuin::default();
1849
1850 q.set_quin_type(0b1001);
1852 assert_eq!(q.get_quin_type(), 0b1001);
1853 assert_eq!(
1855 q.identify_routing_lane(),
1856 PermissiveRoutingLane::PassthroughStandard
1857 );
1858
1859 q.set_sensitivity_tier(NQuin::SENSITIVITY_TIER_MEDICAL);
1861 assert_eq!(q.get_sensitivity_tier(), NQuin::SENSITIVITY_TIER_MEDICAL);
1862
1863 q.set_lamport_clock(0xDEAD_BEEF);
1865 assert_eq!(q.extract_lamport_clock(), 0xDEAD_BEEF);
1866
1867 assert_eq!(q.get_quin_type(), 0b1001);
1869 assert_eq!(q.get_sensitivity_tier(), NQuin::SENSITIVITY_TIER_MEDICAL);
1870 assert_eq!(q.extract_lamport_clock(), 0xDEAD_BEEF);
1871
1872 q.recalculate_parity();
1874 assert!(q.verify_ecc_parity());
1875 }
1876
1877 #[test]
1878 fn engine_version_matches_cargo_pkg_version() {
1879 assert_eq!(ENGINE_VERSION, env!("CARGO_PKG_VERSION"));
1880 assert!(!ENGINE_VERSION.is_empty());
1881 }
1882}
1883
1884#[cfg(not(target_arch = "wasm32"))]
1885pub mod p2p;
1886
1887#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
1888pub mod domains;
1889#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
1890pub mod solvers;
1891
1892#[cfg(target_os = "linux")]
1893extern crate io_uring;