Skip to main content

qualia_core_db/
lib.rs

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-webcivics",
13        feature = "wasm-logic",
14        feature = "wasm-scientific",
15        feature = "wasm-llm",
16        feature = "wasm-playground",
17        feature = "wasm-full",
18        feature = "wasm-webcivics"
19    )
20))]
21compile_error!(
22    "wasm-ontology is an exclusive lite profile; build heavier WASM products separately"
23);
24
25// --- services/ category (reorg) ---
26pub mod services;
27#[cfg(not(target_arch = "wasm32"))]
28pub use services::chat_relay_daemon;
29#[cfg(not(target_arch = "wasm32"))]
30pub use services::daemon;
31#[cfg(not(target_arch = "wasm32"))]
32pub use services::daemon_graph;
33#[cfg(not(target_arch = "wasm32"))]
34pub use services::daemon_query;
35#[cfg(not(target_arch = "wasm32"))]
36pub use services::daemon_swarm;
37#[cfg(not(target_arch = "wasm32"))]
38pub use services::daemon_tensor;
39#[cfg(not(target_arch = "wasm32"))]
40pub use services::ilp_dispatcher;
41#[cfg(not(target_arch = "wasm32"))]
42pub use services::pulse_transport;
43#[cfg(not(target_arch = "wasm32"))]
44pub use services::rpc;
45pub use services::solid_ldp;
46#[cfg(not(target_arch = "wasm32"))]
47pub use services::webizen_server;
48#[cfg(not(target_arch = "wasm32"))]
49pub use services::webtorrent_routes;
50#[cfg(not(target_arch = "wasm32"))]
51pub use services::webtorrent_seeder;
52// --- medical/ category (reorg) ---
53pub mod medical;
54#[cfg(not(target_arch = "wasm32"))]
55pub use medical::comorbidity_eval;
56#[cfg(not(target_arch = "wasm32"))]
57pub use medical::dicom;
58#[cfg(not(target_arch = "wasm32"))]
59pub use medical::dicom_ingest;
60// --- query/ category (reorg) ---
61pub mod query;
62pub use query::cbor_compiler;
63pub use query::graph_accel;
64pub use query::graph_index;
65#[cfg(not(target_arch = "wasm32"))]
66pub use query::graph_proof;
67pub use query::indexing;
68#[cfg(not(target_arch = "wasm32"))]
69pub use query::ingest;
70#[cfg(not(target_arch = "wasm32"))]
71pub use query::ingest_job;
72#[cfg(any(
73    not(target_arch = "wasm32"),
74    feature = "wasm-webcivics",
75    feature = "wasm-logic",
76    feature = "wasm-scientific",
77    feature = "wasm-full"
78))]
79pub use query::ingestion;
80pub use query::lexicon;
81pub use query::mini_parser;
82#[cfg(not(target_arch = "wasm32"))]
83pub use query::ontology_loader;
84#[cfg(any(
85    not(target_arch = "wasm32"),
86    feature = "wasm-webcivics",
87    feature = "wasm-logic",
88    feature = "wasm-scientific",
89    feature = "wasm-full"
90))]
91pub use query::query_compiler;
92pub use query::query_engine;
93pub use query::rdf_star;
94pub use query::resolve;
95pub use query::resolver;
96#[cfg(any(
97    not(target_arch = "wasm32"),
98    feature = "wasm-ontology",
99    feature = "wasm-webcivics",
100    feature = "wasm-logic",
101    feature = "wasm-scientific",
102    feature = "wasm-full"
103))]
104pub use query::shacl_compiler;
105pub use query::spawn_decay;
106pub use query::temporal_graph;
107pub use query::temporal_scrub;
108// --- platform/ category (reorg) ---
109pub mod platform;
110#[cfg(not(target_arch = "wasm32"))]
111pub use platform::device_benchmark;
112pub use platform::git_bridge;
113#[cfg(not(target_arch = "wasm32"))]
114pub use platform::hardware_passport;
115#[cfg(target_os = "android")]
116pub use platform::jni_bridge;
117pub use platform::kml_bridge;
118#[cfg(not(target_arch = "wasm32"))]
119pub use platform::local_scheduler;
120#[cfg(all(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
121pub use platform::npu_ffi;
122#[cfg(not(target_arch = "wasm32"))]
123pub use platform::platform_scheduler;
124pub use platform::tee_ffi;
125// --- inference/ category (reorg) ---
126pub mod inference;
127// Inference-runtime components (honest names); `llm_*` retained as transitional aliases.
128pub use inference::agent;
129#[cfg(not(target_arch = "wasm32"))]
130pub use inference::ambient_orchestration;
131pub use inference::application_profile;
132pub use inference::application_profile::{
133    active_application_profile, apply_application_profile, bootstrap_application_profile,
134    set_application_profile, ApplicationProfile,
135};
136pub use inference::compute_universe;
137#[cfg(all(not(target_arch = "wasm32"), feature = "cuda"))]
138pub use inference::cuda_lane::{
139    cache_dense_weight, clear_weight_cache, dense_weight_cached, device_kv_ready,
140    ensure_device_kv_cache, preload_q4k_soa_weights, q4k_device_weight_count, try_cuda_batch_gemv,
141    try_cuda_batch_gemv_cached, try_cuda_batch_gemv_cached_only, try_cuda_mega_pass,
142    try_q4k_soa_attention_device, try_q4k_soa_ffn_block, try_q4k_soa_ffn_block_residual,
143    try_q4k_soa_fused_swiglu, try_q4k_soa_gemv, try_q4k_soa_qkv, warm_cuda_context,
144    weight_cache_len, weight_fingerprint, MegaPassLayerDims, MegaPassLayerWeights, MAX_DENSE_ELEMS,
145};
146#[cfg(target_os = "windows")]
147pub use inference::directml_bridge;
148pub use inference::ggml_quants;
149pub use inference::gguf_sharder;
150pub use inference::inference_agent;
151pub use inference::inference_agent as llm_agent;
152pub use inference::inference_awq;
153pub use inference::inference_awq as llm_awq;
154#[cfg(not(target_arch = "wasm32"))]
155pub use inference::inference_bench;
156#[cfg(not(target_arch = "wasm32"))]
157pub use inference::inference_bench as llm_bench;
158#[cfg(target_arch = "wasm32")]
159pub use inference::inference_bench_wasm as llm_bench;
160pub use inference::inference_eval;
161pub use inference::inference_eval as llm_eval;
162#[cfg(feature = "gpu-runtime")]
163pub use inference::inference_gpu_profiler;
164#[cfg(feature = "gpu-runtime")]
165pub use inference::inference_gpu_profiler as llm_gpu_profiler;
166pub use inference::inference_kernel_parity;
167pub use inference::inference_kernel_parity as llm_kernel_parity;
168pub use inference::inference_modes;
169pub use inference::inference_modes::{
170    active_inference_mode, apply_mode_toggles, bootstrap_inference_mode, fast_verify_html_default,
171    post_turn_verify_enabled, prefer_tensor_core_gemm, quant_graph_grounding_enabled,
172    rights_mode_enabled, sentinel_mid_decode_enabled, set_inference_mode, InferenceMode,
173};
174#[cfg(not(target_arch = "wasm32"))]
175pub use inference::inference_path_selector;
176#[cfg(not(target_arch = "wasm32"))]
177pub use inference::inference_path_selector::{
178    apply_inference_path_plan, bootstrap_optimal_inference_path, format_path_plan,
179    last_inference_path_plan, path_auto_enabled, resolve_inference_path_plan, run_path_select_cli,
180    ComputeLane, InferencePathPlan, QuantProfile,
181};
182#[cfg(not(target_arch = "wasm32"))]
183pub use inference::kv_capture;
184pub use inference::kv_dict;
185#[cfg(not(target_arch = "wasm32"))]
186pub use inference::kv_dict_runtime;
187#[cfg(not(target_arch = "wasm32"))]
188pub use inference::lab;
189#[cfg(not(target_arch = "wasm32"))]
190pub use inference::lab::{
191    append_run_csv, audit_hot_path, calibrate_device_roof, default_search_space,
192    format_lockin_summary, run_ablation_matrix, run_auto_improve, run_decode_timeline,
193    run_q4k_soa_microbench, AblationRow, AutoImproveConfig, DecodeTimeline, DeviceRoof,
194    ExperimentRun, HotPathAudit, LabConfig, LockInPackage, MicrobenchResult, TrialResult,
195    CSV_HEADER,
196};
197#[cfg(any(target_os = "macos", target_os = "ios"))]
198pub use inference::metal_bridge;
199pub use inference::metal_lane;
200pub use inference::neuro_symbolic_sieve;
201pub use inference::orchestrator;
202pub use inference::post_turn_verify;
203pub use inference::post_turn_verify::{
204    maybe_verify_turn, return_html_as_text, verify_and_heal_turn, VerifiedTurn, VerifyCheck,
205};
206pub use inference::prompt_lookup;
207pub use inference::qualia_hybrid;
208pub use inference::qualia_hybrid::{
209    apply_graph_logit_bias, force_fact_tokens, graph_force_enabled, prepare_hybrid_decode,
210    propose_best_draft, propose_fact_draft, publish_graph_route_from_prompt,
211    publish_grounding_obligation, publish_prompt_query_tensor, GRAPH_LOGIT_BIAS,
212};
213pub use inference::quant_graph_grounding;
214pub use inference::quant_graph_grounding::{
215    export_fact_quins, fact_count, ground_generation, load_facts_from_tsv, lookup_capital_object,
216    maybe_ground_generation, register_capital_fact, register_fact, reset_fact_store_to_defaults,
217    seed_facts_from_bundled, GroundingFact, GroundingResult, CTX_GROUNDING, P_CAPITAL_OF,
218};
219#[cfg(not(target_arch = "wasm32"))]
220pub use inference::residency_planner;
221pub use inference::resident_model;
222pub use inference::safetensor;
223pub use inference::sampler;
224pub use inference::semantic_culler;
225pub use inference::spatial_sieve;
226pub use inference::tensor_roles;
227pub use inference::ternary;
228#[cfg(all(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
229pub use inference::ternary_gpu;
230pub use inference::topk;
231// W7: GPU thermal/power telemetry + auto-cap governor (native-only). Exposes the UI-reachable mode
232// switch (`set_gpu_auto_cap` / `gpu_auto_cap_enabled`) and `sample_gpu_thermal()` telemetry.
233#[cfg(not(target_arch = "wasm32"))]
234pub use inference::thermal_telemetry;
235#[cfg(all(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
236pub use inference::topk_gpu;
237pub mod lora;
238// --- q42/ category (reorg) ---
239pub mod q42;
240pub mod sensing;
241pub use q42::design_encode;
242pub use q42::execution_profile;
243pub use q42::journal;
244pub use q42::journal::{JournalHeader, JournalTransaction, MutableQ42Session, Q42Journal};
245pub use q42::machine_gpu_profile;
246pub use q42::model_helper;
247pub use q42::p64_weight;
248/// Backward-compatible module name retained for existing inference and
249/// transcode harnesses while the on-disk magic/API is P64.
250pub use q42::p64_weight as q42_weight;
251#[cfg(not(target_arch = "wasm32"))]
252pub use q42::q42_lexicon;
253#[cfg(not(target_arch = "wasm32"))]
254pub use q42::q42_reader;
255pub use q42::q42_volume;
256pub use q42::yaml_ld_q42;
257// --- extensions/ category (reorg) ---
258pub mod extensions;
259pub use extensions::extension_bus;
260pub use extensions::extension_manifest;
261#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-llm"))]
262pub use extensions::resource_catalog;
263pub mod modalities;
264// --- identity/ category (reorg) ---
265pub mod did_qi;
266pub mod identity;
267pub use identity::agency;
268pub use identity::identifier;
269#[cfg(not(target_arch = "wasm32"))]
270pub use identity::key_vault;
271pub use identity::profiles;
272pub use identity::vault_manifest;
273pub use identity::webizen_identifiers;
274pub mod gpu_context;
275pub mod shaders;
276#[cfg(all(not(target_arch = "wasm32"), feature = "wgsl-forge"))]
277pub mod wgsl_forge;
278#[cfg(feature = "gpu-runtime")]
279pub use etalon_agent;
280pub use etalon_nquin;
281pub use etalon_render;
282pub use etalon_tensor;
283#[cfg(feature = "gpu-runtime")]
284pub use etalon_wasm;
285#[cfg(feature = "gpu-runtime")]
286pub use etalon_wgsl_forge;
287// --- foundation/ category (reorg) ---
288pub mod foundation;
289pub use foundation::crdt;
290pub use foundation::frame_layout;
291pub use foundation::fuzz_testing;
292pub use foundation::telemetry;
293pub use foundation::topology_draft;
294// --- net/ category (reorg) ---
295pub mod net;
296#[cfg(not(target_arch = "wasm32"))]
297pub use net::acoustic_ble_mesh;
298#[cfg(not(target_arch = "wasm32"))]
299pub use net::ebpf_filter;
300#[cfg(not(target_arch = "wasm32"))]
301pub use net::ebpf_firewall;
302#[cfg(not(target_arch = "wasm32"))]
303pub use net::host_topology;
304#[cfg(not(target_arch = "wasm32"))]
305pub use net::nym_adapter;
306pub use net::sonic_token;
307pub mod audio;
308/// `.hmc` — a transparent container-of-files bundle for shipping a set of
309/// sealed assets (`.10d` / `.q42` / `.p64`) as one attestable unit. Available to
310/// both native and WASM builds (native adds the zero-copy `BundleMmap`).
311pub mod bundle;
312/// Deterministic fixed-tick simulation engine (QG-09).
313pub mod simulation;
314pub use simulation::fixed_tick;
315/// `.10d` living-container v1 — normative header, axis-role taxonomy, and
316/// metric-completeness descriptor for the 10-D tensor substrate. P0.1 barrier
317/// task. Available to browser/WASM builds (P0.8 parity target). See
318/// `docs/plans/native-computational-geometry-EXECUTION.md` P0.1.
319pub mod container_10d;
320/// Semantic-instrument collectables (SI-03): Demo-labelled HMC of HCF + N3 + `.10d`.
321pub mod semantic_instruments;
322pub mod tensor;
323pub mod topology;
324// geometric_algebra moved into solvers/ (it is a math solver, not a logic modality);
325// re-exported here so `crate::geometric_algebra::*` paths keep resolving. Gated to match the
326// `solvers` module below — on wasm32 it only exists under the `wasm-scientific` feature.
327#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
328pub use crate::solvers::geometric_algebra;
329// --- governance/ category (reorg) ---
330pub mod governance;
331pub use governance::illocution;
332pub use governance::modal_kind;
333pub use governance::provenance;
334#[cfg(not(target_arch = "wasm32"))]
335pub use governance::web_civics;
336pub use governance::webizen;
337pub use governance::webizen_bytecode;
338#[cfg(not(target_arch = "wasm32"))]
339pub use governance::webizen_sync;
340pub use governance::webizen_validator;
341pub mod sparql_library;
342pub use sparql_library::*;
343
344/// Hypermedia semantic library — asset ⊕ analytics ⊕ related-assets bound as a semantic graph (not a
345/// directory). See `docs/plans/hypermedia-semantic-library.md`.
346#[cfg(not(all(
347    target_arch = "wasm32",
348    any(
349        all(
350            feature = "wasm-ontology",
351            not(any(
352                feature = "wasm-webcivics",
353                feature = "wasm-logic",
354                feature = "wasm-scientific",
355                feature = "wasm-full",
356                feature = "portal"
357            ))
358        ),
359        all(
360            feature = "wasm-webcivics",
361            not(any(
362                feature = "wasm-logic",
363                feature = "wasm-scientific",
364                feature = "wasm-full",
365                feature = "portal"
366            ))
367        )
368    )
369)))]
370pub mod agent_runtime;
371pub mod clinical_engine;
372#[cfg(all(
373    target_arch = "wasm32",
374    any(feature = "wasm-playground", feature = "wasm-full")
375))]
376pub(crate) mod clinical_playground;
377/// Entity-view kernel: entity id, observer status, rights filter, attribution, packages (shared by whole desktop; not "mindware-only").
378pub mod entity_view;
379pub mod hypermedia;
380/// N9: Hypermedia asset authoring — image, video, 3D, interactive, portals, DMX.
381pub mod hypermedia_authoring;
382/// Document NLP (tokenize, gazetteer, span plans). Engine capability, not Vibe.
383pub mod nlp;
384/// Q42LEX lexicon format. The byte-view reader ([`q42_lex::Q42LexMmap`]) and
385/// serializers are transport-neutral and compile on wasm32; only the
386/// filesystem/mmap handles ([`q42_lex::Q42LexFile`], [`q42_lex::Q42Lexicon`]
387/// path loaders) stay native.
388pub mod q42_lex;
389/// Q42LEX v4 writer: paged lexicon with per-page namespace dictionaries.
390pub mod q42_lex_ns;
391// The ontology MCP binary deliberately contains only its explicit reasoning
392// kernel (`modalities_lite`); it has no VibeScript runtime. Other WASM
393// profiles retain the full browser capability host — except `wasm-webcivics`,
394// which is a slim decision-evidence package (typed wasm_bridge only; Vibe
395// LocalHost lives in the separate `vibe-wasm` crate).
396#[cfg(not(all(
397    target_arch = "wasm32",
398    any(
399        all(
400            feature = "wasm-ontology",
401            not(any(
402                feature = "wasm-webcivics",
403                feature = "wasm-logic",
404                feature = "wasm-scientific",
405                feature = "wasm-full",
406                feature = "portal"
407            ))
408        ),
409        all(
410            feature = "wasm-webcivics",
411            not(any(
412                feature = "wasm-logic",
413                feature = "wasm-scientific",
414                feature = "wasm-full",
415                feature = "portal"
416            ))
417        )
418    )
419)))]
420#[path = "poet_host/mod.rs"]
421pub mod vibe_host;
422#[cfg(any(all(target_arch = "wasm32", feature = "device-harness"), all(test, not(target_arch = "wasm32"))))]
423mod etalon_vibe_browser;
424/// Compatibility name for code written before the Vibe execution layer was
425/// separated from Poet, its current UI/client. New integrations use
426/// [`vibe_host`].
427#[cfg(not(all(
428    target_arch = "wasm32",
429    any(
430        all(
431            feature = "wasm-ontology",
432            not(any(
433                feature = "wasm-webcivics",
434                feature = "wasm-logic",
435                feature = "wasm-scientific",
436                feature = "wasm-full",
437                feature = "portal"
438            ))
439        ),
440        all(
441            feature = "wasm-webcivics",
442            not(any(
443                feature = "wasm-logic",
444                feature = "wasm-scientific",
445                feature = "wasm-full",
446                feature = "portal"
447            ))
448        )
449    )
450)))]
451pub use vibe_host as poet_host;
452pub mod qubo_compiler;
453pub mod render;
454/// N8: Research / investigation / epistemics — enquiry, corpus, dark links, inference chains,
455/// investigations, hypothesis graphs, epistemic assessment, sentiment analysis.
456pub mod research;
457#[cfg(all(target_arch = "wasm32", feature = "portal"))]
458pub mod spatial_wasm;
459pub mod text_span;
460#[cfg(all(
461    target_arch = "wasm32",
462    any(
463        feature = "wasm-webcivics",
464        feature = "wasm-logic",
465        feature = "wasm-scientific",
466        feature = "wasm-full",
467        feature = "wasm-playground",
468        feature = "wasm-webcivics"
469    )
470))]
471pub mod wasm_bridge;
472#[cfg(not(target_arch = "wasm32"))]
473pub mod wasm_bridge;
474#[cfg(all(
475    target_arch = "wasm32",
476    feature = "portal",
477    not(any(
478        feature = "wasm-webcivics",
479        feature = "wasm-logic",
480        feature = "wasm-scientific",
481        feature = "wasm-full",
482        feature = "wasm-playground",
483        feature = "wasm-webcivics"
484    ))
485))]
486pub mod wasm_bridge_core;
487#[cfg(all(target_arch = "wasm32", feature = "wasm-llm"))]
488pub mod wasm_llm;
489#[cfg(all(target_arch = "wasm32", feature = "portal"))]
490pub use render::portal::QualiaPortal;
491#[cfg(all(target_arch = "wasm32", feature = "portal"))]
492pub use render::portal_wasm::{create_canvas, init_panic_hook, WebEngine};
493#[cfg(all(target_arch = "wasm32", feature = "portal"))]
494pub use spatial_wasm::{
495    design_encode_wasm, export_tensor_buffer_wasm, export_tensor_slice_wasm,
496    geosparql_operation_wasm, sample_browser_telemetry_wasm, spatial_encode_wasm,
497};
498#[cfg(all(
499    target_arch = "wasm32",
500    any(
501        feature = "wasm-webcivics",
502        feature = "wasm-logic",
503        feature = "wasm-scientific",
504        feature = "wasm-full",
505        feature = "wasm-playground",
506        feature = "wasm-webcivics"
507    )
508))]
509pub use wasm_bridge::{
510    parse_cbor_ld_wasm, parse_json_wasm, parse_n3logic_wasm, parse_turtle_wasm,
511    parse_yaml_ld_q42_wasm,
512};
513#[cfg(all(
514    target_arch = "wasm32",
515    feature = "portal",
516    not(any(
517        feature = "wasm-webcivics",
518        feature = "wasm-logic",
519        feature = "wasm-scientific",
520        feature = "wasm-full",
521        feature = "wasm-playground",
522        feature = "wasm-webcivics"
523    ))
524))]
525pub use wasm_bridge_core::{parse_cbor_ld_wasm, parse_json_wasm};
526pub mod storage_driver;
527#[cfg(all(
528    target_arch = "wasm32",
529    any(feature = "wasm-playground", feature = "wasm-full")
530))]
531pub mod wasm_playground;
532#[cfg(not(target_arch = "wasm32"))]
533pub mod zns_storage;
534// --- crypto/ category (reorg) ---
535pub mod crypto;
536#[cfg(feature = "zk-culling")]
537pub use crypto::deontic_circuit;
538pub use crypto::fiduciary_crypto;
539#[cfg(feature = "pq-kem")]
540pub use crypto::pq_kem_shim;
541#[cfg(not(target_arch = "wasm32"))]
542#[cfg(feature = "sanctuary-crypto")]
543pub use crypto::sanctuary_crypto;
544pub use crypto::verifiable_credential;
545pub use crypto::zk_proofs;
546#[cfg(not(target_arch = "wasm32"))]
547pub mod csd_storage;
548// pub mod clinical_engine; // Temporarily disabled
549// The portal uses the portable portions of this tree (geometry, symbolic
550// algebra, and computational economics). Individual native-only libraries are
551// gated within `specialized_libs`, so the top-level registry must be present
552// for the corresponding Vibe capabilities to resolve in the browser.
553pub mod specialized_libs;
554
555// pub use specialized_libs::linear_algebra;
556// pub use specialized_libs::statistical_computing;
557// // pub use specialized_libs::cryptographic_library;
558// pub use specialized_libs::physics_simulation;
559// pub use specialized_libs::machine_learning;
560// pub use specialized_libs::financial_modeling;
561// pub use specialized_libs::chemistry_modeling;
562// pub use specialized_libs::medical_computing; // Temporarily disabled
563// pub use specialized_libs::engineering_analysis;
564
565pub mod wasm_capabilities;
566
567/// The Global Capability Registry exposes which features are compiled into the
568/// current qualia-core-db binary. This allows the CLI to dynamically self-document
569/// and progressively expose features like SHACL extensions or specific logic modalities.
570/// Crate semver baked in at compile time — shared by daemon `/health`, CLI, and WASM `get_engine_version()`.
571pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
572
573/// Canonical description of an inference capability and the MCP tools that
574/// execute it. Chat prompting and MCP registration both consume this table, so
575/// STEM solvers are exposed as tools rather than reimplemented in the LLM layer.
576#[derive(Debug, Clone, Copy, PartialEq, Eq)]
577pub struct CapabilityDescriptor {
578    pub name: &'static str,
579    pub domain: &'static str,
580    /// Concrete operations implemented by this capability family. This is
581    /// discovery metadata, not a promise that every operation has an MCP route.
582    pub operations: &'static [&'static str],
583    pub mcp_tools: &'static [&'static str],
584    /// `stable`, `partial`, `experimental`, or `fail-closed`.
585    pub maturity: &'static str,
586    /// Surfaces that can currently execute the capability.
587    pub surfaces: &'static [&'static str],
588}
589
590pub const CAPABILITY_DESCRIPTORS: &[CapabilityDescriptor] = &[
591    CapabilityDescriptor {
592        name: "CapabilityDiscovery",
593        domain: "runtime",
594        operations: &[
595            "list capability families",
596            "inspect operations",
597            "inspect maturity",
598            "inspect runtime surfaces",
599        ],
600        mcp_tools: &["list_capabilities"],
601        maturity: "stable",
602        surfaces: &["native", "wasm", "mcp", "cli", "chat"],
603    },
604    CapabilityDescriptor {
605        name: "SHACL",
606        domain: "ontology",
607        operations: &[
608            "validate shapes",
609            "route decentralized shapes",
610            "credential gate",
611            "degrade violations",
612        ],
613        mcp_tools: &["validate_shacl", "shacl_route"],
614        maturity: "stable",
615        surfaces: &["native", "wasm-logic", "mcp", "webizen"],
616    },
617    CapabilityDescriptor {
618        name: "GraphDatabase",
619        domain: "ontology",
620        operations: &[
621            "graph query",
622            "SPARQL query",
623            "identifier resolution",
624            "ontology ingest",
625            "RDF parse and serialize",
626        ],
627        mcp_tools: &["query_graph", "query_sparql", "graph_resolve"],
628        maturity: "stable",
629        surfaces: &["native", "wasm-ontology", "mcp"],
630    },
631    CapabilityDescriptor {
632        name: "DeonticLogic",
633        domain: "logic",
634        operations: &[
635            "obligation",
636            "permission",
637            "prohibition",
638            "defeaters",
639            "expiry",
640            "jural correlation",
641            "policy governance",
642        ],
643        mcp_tools: &["evaluate_modality", "deontic_govern", "jural_correlate"],
644        maturity: "stable",
645        surfaces: &["native", "wasm-logic", "mcp", "webizen"],
646    },
647    CapabilityDescriptor {
648        name: "EpistemicLogic",
649        domain: "logic",
650        operations: &[
651            "knowledge",
652            "belief",
653            "common knowledge",
654            "certainty",
655            "possible-world filtering",
656        ],
657        mcp_tools: &["evaluate_modality"],
658        maturity: "stable",
659        surfaces: &["native", "wasm-logic", "mcp", "webizen"],
660    },
661    CapabilityDescriptor {
662        name: "ParaconsistentLogic",
663        domain: "logic",
664        operations: &[
665            "contradiction detection",
666            "context isolation",
667            "non-explosive merge",
668        ],
669        mcp_tools: &["evaluate_modality"],
670        maturity: "stable",
671        surfaces: &["native", "wasm-logic", "mcp", "webizen"],
672    },
673    CapabilityDescriptor {
674        name: "TemporalAndDescriptionLogic",
675        domain: "logic",
676        operations: &[
677            "LTL globally/finally/next/until/release",
678            "CTL path operators",
679            "description-logic subsumption",
680            "interval reasoning",
681        ],
682        mcp_tools: &["evaluate_modality"],
683        maturity: "partial",
684        surfaces: &["native", "wasm-logic", "mcp"],
685    },
686    CapabilityDescriptor {
687        name: "SymbolicAndDefeasibleLogic",
688        domain: "logic",
689        operations: &[
690            "bounded SAT",
691            "defeasible forward chaining",
692            "ASP stable models",
693            "argumentation semantics",
694            "abductive reasoning",
695        ],
696        mcp_tools: &["symbolic_logic_infer", "evaluate_modality"],
697        maturity: "partial",
698        surfaces: &["native", "mcp", "webizen"],
699    },
700    CapabilityDescriptor {
701        name: "SymbolicAlgebra",
702        domain: "mathematics",
703        operations: &[
704            "parse/evaluate expressions",
705            "simplify",
706            "expand",
707            "differentiate",
708            "symbolic integration",
709            "limits",
710            "assumptions",
711            "trigonometric simplification",
712            "Taylor series",
713            "polynomial roots",
714            "symbolic ODE/PDE",
715        ],
716        mcp_tools: &["cas", "algebra_solve_polynomial"],
717        maturity: "partial",
718        surfaces: &["native", "mcp"],
719    },
720    CapabilityDescriptor {
721        name: "LinearAlgebra",
722        domain: "mathematics",
723        operations: &[
724            "matrix multiply",
725            "transpose",
726            "inverse",
727            "linear solve",
728            "determinant",
729            "LU",
730            "QR",
731            "Cholesky",
732            "SVD",
733            "general eigenvalues",
734            "symmetric eigensystem",
735            "tensor contraction",
736        ],
737        mcp_tools: &["matrix_operation", "algebra_matrix_analyze"],
738        maturity: "stable",
739        surfaces: &["native", "mcp", "webizen"],
740    },
741    CapabilityDescriptor {
742        name: "NumericalCalculus",
743        domain: "mathematics",
744        operations: &[
745            "RK4",
746            "BDF1/BDF2",
747            "Verlet/Ruth/Yoshida symplectic integration",
748            "shooting BVP",
749            "Simpson/trapezoid integration",
750            "sensitivity analysis",
751            "interpolation",
752            "splines",
753            "least-squares polynomial fit",
754        ],
755        mcp_tools: &[],
756        maturity: "stable",
757        surfaces: &["native", "library", "webizen"],
758    },
759    CapabilityDescriptor {
760        name: "Optimization",
761        domain: "mathematics",
762        operations: &[
763            "Nelder-Mead",
764            "bounded Newton-Raphson",
765            "Levenberg-Marquardt",
766            "hill climbing",
767            "simulated annealing",
768            "artificial bee colony",
769        ],
770        mcp_tools: &[],
771        maturity: "stable",
772        surfaces: &["native", "library"],
773    },
774    CapabilityDescriptor {
775        name: "GeometricAlgebra",
776        domain: "mathematics",
777        operations: &[
778            "dot/cross/angle",
779            "geometric product",
780            "outer product",
781            "rotors",
782            "translators",
783            "multivectors",
784            "SIMD kernels",
785        ],
786        mcp_tools: &["geometric_algebra_op"],
787        maturity: "partial",
788        surfaces: &["native", "mcp", "webizen"],
789    },
790    CapabilityDescriptor {
791        name: "ComputationalGeometry",
792        domain: "geometry",
793        operations: &[
794            "robust geometric predicates",
795            "convex hulls",
796            "half-edge topology graphs",
797            "10D geometry feature encoding",
798            ".10d quantized mesh geometry",
799            "Delaunay triangulation",
800            "Voronoi diagrams",
801            "nearest-site query",
802            "primitive generation (box, sphere, cylinder, plane)",
803            "T·R·S transform composition",
804            "scene graph assembly",
805            ".10d asset export with μ provenance",
806            "VR filtration + persistent homology",
807            "CkNN graph Laplacian",
808            "natural-neighbour interpolation",
809        ],
810        mcp_tools: &["computational_geometry", "geometry_manifests"],
811        maturity: "partial",
812        surfaces: &["native", "wasm-scientific", "mcp", "webizen", "renderer"],
813    },
814    CapabilityDescriptor {
815        name: "ComputerVision",
816        domain: "vision",
817        operations: &[
818            "classical CV (blur, edges, features, flow, morph)",
819            "classical + tiled super-resolution (nearest/bilinear/bicubic/lanczos)",
820            "Forge shared_gpu nearest + bicubic resize when Cool",
821            "bio histopathology / radiomics / DICOM-lite",
822            "MeshIR export / quality cleanup / class→σ map",
823            "local CBIR proxy embeddings (aHash/dHash/hist)",
824        ],
825        mcp_tools: &["computer_vision"],
826        maturity: "partial",
827        surfaces: &["native", "mcp", "webizen", "qualia-vision"],
828    },
829    CapabilityDescriptor {
830        name: "NumberTheory",
831        domain: "mathematics",
832        operations: &[
833            "primality",
834            "factorization",
835            "divisors",
836            "GCD/LCM",
837            "modular powers/inverses",
838            "Chinese remainder theorem",
839            "totient",
840            "Mobius",
841            "partitions",
842            "Stirling numbers",
843            "Catalan numbers",
844        ],
845        mcp_tools: &[],
846        maturity: "stable",
847        surfaces: &["native", "library"],
848    },
849    CapabilityDescriptor {
850        name: "SpecialFunctionsAndTransforms",
851        domain: "mathematics",
852        operations: &[
853            "Bessel",
854            "Airy",
855            "zeta",
856            "Legendre",
857            "Chebyshev",
858            "Hermite",
859            "Laguerre",
860            "DFT/IDFT",
861            "Laplace transform",
862            "Z-transform",
863            "unit conversion",
864            "dimensional analysis",
865            "vector calculus",
866        ],
867        mcp_tools: &[],
868        maturity: "stable",
869        surfaces: &["native", "library"],
870    },
871    CapabilityDescriptor {
872        name: "Statistics",
873        domain: "statistics",
874        operations: &[
875            "descriptive statistics",
876            "robust statistics",
877            "Pearson/Spearman/Kendall correlation",
878            "histograms",
879            "linear regression",
880            "normal/t/chi-square/F distributions",
881            "t-tests",
882            "ANOVA",
883            "chi-square tests",
884            "non-parametric tests",
885            "multiple testing",
886            "anomaly detection",
887            "entropy/KL/mutual information",
888        ],
889        mcp_tools: &["statistical_analysis"],
890        maturity: "partial",
891        surfaces: &["native", "mcp", "library"],
892    },
893    CapabilityDescriptor {
894        name: "MachineLearning",
895        domain: "machine-learning",
896        // NOTE: these classical-ML operations are implemented in the
897        // `solvers::learning` tree (60+ files), NOT in
898        // `specialized_libs::machine_learning`, which the `ml_inference`
899        // tool below routes to (that file serves the GGUF-load + MLP-forward
900        // inference path, plus int8 quant/prune/distill). Per the field doc
901        // above, listing an operation here does not imply an MCP route to it.
902        operations: &[
903            "linear/ridge/lasso/Bayesian regression",
904            "KNN/naive Bayes/SVM/discriminant classification",
905            "k-means/GMM/hierarchical clustering",
906            "decision trees/random forests/boosting/BART",
907            "PCA/SOM",
908            "Gaussian processes",
909            "HMM/Kalman",
910            "survival analysis",
911            "MCMC/variational inference",
912            "resampling",
913            "active learning",
914            "bandits",
915            "knowledge-graph embeddings",
916        ],
917        mcp_tools: &["ml_inference"],
918        maturity: "fail-closed",
919        surfaces: &["native", "library"],
920    },
921    CapabilityDescriptor {
922        name: "PhysicsAndODE",
923        domain: "physics",
924        operations: &[
925            "thermodynamics",
926            "CFD",
927            "molecular dynamics",
928            "RK4 ODE",
929            "Thomas-Fermi DFT",
930            "PINN binding affinity",
931            "distributed simulation",
932        ],
933        mcp_tools: &["ode_solve", "qpu_dft"],
934        maturity: "partial",
935        surfaces: &["native", "mcp", "webizen"],
936    },
937    CapabilityDescriptor {
938        name: "Bioinformatics",
939        domain: "bioscience",
940        operations: &[
941            "Smith-Waterman",
942            "Needleman-Wunsch",
943            "DNA/protein alignment",
944            "k-mer frequencies",
945            "MinHash/Jaccard",
946            "UPGMA",
947            "FASTA validation",
948            "DNA translation",
949            "isoelectric point",
950            "peptide cleavage",
951            "fingerprint similarity",
952        ],
953        mcp_tools: &["bioinformatics_align"],
954        maturity: "partial",
955        surfaces: &["native", "mcp", "webizen"],
956    },
957    CapabilityDescriptor {
958        name: "OrganicChemistry",
959        domain: "chemistry",
960        operations: &[
961            "SMILES/InChI validation",
962            "formula and molecular weight",
963            "LogP/TPSA",
964            "Lipinski/Veber/Ghose/Egan",
965            "functional groups",
966            "pKa",
967            "chiral centers",
968            "circular fingerprints",
969            "reaction kinetics",
970            "equilibrium",
971            "green metrics",
972            "BBB permeation",
973            "isotope distributions",
974        ],
975        mcp_tools: &["chemical_analysis", "chemical_descriptors"],
976        maturity: "partial",
977        surfaces: &["native", "mcp", "webizen"],
978    },
979    CapabilityDescriptor {
980        name: "ClinicalRisk",
981        domain: "clinical",
982        operations: &[
983            "Framingham",
984            "CHA2DS2-VASc",
985            "SCORE2",
986            "SOFA",
987            "eGFR/creatinine clearance",
988            "drug interactions",
989            "contraindications",
990            "FHIR validation",
991            "longitudinal trends",
992            "gene expression",
993            "one-compartment pharmacokinetics",
994        ],
995        mcp_tools: &["medical_score", "clinical_risk"],
996        maturity: "partial",
997        surfaces: &["native", "mcp", "webizen"],
998    },
999    CapabilityDescriptor {
1000        name: "FinancialModeling",
1001        domain: "economics",
1002        operations: &[
1003            "Black-Scholes option pricing and Greeks",
1004            "portfolio VaR",
1005            "Sharpe/Sortino",
1006            "maximum drawdown",
1007            "Monte Carlo risk",
1008        ],
1009        mcp_tools: &["financial_model"],
1010        maturity: "partial",
1011        surfaces: &["native", "mcp", "webizen"],
1012    },
1013    CapabilityDescriptor {
1014        name: "EngineeringAnalysis",
1015        domain: "engineering",
1016        operations: &[
1017            "structural analysis",
1018            "thermal conduction",
1019            "linear dynamics",
1020            "stress/displacement",
1021            "fatigue",
1022            "fluid analysis",
1023        ],
1024        mcp_tools: &["engineering_analysis_op"],
1025        maturity: "partial",
1026        surfaces: &["native", "mcp"],
1027    },
1028    CapabilityDescriptor {
1029        name: "CausalFuzzyAndControl",
1030        domain: "reasoning",
1031        operations: &[
1032            "causal reachability",
1033            "but-for and overdetermined cause",
1034            "do-intervention",
1035            "counterfactuals",
1036            "fuzzy t-norms/conorms",
1037            "Mamdani/Sugeno inference",
1038            "type-2 fuzzy sets",
1039            "PID/control feedback",
1040        ],
1041        mcp_tools: &[],
1042        maturity: "stable",
1043        surfaces: &["native", "library", "webizen"],
1044    },
1045    CapabilityDescriptor {
1046        name: "ContractsIdentityAndConsensus",
1047        domain: "governance",
1048        operations: &[
1049            "contract formation",
1050            "capacity",
1051            "delegation/revocation",
1052            "responsibility",
1053            "jural chains",
1054            "socioeconomics",
1055            "identity fabric",
1056            "BFT quorum",
1057            "Lamport/vector clocks",
1058            "legal composition",
1059        ],
1060        mcp_tools: &[
1061            "values_check",
1062            "values_evaluate",
1063            "jural_correlate",
1064            "deontic_govern",
1065            "mcp_cooperate",
1066        ],
1067        maturity: "partial",
1068        surfaces: &["native", "wasm-logic", "mcp", "webizen"],
1069    },
1070    CapabilityDescriptor {
1071        name: "QuantumAndCryptographic",
1072        domain: "quantum-security",
1073        operations: &[
1074            "QUBO formulation",
1075            "classical pre-solve",
1076            "QAOA/SPSA",
1077            "QPU job dispatch",
1078            "DFT bridge",
1079            "sign/encrypt/verify",
1080            "ML-DSA credentials",
1081            "zero-knowledge proof plumbing",
1082            "quantum biology orchestration",
1083        ],
1084        mcp_tools: &["qpu_optimize", "qpu_dft", "qpu_status"],
1085        maturity: "experimental",
1086        surfaces: &["native", "mcp", "webizen"],
1087    },
1088    CapabilityDescriptor {
1089        name: "NLP",
1090        domain: "language",
1091        operations: &[
1092            "tokenize (deterministic UTF-8 prototype)",
1093            "sentence split (deterministic UTF-8 prototype)",
1094            "gazetteer (compiled default lexicon, not NER)",
1095            "ISO dates and unit symbols",
1096            "exact-match coreference plus experimental pronoun sieve",
1097            "keyword-triple search (not GraphRAG)",
1098            "tiny suffix FST demo (not a language pack)",
1099            "rule-demo frames (not FrameNet)",
1100            "rule-demo relations (not OpenIE)",
1101            "symbolic substrate (every-word mentions)",
1102        ],
1103        mcp_tools: &[],
1104        maturity: "experimental",
1105        surfaces: &["native", "library"],
1106    },
1107    CapabilityDescriptor {
1108        name: "Conditioning",
1109        domain: "inference",
1110        operations: &[
1111            "validate profile",
1112            "compile conditioning contract",
1113            "inspect requirement trace",
1114            "evaluate conditioning campaign",
1115            "activate profile version",
1116            "rollback profile version",
1117        ],
1118        mcp_tools: &["conditioning_compile", "conditioning_validate"],
1119        maturity: "stable",
1120        surfaces: &["native", "mcp", "cli", "chat"],
1121    },
1122];
1123
1124/// Bare-metal 40-byte continuous statement container for the Qualia engine.
1125/// Fully optimized for zero-copy memory operations on post-2020 architectures.
1126#[repr(C, align(16))]
1127#[derive(
1128    Debug,
1129    Default,
1130    Clone,
1131    Copy,
1132    PartialEq,
1133    Eq,
1134    Hash,
1135    PartialOrd,
1136    Ord,
1137    Zeroize,
1138    bytemuck::Pod,
1139    bytemuck::Zeroable,
1140    serde::Serialize,
1141    serde::Deserialize,
1142)]
1143pub struct NQuin {
1144    /// Subject identifier code reference index
1145    pub subject: u64,
1146    /// Predicate relation code reference index
1147    pub predicate: u64,
1148    /// Object value or entity code reference index
1149    pub object: u64,
1150    /// Graph Context identifier code reference index
1151    pub context: u64,
1152    /// The Fifth Vector: Metadata, Policy bitmasks, and geometric traits
1153    pub metadata: u64,
1154    /// The Sixth Vector: ECC Parity and Checksum bits (making the Quin 48 bytes)
1155    pub parity: u64,
1156}
1157
1158impl NQuin {
1159    const NESTED_BIT_MASK: u64 = 1 << 63;
1160
1161    #[inline(always)]
1162    /// `true` when the subject is nested.
1163    pub fn is_subject_nested(&self) -> bool {
1164        (self.subject & Self::NESTED_BIT_MASK) != 0
1165    }
1166
1167    #[inline(always)]
1168    /// Subject literal id.
1169    pub fn get_subject_literal_id(&self) -> u64 {
1170        self.subject & !Self::NESTED_BIT_MASK
1171    }
1172
1173    // ── Metadata field bit-layout (v3, post §4.1 migration) ─────────────────
1174    //
1175    // [63:60]  Quin Type  — 4-bit nibble; bits [62:61] are the routing lane
1176    // [59:56]  Sensitivity tier — 4-bit ODRL layer (0=PUBLIC..4=FIDUCIARY)
1177    // [55:32]  Reserved — 24 bits for Phase 2 temporal/spatial flags
1178    // [31:0]   Lamport clock — 32-bit logical clock for CRDT ordering
1179    //
1180    // LoRA context triggers have been moved to LoRAAdapterManager's side-table.
1181
1182    // Routing lane reads bits [62:61] — sub-bits of the Quin Type nibble.
1183    const LANE_MASK: u64 = 0b11 << 61;
1184    const SHIFT_LANE: u32 = 61;
1185
1186    #[inline(always)]
1187    /// PermissiveRoutingLane.
1188    pub fn identify_routing_lane(&self) -> PermissiveRoutingLane {
1189        // Since it's packed, taking reference to field might be unsafe in some contexts,
1190        // but passing self by reference and copying the field is usually fine,
1191        // though `self.metadata` directly copies if it's Copy.
1192        // Let's use `let metadata = { self.metadata };` to safely copy if needed,
1193        // but `self.metadata` usually works if we don't take a reference to it.
1194        let metadata = self.metadata;
1195        let lane_bits = (metadata & Self::LANE_MASK) >> Self::SHIFT_LANE;
1196        match lane_bits {
1197            0x01 => PermissiveRoutingLane::EnforcePermissiveCommons,
1198            0x02 => PermissiveRoutingLane::EnforceBilateralMicroCommons,
1199            0x03 => PermissiveRoutingLane::SpatiotemporalAmbiguous,
1200            _ => PermissiveRoutingLane::PassthroughStandard,
1201        }
1202    }
1203
1204    pub const SENSITIVITY_PUBLIC: u8 = 0x00;
1205    pub const SENSITIVITY_RESTRICTED: u8 = 0x01;
1206    pub const SENSITIVITY_CLASSIFIED: u8 = 0x02;
1207
1208    #[inline(always)]
1209    /// Sensitivity byte.
1210    pub fn get_sensitivity_byte(&self) -> u8 {
1211        (self.context >> 56) as u8
1212    }
1213
1214    #[inline(always)]
1215    /// Sets the sensitivity byte.
1216    pub fn set_sensitivity_byte(&mut self, sensitivity: u8) {
1217        // Clear top 8 bits
1218        self.context &= 0x00FF_FFFF_FFFF_FFFF;
1219        // Set new sensitivity
1220        self.context |= (sensitivity as u64) << 56;
1221    }
1222
1223    // ── Quin Type (bits [63:60], via the FrameLayout ABI) ────────────────────
1224    // Canonical home: `frame_layout::{quin_type, with_quin_type}`. Bits [62:61] of
1225    // this nibble double as the permissive-routing lane on routed quins (an
1226    // intentional, role-exclusive overlay documented in frame_layout). It is NOT
1227    // relocated lower — every lower slot lands inside the tensor-bake clock [32:60].
1228    #[inline(always)]
1229    /// Quin type tag.
1230    pub fn get_quin_type(&self) -> u8 {
1231        crate::frame_layout::quin_type(self.metadata)
1232    }
1233
1234    /// Write the 4-bit Quin Type nibble into bits \[63:60\], preserving all other bits.
1235    #[inline(always)]
1236    pub fn set_quin_type(&mut self, quin_type: u8) {
1237        self.metadata = crate::frame_layout::with_quin_type(self.metadata, quin_type);
1238    }
1239
1240    // ── Sensitivity tier (bits [59:56]) — ODRL layer ─────────────────────────
1241
1242    pub const SENSITIVITY_TIER_PUBLIC: u8 = 0x00;
1243    pub const SENSITIVITY_TIER_PROFESSIONAL: u8 = 0x01;
1244    pub const SENSITIVITY_TIER_LEGAL: u8 = 0x02;
1245    pub const SENSITIVITY_TIER_MEDICAL: u8 = 0x03;
1246    pub const SENSITIVITY_TIER_FIDUCIARY: u8 = 0x04;
1247
1248    /// Read the 4-bit ODRL sensitivity tier from bits \[59:56\].
1249    #[inline(always)]
1250    pub fn get_sensitivity_tier(&self) -> u8 {
1251        ((self.metadata >> 56) & 0xF) as u8
1252    }
1253
1254    /// Write the 4-bit ODRL sensitivity tier into bits \[59:56\], preserving all other bits.
1255    #[inline(always)]
1256    pub fn set_sensitivity_tier(&mut self, tier: u8) {
1257        self.metadata = (self.metadata & !(0xFu64 << 56)) | ((tier as u64 & 0xF) << 56);
1258    }
1259
1260    // ── Lamport clock (bits [31:0]) ───────────────────────────────────────────
1261
1262    /// Extracts the 32-bit Lamport logical clock from bits \[31:0\].
1263    #[inline(always)]
1264    pub fn extract_lamport_clock(&self) -> u32 {
1265        (self.metadata & 0xFFFF_FFFF) as u32
1266    }
1267
1268    /// Sets the 32-bit Lamport logical clock in bits \[31:0\], preserving all upper bits.
1269    #[inline(always)]
1270    pub fn set_lamport_clock(&mut self, clock: u32) {
1271        self.metadata = (self.metadata & !0xFFFF_FFFFu64) | (clock as u64);
1272    }
1273
1274    /// Returns bits \[31:0\] of the metadata field.
1275    /// After the v3 migration this is the Lamport clock; call `extract_lamport_clock()`
1276    /// directly for clarity in new code.
1277    #[inline(always)]
1278    pub fn extract_clean_metadata_value(&self) -> u64 {
1279        self.metadata & 0xFFFF_FFFF
1280    }
1281
1282    /// XOR parity over the five semantic fields. Store in `parity` at creation time;
1283    /// call `verify_ecc_parity()` to confirm integrity.
1284    #[inline(always)]
1285    pub fn calculate_parity(
1286        subject: u64,
1287        predicate: u64,
1288        object: u64,
1289        context: u64,
1290        metadata: u64,
1291    ) -> u64 {
1292        subject ^ predicate ^ object ^ context ^ metadata
1293    }
1294
1295    #[inline(always)]
1296    /// `true` when the ECC parity holds.
1297    pub fn verify_ecc_parity(&self) -> bool {
1298        self.parity
1299            == Self::calculate_parity(
1300                self.subject,
1301                self.predicate,
1302                self.object,
1303                self.context,
1304                self.metadata,
1305            )
1306    }
1307
1308    /// Recalculate and store ECC parity after mutating any field.
1309    #[inline(always)]
1310    pub fn recalculate_parity(&mut self) {
1311        self.parity = Self::calculate_parity(
1312            self.subject,
1313            self.predicate,
1314            self.object,
1315            self.context,
1316            self.metadata,
1317        );
1318    }
1319
1320    #[inline(always)]
1321    /// Builds a conduct-violation quin.
1322    pub fn new_conduct_violation(reason: &[u8]) -> Self {
1323        let mut quin = Self::default();
1324        quin.predicate = 0x42_0000_0000_0000; // q42:conductViolation
1325        let mut obj_bytes = [0u8; 8];
1326        let len = core::cmp::min(reason.len(), 8);
1327        obj_bytes[..len].copy_from_slice(&reason[..len]);
1328        quin.object = u64::from_le_bytes(obj_bytes);
1329        quin.parity = Self::calculate_parity(
1330            quin.subject,
1331            quin.predicate,
1332            quin.object,
1333            quin.context,
1334            quin.metadata,
1335        );
1336        quin
1337    }
1338}
1339
1340pub const MODALITY_FLAG_LLM_TENSOR: u8 = 0b1001;
1341pub const MODALITY_FLAG_DENSE_PHYSICS: u8 = 0b1000;
1342/// CLIP / mmproj vision encoder tensors in a multimodal GGUF bundle.
1343pub const MODALITY_FLAG_VISION_TENSOR: u8 = 0b1010;
1344
1345pub trait QuinPointerExt {
1346    /// Extracts the modality flag.
1347    fn extract_modality_flag(&self) -> u8;
1348    /// Extracts the byte offset.
1349    fn extract_byte_offset(&self) -> u64;
1350}
1351
1352impl QuinPointerExt for NQuin {
1353    #[inline(always)]
1354    /// Extracts the modality flag.
1355    fn extract_modality_flag(&self) -> u8 {
1356        (self.object >> 60) as u8
1357    }
1358
1359    #[inline(always)]
1360    /// Extracts the byte offset.
1361    fn extract_byte_offset(&self) -> u64 {
1362        self.object & 0x0FFF_FFFF_FFFF_FFFF
1363    }
1364}
1365
1366pub const QUINS_PER_BLOCK: usize = 850;
1367pub const BLOCK_MULTIPLIER_SIZE: usize = 40960; // Exact alignment across 10 sectors
1368
1369#[repr(C, align(4096))]
1370pub struct QualiaSuperBlock {
1371    /// Monotonically increasing sequencing page tracker index ID
1372    pub block_sequence_id: u64,
1373    /// Binary token identifying the decentralized micro-commons owner DID root node
1374    pub storage_owner_did: u64,
1375    /// Active, filled quin array items within current page focus
1376    pub active_quin_count: u64,
1377    /// Validation value checksum bit flags
1378    pub validation_checksum: u32,
1379    /// Hard-coded sector configuration properties context (and FEA bounds)
1380    pub hardware_profile_flags: u32,
1381    /// Identifier for attached 3D voxel/tetrahedra FEA structural mesh layer
1382    pub fea_mesh_index_id: u64,
1383    /// Fixed trailing block buffer space to force page-header normalization
1384    pub layout_padding: [u8; 120], // Adjusted padding to maintain exactly 160 bytes header
1385    /// Contiguous un-padded sequential database array zones
1386    pub quin_ledger: [NQuin; QUINS_PER_BLOCK],
1387}
1388
1389pub mod archive;
1390
1391/// Target lanes configuration identifiers for Qualia data pipelines
1392#[repr(u8)]
1393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1394
1395/// Standard payload mask denoting Ambient Telemetry (Passthrough routing) Path: Local sensor traces, timeline events, and internal files
1396pub enum PermissiveRoutingLane {
1397    /// Passthrough Fast Path: Local sensor traces, timeline events, and internal files
1398    PassthroughStandard = 0x00,
1399    /// Enforces Permissive Commons compensation milestone evaluation gates
1400    EnforcePermissiveCommons = 0x01,
1401    /// Enforces absolute multi-signatory safeguards for sensitive personal links
1402    EnforceBilateralMicroCommons = 0x02,
1403    /// Triggers GPU/NPU to run bounding hull math and linguistic semantic checking
1404    SpatiotemporalAmbiguous = 0x03,
1405}
1406
1407// Bitwise parameters checked for targeted DID tracks
1408pub const MASK_AUTHENTICATED_NATURAL_PERSON: u16 = 0b0000_0001;
1409pub const MASK_BILATERAL_IDENTITY_LOCKED: u16 = 0b0000_0010;
1410pub const MASK_COMMERCIAL_BILLABLE_GATE: u16 = 0b0000_0100;
1411pub const MASK_WORK_OBLIGATION_SATISFIED: u16 = 0b0000_1000;
1412
1413#[inline(always)]
1414/// Evaluates the permissive runtime gate.
1415pub fn evaluate_permissive_runtime_gate(
1416    entry_policy_mask: u16,
1417    requesting_agent_signature_flags: u16,
1418) -> bool {
1419    // Fulfilment / work-obligation recovery cannot bypass bilateral identity
1420    // lock or unauthenticated personhood (E17.6). Check this before the
1421    // zero-cost open on MASK_WORK_OBLIGATION_SATISFIED.
1422    if (entry_policy_mask & MASK_BILATERAL_IDENTITY_LOCKED) != 0
1423        && (requesting_agent_signature_flags & MASK_AUTHENTICATED_NATURAL_PERSON) == 0
1424    {
1425        return false;
1426    }
1427
1428    // If permissive commons work metrics or cost recoupments are met, data opens at zero cost
1429    if (entry_policy_mask & MASK_WORK_OBLIGATION_SATISFIED) != 0 {
1430        return true;
1431    }
1432
1433    // Halt corporate analytics data mining if programmatic micro-payment ticks fail
1434    if (requesting_agent_signature_flags & MASK_COMMERCIAL_BILLABLE_GATE) != 0
1435        && (entry_policy_mask & MASK_COMMERCIAL_BILLABLE_GATE) != 0
1436    {
1437        return false;
1438    }
1439
1440    true
1441}
1442
1443pub struct QuinIncrementalScanner<'a> {
1444    pub file_descriptor: &'a File,
1445    pub block_sector_offsets: &'a [u64],
1446    pub current_cursor: usize,
1447    pub agent_signature_attributes: u16,
1448    /// Stack pre-allocated workspace ensures the app memory footprint remains flatlined
1449    pub allocated_working_buffer: QualiaSuperBlock,
1450}
1451
1452impl<'a> Stream for QuinIncrementalScanner<'a> {
1453    type Item = Result<Vec<NQuin>, std::io::Error>;
1454
1455    fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1456        if self.current_cursor >= self.block_sector_offsets.len() {
1457            return Poll::Ready(None); // Stream scan sequence completed
1458        }
1459
1460        let file_offset = self.block_sector_offsets[self.current_cursor];
1461        if file_offset == 0 {
1462            return Poll::Ready(None);
1463        }
1464
1465        #[cfg(target_family = "unix")]
1466        {
1467            use std::os::unix::fs::FileExt;
1468
1469            // Unpack layout buffer straight into register space via raw block copy paths
1470            let destination_ptr = &mut self.allocated_working_buffer as *mut _ as *mut u8;
1471            let byte_slice =
1472                unsafe { std::slice::from_raw_parts_mut(destination_ptr, BLOCK_MULTIPLIER_SIZE) };
1473
1474            if let Err(e) = self.file_descriptor.read_exact_at(byte_slice, file_offset) {
1475                return Poll::Ready(Some(Err(e)));
1476            }
1477        }
1478
1479        #[cfg(target_family = "windows")]
1480        {
1481            use std::os::windows::fs::FileExt;
1482
1483            let destination_ptr = &mut self.allocated_working_buffer as *mut _ as *mut u8;
1484            let byte_slice =
1485                unsafe { std::slice::from_raw_parts_mut(destination_ptr, BLOCK_MULTIPLIER_SIZE) };
1486
1487            let mut bytes_read = 0;
1488            while bytes_read < BLOCK_MULTIPLIER_SIZE {
1489                match self.file_descriptor.seek_read(
1490                    &mut byte_slice[bytes_read..],
1491                    file_offset + bytes_read as u64,
1492                ) {
1493                    Ok(0) => {
1494                        return Poll::Ready(Some(Err(std::io::Error::new(
1495                            std::io::ErrorKind::UnexpectedEof,
1496                            "failed to fill whole buffer",
1497                        ))))
1498                    }
1499                    Ok(n) => bytes_read += n,
1500                    Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1501                    Err(e) => return Poll::Ready(Some(Err(e))),
1502                }
1503            }
1504        }
1505
1506        // Taking a reference to a field of a packed struct is fine if we just extract it.
1507        // Wait, we can't take a reference to a packed struct element without caution.
1508        // Using `std::ptr::addr_of!` or just making a local copy is safe.
1509        // `self.allocated_working_buffer.quin_ledger[0]` copies the 40-byte struct because it implements Copy.
1510        let sampling_quin = self.allocated_working_buffer.quin_ledger[0];
1511
1512        if !sampling_quin.verify_ecc_parity() {
1513            return Poll::Ready(Some(Err(std::io::Error::new(
1514                std::io::ErrorKind::InvalidData,
1515                "Quin failed ECC parity check - Sector corrupted",
1516            ))));
1517        }
1518
1519        match sampling_quin.identify_routing_lane() {
1520            PermissiveRoutingLane::EnforcePermissiveCommons => {
1521                let bitmask = sampling_quin.extract_clean_metadata_value() as u16;
1522                if !evaluate_permissive_runtime_gate(bitmask, self.agent_signature_attributes) {
1523                    return Poll::Ready(Some(Err(std::io::Error::new(
1524                        std::io::ErrorKind::PermissionDenied,
1525                        "Target resource permissive commons access criteria unfulfilled",
1526                    ))));
1527                }
1528            }
1529            PermissiveRoutingLane::EnforceBilateralMicroCommons => {
1530                let _relation_token = sampling_quin.extract_clean_metadata_value();
1531                // Core evaluation checks require signature presence before output emission
1532                if (self.agent_signature_attributes & MASK_AUTHENTICATED_NATURAL_PERSON) == 0 {
1533                    return Poll::Ready(Some(Err(std::io::Error::new(
1534                        std::io::ErrorKind::PermissionDenied,
1535                        "Protected Bilateral Micro-Commons authorization token missing",
1536                    ))));
1537                }
1538            }
1539            PermissiveRoutingLane::PassthroughStandard => {
1540                // Directly bypasses permission check matrices for regular local database paths
1541            }
1542            PermissiveRoutingLane::SpatiotemporalAmbiguous => {
1543                // Routed to the Geometric Pruning Pipeline and Agent Orchestrator
1544            }
1545        }
1546
1547        self.current_cursor += 1;
1548        let elements_in_frame = self.allocated_working_buffer.active_quin_count as usize;
1549
1550        // Cannot take a slice of an unaligned array. However, `NQuin` is 40 bytes, which is a multiple of 8.
1551        // But `#[repr(C, packed)]` causes the elements in `quin_ledger` to be tightly packed with 1-byte alignment.
1552        // But since it's 40 bytes (multiple of 8), they end up exactly where they would be if aligned to 8!
1553        // We can safely create a Vec by copying element by element to avoid unaligned reference warnings, or just use `to_vec()` if it compiles.
1554        // Let's use a safe iterator to copy:
1555        let mut emitted_vector_slice = Vec::with_capacity(elements_in_frame);
1556        for i in 0..elements_in_frame {
1557            emitted_vector_slice.push(self.allocated_working_buffer.quin_ledger[i]);
1558        }
1559
1560        Poll::Ready(Some(Ok(emitted_vector_slice)))
1561    }
1562}
1563
1564impl Drop for QualiaSuperBlock {
1565    fn drop(&mut self) {
1566        // Safe volatile memory scrubbing to clear tracking signatures.
1567        unsafe {
1568            std::ptr::write_volatile(self as *mut _, std::mem::zeroed());
1569        }
1570    }
1571}
1572
1573// mcp_* modules now live in mcp/ (see MODULE_REORG_PLAN.md). The `pub mod mcp;`
1574// declaration + path-preserving re-exports are below, near the old mcp_server line.
1575// (asset_bridge moved to render::assets in Phase 0.2a)
1576#[cfg(any(
1577    not(target_arch = "wasm32"),
1578    feature = "wasm-scientific",
1579    feature = "wasm-full"
1580))]
1581pub mod deontic_logic;
1582// Sensing association estimates retain their real epistemic classification in every profile.
1583pub mod epistemic;
1584pub mod storage;
1585#[cfg(not(target_arch = "wasm32"))]
1586pub mod sync;
1587pub mod wal;
1588pub mod wal_intent;
1589
1590// The model-inference runtime: reads GGUF weight files and runs the tensor program on the GPU.
1591// It is a *runtime*, not an "engine" — the mathematics it executes lives in `crate::solvers`
1592// (GEMM, activations/softmax/normalization, attention, RoPE, FFN), each proven equal to the
1593// kernels here. `inference_runtime` is the honest name; `gguf_bridge` is retained (the directory
1594// rename is deferred — it is a shared performance lane — but the honest name is available).
1595#[cfg(any(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
1596pub mod gguf_bridge;
1597#[cfg(any(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
1598pub use gguf_bridge as inference_runtime;
1599/// Phase 4: AOT GGUF → P64 LLM-weight container compiler.
1600/// Phase 6 / task #12: safetensor (+ MLX) source parsing + dtype gate for the streaming transcoder.
1601/// Task #12 / STELLAR §A: BitNet b1.58 ternary quantization codec (compression during transcode).
1602/// Task #12 / STELLAR §A: tensor-name → engine GEMM-role mapping + the ternary (FFN-only) policy.
1603/// Task #12 / STELLAR §A: native GPU dispatch of the ternary GEMM kernel + on-device parity test.
1604/// STELLAR §A A1a: GPU top-K reduction — CPU oracle + host merge + the WGSL kernel.
1605/// STELLAR §A A1a: native GPU dispatch of the top-K reduction + on-device parity test.
1606/// STELLAR §A AH-track H0: host topology + capability sensor (enumerate all adapters; discrete vs unified).
1607/// STELLAR §A AH-track H1(a): cross-circuit GEMV benchmark → measured capability matrix (CPU/iGPU/GPU).
1608/// STELLAR §A AH-track H2: residency + device-priority planner (discovery → employment plan, D31).
1609/// STELLAR §A AH-track H1(a) cache: CBOR hardware passport (cache discovery, fast-boot skip, D26).
1610/// STELLAR §A A0 (D17/D22): shared native LLM benchmark harness — the one measurement
1611/// surface for the existing F16/Q8 path and the future ternary/top-k paths.
1612/// STELLAR §A W2 (D17): per-kernel GPU timestamp profiler for the LLM forward/decode path.
1613/// STELLAR §A W3: in-project GPU↔CPU kernel-parity oracle (error metrics + synthetic quant weights).
1614/// STELLAR §A W1: in-project quality oracle (perplexity / KL / coherence + the quant quality gate).
1615/// STELLAR §A AWQ: activation-statistics capture (the AWQ forward hook) for calibrated quantization.
1616// mcp/ category (moved from crate root). Re-exports keep crate::mcp_server and
1617// crate::mcp_cooperation paths stable for qualia-cli and intra-crate callers.
1618pub mod mcp;
1619#[cfg(any(
1620    not(target_arch = "wasm32"),
1621    feature = "wasm-webcivics",
1622    feature = "wasm-logic",
1623    feature = "wasm-scientific",
1624    feature = "wasm-full"
1625))]
1626pub use mcp::mcp_cooperation;
1627#[cfg(not(target_arch = "wasm32"))]
1628pub use mcp::mcp_server;
1629pub mod ode_solver;
1630#[cfg(not(target_arch = "wasm32"))]
1631pub mod qpu_ingress;
1632pub mod quantum_dft;
1633
1634#[cfg(target_arch = "wasm32")]
1635pub mod wasm_edge;
1636
1637#[cfg(target_arch = "wasm32")]
1638pub mod wasm_storage;
1639
1640/// A zero-allocation compile-time hashing function for Q-Turtle macros.
1641/// Uses FNV-1a, then truncates to 60 bits so the result is a pure IDENTIFIER:
1642/// the top 4 bits [60..63] are reserved as the role-keyed type/modality/tag
1643/// overlay (inline datatype tags in the Object register, the deontic
1644/// DEFEATER_BIT in the Predicate, etc.). This is the ONE canonical term-identity
1645/// hash — it MUST stay bit-for-bit identical to `lexicon::generate_60bit_token`
1646/// (same FNV constants + the same 0x0FFF_FFFF_FFFF_FFFF mask) so compile-time-baked
1647/// URIs and runtime-parsed/ingested URIs share a single hash space and JOIN.
1648pub const fn q_hash(s: &str) -> u64 {
1649    let mut hash: u64 = 0xcbf29ce484222325;
1650    let bytes = s.as_bytes();
1651    let mut i = 0;
1652    while i < bytes.len() {
1653        hash = hash ^ (bytes[i] as u64);
1654        hash = hash.wrapping_mul(0x100000001b3);
1655        i += 1;
1656    }
1657    // Truncate to 60 bits (top 4 reserved for the type/modality/tag overlay).
1658    hash & 0x0FFF_FFFF_FFFF_FFFF
1659}
1660
1661/// Advanced 2026 Q-Turtle Macro
1662/// Translates terse semantic triples into physical 48-byte hardware Quins
1663/// strictly at compile time. Eliminates runtime string allocations entirely.
1664#[macro_export]
1665macro_rules! q_turtle {
1666    ($s:expr, $p:expr, $o:expr) => {
1667        $crate::NQuin {
1668            subject: $crate::q_hash($s),
1669            predicate: $crate::q_hash($p),
1670            object: $crate::q_hash($o),
1671            context: 0,
1672            metadata: 0b01 << 61, // Default to Permissive Commons routing
1673            parity: 0,
1674        }
1675    };
1676}
1677
1678// Tests for Antigravity Validation Pipeline
1679#[cfg(test)]
1680mod tests {
1681    use super::*;
1682
1683    #[test]
1684    fn qualia_spatial_val() {
1685        use crate::domains::geospatial::spatial::{embed_h3_context, SpatiotemporalQuadTree};
1686
1687        let h3_index = 0x000a1072b59ffff; // Mock H3 cell index payload
1688        let context_val = embed_h3_context(h3_index, 10, 42);
1689        let expected_context =
1690            ((10u64 & 0x0F) << 59) | ((42u64 & 0x7F) << 52) | (h3_index & 0x000F_FFFF_FFFF_FFFF);
1691        assert_eq!(
1692            context_val, expected_context,
1693            "Failed to embed H3 index into context"
1694        );
1695
1696        let quad_tree = SpatiotemporalQuadTree::new((0.0, 0.0, 100.0, 100.0));
1697
1698        let results = quad_tree.query_region(10.0, 10.0, 20.0, 20.0, 0, 0);
1699        // We expect it to be empty since it's a structural mock
1700        assert_eq!(
1701            results.len(),
1702            0,
1703            "SpatiotemporalQuadTree placeholder query failed"
1704        );
1705    }
1706
1707    #[test]
1708    fn qualia_logic_val() {
1709        use crate::modalities::logic::core::{WebizenCompiler, WebizenVM};
1710        let q = NQuin {
1711            subject: 0,
1712            predicate: 100,
1713            object: 18,
1714            context: 0,
1715            metadata: 0,
1716            parity: 0,
1717        };
1718
1719        let mut vm = WebizenVM::new();
1720        // Use the Compiler mock to generate bytecode for the constraint:
1721        // Must have predicate 100 and object 18.
1722        let bytecode = WebizenCompiler::compile_mock_constraint();
1723        vm.load_bytecode(&bytecode);
1724
1725        let result = vm.execute_constraint(&q);
1726        assert_eq!(
1727            result, true,
1728            "Webizen VM failed to validate constraint byte-code"
1729        );
1730    }
1731
1732    #[test]
1733    fn qualia_webizen_guardianship() {
1734        use crate::modalities::logic::core::{WebizenOpcode, WebizenVM};
1735
1736        // 0b11 << 61 signals SpatiotemporalAmbiguous for bounding logic
1737        let q = NQuin {
1738            subject: 0,
1739            predicate: 0,
1740            object: 0,
1741            context: 0,
1742            metadata: 0b11 << 61 | 500,
1743            parity: 0,
1744        };
1745
1746        let mut vm = WebizenVM::new();
1747        let bytecode = vec![
1748            WebizenOpcode::EvalMetadataMask(499), // Try to match exactly 499 on the lower 16 bits
1749            WebizenOpcode::HaltIfFalse,
1750        ];
1751        vm.load_bytecode(&bytecode);
1752
1753        let result = vm.execute_constraint(&q);
1754        assert_eq!(
1755            result, false,
1756            "Webizen VM failed to deny mismatched EvalMetadataMask"
1757        );
1758    }
1759
1760    #[test]
1761    fn qualia_ldp_rdf_star_mapping() {
1762        use crate::solid_ldp::SolidLdpFacade;
1763        let q = NQuin {
1764            subject: 1,
1765            predicate: 2,
1766            object: 3,
1767            context: 4,
1768            metadata: 0b11 << 61 | 555,
1769            parity: 0,
1770        };
1771
1772        let rdf_output = SolidLdpFacade::serialize_to_rdf_star(&q);
1773
1774        // Ensure it mapped to RDF quads with context
1775        assert!(rdf_output.contains("GRAPH <urn:qualia:context:4>"));
1776        // Ensure RDF-star reification with GeoSPARQL WKT is present because it's SpatiotemporalAmbiguous
1777        assert!(rdf_output.contains("geo:asWKT"));
1778        assert!(rdf_output.contains("qualia:hardwareIntegrity \"VERIFIED_ECC_PASS\""));
1779    }
1780
1781    #[test]
1782    fn qualia_vector_density() {
1783        use crate::domains::mathematical::geometric::{
1784            extract_spatial_projection, VectorSectorMap,
1785        };
1786        let q = NQuin {
1787            subject: 0,
1788            predicate: 0,
1789            object: 0,
1790            context: 0,
1791            metadata: 42,
1792            parity: 0,
1793        };
1794        let projection = extract_spatial_projection(&q);
1795
1796        let sector_map = VectorSectorMap {
1797            sector_id: 2,
1798            active: true,
1799        }; // 42 % 10 = 2
1800        assert_eq!(
1801            sector_map.contains(projection),
1802            true,
1803            "VectorSectorMap failed to include point within bounding hull"
1804        );
1805
1806        let out_of_bounds_map = VectorSectorMap {
1807            sector_id: 3,
1808            active: true,
1809        };
1810        assert_eq!(
1811            out_of_bounds_map.contains(projection),
1812            false,
1813            "VectorSectorMap failed to prune out-of-bounds point"
1814        );
1815    }
1816
1817    #[test]
1818    fn qualia_validate_volatile_drop() {
1819        let mut block = Box::new(unsafe { std::mem::zeroed::<QualiaSuperBlock>() });
1820        block.block_sequence_id = 12345;
1821        assert_eq!(block.block_sequence_id, 12345);
1822        drop(block);
1823    }
1824
1825    #[test]
1826    fn qualia_validate_quin() {
1827        assert_eq!(
1828            std::mem::size_of::<NQuin>(),
1829            48,
1830            "NQuin must be exactly 48 bytes"
1831        );
1832    }
1833
1834    #[test]
1835    fn qualia_validate_ecc() {
1836        let mut q = NQuin {
1837            subject: 0,
1838            predicate: 0,
1839            object: 0,
1840            context: 0,
1841            metadata: 0,
1842            parity: 0,
1843        };
1844        assert_eq!(q.verify_ecc_parity(), true, "Valid ECC parity should pass");
1845
1846        q.parity = u64::MAX;
1847        assert_eq!(
1848            q.verify_ecc_parity(),
1849            false,
1850            "Corrupted ECC parity should fail"
1851        );
1852    }
1853
1854    #[test]
1855    fn qualia_validate_alignment() {
1856        assert_eq!(
1857            std::mem::size_of::<QualiaSuperBlock>(),
1858            40960,
1859            "QualiaSuperBlock must be exactly 40960 bytes (10 sectors)"
1860        );
1861        assert_eq!(
1862            std::mem::align_of::<QualiaSuperBlock>(),
1863            4096,
1864            "QualiaSuperBlock must be page aligned (4096 bytes)"
1865        );
1866    }
1867
1868    #[test]
1869    fn qualia_validate_routing() {
1870        // Routing lane = bits[62:61]; Lamport clock = bits[31:0] (v3 layout).
1871        // Values set in bits[31:0] are the Lamport clock; routing lane bits stay in [62:61].
1872
1873        let q1 = NQuin {
1874            subject: 0,
1875            predicate: 0,
1876            object: 0,
1877            context: 0,
1878            metadata: 0b00u64 << 61 | 12345,
1879            parity: 0,
1880        };
1881        assert_eq!(
1882            q1.identify_routing_lane(),
1883            PermissiveRoutingLane::PassthroughStandard
1884        );
1885        assert_eq!(q1.extract_lamport_clock(), 12345);
1886
1887        let q2 = NQuin {
1888            subject: 0,
1889            predicate: 0,
1890            object: 0,
1891            context: 0,
1892            metadata: 0b01u64 << 61 | 67890,
1893            parity: 0,
1894        };
1895        assert_eq!(
1896            q2.identify_routing_lane(),
1897            PermissiveRoutingLane::EnforcePermissiveCommons
1898        );
1899        assert_eq!(q2.extract_lamport_clock(), 67890);
1900
1901        let q3 = NQuin {
1902            subject: 0,
1903            predicate: 0,
1904            object: 0,
1905            context: 0,
1906            metadata: 0b10u64 << 61 | 42,
1907            parity: 0,
1908        };
1909        assert_eq!(
1910            q3.identify_routing_lane(),
1911            PermissiveRoutingLane::EnforceBilateralMicroCommons
1912        );
1913        assert_eq!(q3.extract_lamport_clock(), 42);
1914
1915        let q4 = NQuin {
1916            subject: 0,
1917            predicate: 0,
1918            object: 0,
1919            context: 0,
1920            metadata: 0b11u64 << 61 | 999,
1921            parity: 0,
1922        };
1923        assert_eq!(
1924            q4.identify_routing_lane(),
1925            PermissiveRoutingLane::SpatiotemporalAmbiguous
1926        );
1927        assert_eq!(q4.extract_lamport_clock(), 999);
1928    }
1929
1930    #[test]
1931    fn nquin_metadata_v3_layout() {
1932        let mut q = NQuin::default();
1933
1934        // Quin type nibble
1935        q.set_quin_type(0b1001);
1936        assert_eq!(q.get_quin_type(), 0b1001);
1937        // Routing lane reads bits[62:61] = bits 2:1 of the nibble = 0b00 (from 0b1001)
1938        assert_eq!(
1939            q.identify_routing_lane(),
1940            PermissiveRoutingLane::PassthroughStandard
1941        );
1942
1943        // Sensitivity tier
1944        q.set_sensitivity_tier(NQuin::SENSITIVITY_TIER_MEDICAL);
1945        assert_eq!(q.get_sensitivity_tier(), NQuin::SENSITIVITY_TIER_MEDICAL);
1946
1947        // Lamport clock
1948        q.set_lamport_clock(0xDEAD_BEEF);
1949        assert_eq!(q.extract_lamport_clock(), 0xDEAD_BEEF);
1950
1951        // Ensure fields don't bleed into each other
1952        assert_eq!(q.get_quin_type(), 0b1001);
1953        assert_eq!(q.get_sensitivity_tier(), NQuin::SENSITIVITY_TIER_MEDICAL);
1954        assert_eq!(q.extract_lamport_clock(), 0xDEAD_BEEF);
1955
1956        // Parity still works after mutations
1957        q.recalculate_parity();
1958        assert!(q.verify_ecc_parity());
1959    }
1960
1961    #[test]
1962    fn engine_version_matches_cargo_pkg_version() {
1963        assert_eq!(ENGINE_VERSION, env!("CARGO_PKG_VERSION"));
1964        assert!(!ENGINE_VERSION.is_empty());
1965    }
1966}
1967
1968#[cfg(not(target_arch = "wasm32"))]
1969pub mod p2p;
1970
1971pub mod domain_licence;
1972pub mod domains;
1973pub mod solvers;
1974
1975#[cfg(target_os = "linux")]
1976extern crate io_uring;