Skip to main content

qualia_core_db/poet_host/
bridge.rs

1//! Vibe-host execution capability contract.
2//!
3//! This module describes *where* a Vibe capability runs; it does not change
4//! the language or silently substitute a different computation.  In
5//! particular, the detached WASM graph is an isolated snapshot, not a claim
6//! that a persistent native graph has been reached.
7
8/// Versioned identifier emitted by the loopback negotiation endpoint.
9pub const BRIDGE_PROTOCOL: &str = "qualia-vibe-bridge/1";
10
11/// Execution route for a host capability.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum CapabilityRoute {
14    /// Runs wholly inside the loaded WASM module.
15    StandaloneWasm,
16    /// Runs in WASM, but against an isolated, non-persistent snapshot.
17    StandaloneSnapshot,
18    /// Needs the native engine through an authenticated local adapter.
19    NativeBridge,
20    /// Uses an in-process native engine directly.
21    NativeDirect,
22}
23
24impl CapabilityRoute {
25    /// Static string.
26    pub const fn as_str(self) -> &'static str {
27        match self {
28            Self::StandaloneWasm => "standalone-wasm",
29            Self::StandaloneSnapshot => "standalone-snapshot",
30            Self::NativeBridge => "native-bridge",
31            Self::NativeDirect => "native-direct",
32        }
33    }
34}
35
36/// Meaning promised by a route. This is deliberately separate from speed or
37/// availability: an isolated graph snapshot is useful, but it is not a
38/// persistent graph transaction.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum SemanticGuarantee {
41    Exact,
42    IsolatedSnapshot,
43    Unavailable,
44}
45
46impl SemanticGuarantee {
47    /// Stable string form.
48    pub const fn as_str(self) -> &'static str {
49        match self {
50            Self::Exact => "exact",
51            Self::IsolatedSnapshot => "isolated-snapshot",
52            Self::Unavailable => "unavailable",
53        }
54    }
55}
56
57/// A static capability boundary shared by catalogue metadata, the daemon
58/// negotiation document, and tools-side diagnostics.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub struct CapabilityBoundary {
61    pub standalone_route: CapabilityRoute,
62    pub standalone_semantics: SemanticGuarantee,
63    pub native_route: CapabilityRoute,
64    pub native_semantics: SemanticGuarantee,
65}
66
67const EXACT_WASM_BINDINGS: &[&str] = &[
68    "math.abs",
69    "math.min",
70    "math.max",
71    "rdf.triple",
72    "rdf.reify",
73    "quin.statement",
74    "capability.resolve",
75];
76
77const SNAPSHOT_BINDINGS: &[&str] = &[
78    "graph.read",
79    "graph.write",
80    "aura.validate",
81    "pulse.publish",
82];
83
84const NATIVE_BRIDGE_BINDINGS: &[&str] = &[
85    "GraphDatabase.sparql",
86    "Inference.load_model",
87    "Inference.run_transformer",
88];
89
90/// Resolve a capability boundary without allocating. Unknown capabilities are
91/// intentionally unavailable until an owning host declares them.
92pub const fn boundary_for(id: &str) -> CapabilityBoundary {
93    if slice_contains(EXACT_WASM_BINDINGS, id) {
94        return CapabilityBoundary {
95            standalone_route: CapabilityRoute::StandaloneWasm,
96            standalone_semantics: SemanticGuarantee::Exact,
97            native_route: CapabilityRoute::NativeDirect,
98            native_semantics: SemanticGuarantee::Exact,
99        };
100    }
101    if slice_contains(SNAPSHOT_BINDINGS, id) {
102        return CapabilityBoundary {
103            standalone_route: CapabilityRoute::StandaloneSnapshot,
104            standalone_semantics: SemanticGuarantee::IsolatedSnapshot,
105            native_route: CapabilityRoute::NativeDirect,
106            native_semantics: SemanticGuarantee::Exact,
107        };
108    }
109    if slice_contains(NATIVE_BRIDGE_BINDINGS, id) {
110        return CapabilityBoundary {
111            standalone_route: CapabilityRoute::NativeBridge,
112            standalone_semantics: SemanticGuarantee::Unavailable,
113            native_route: CapabilityRoute::NativeDirect,
114            native_semantics: SemanticGuarantee::Exact,
115        };
116    }
117    CapabilityBoundary {
118        standalone_route: CapabilityRoute::NativeBridge,
119        standalone_semantics: SemanticGuarantee::Unavailable,
120        native_route: CapabilityRoute::NativeDirect,
121        native_semantics: SemanticGuarantee::Exact,
122    }
123}
124
125const fn slice_contains(haystack: &[&str], needle: &str) -> bool {
126    let mut index = 0;
127    while index < haystack.len() {
128        if str_eq(haystack[index], needle) {
129            return true;
130        }
131        index += 1;
132    }
133    false
134}
135
136const fn str_eq(left: &str, right: &str) -> bool {
137    let left_bytes = left.as_bytes();
138    let right_bytes = right.as_bytes();
139    if left_bytes.len() != right_bytes.len() {
140        return false;
141    }
142    let mut index = 0;
143    while index < left_bytes.len() {
144        if left_bytes[index] != right_bytes[index] {
145            return false;
146        }
147        index += 1;
148    }
149    true
150}
151
152/// The JSON-shaped, allocation-permitted cold-path view of the contract.
153pub fn negotiation_document(native_available: bool) -> serde_json::Value {
154    let capabilities: Vec<serde_json::Value> = crate::poet_host::invoke::ids::ALL_BOUND
155        .iter()
156        .map(|id| capability_json(id, native_available))
157        .collect();
158
159    serde_json::json!({
160        "protocol": BRIDGE_PROTOCOL,
161        "execution_host": "vibe-host",
162        "profile": crate::wasm_capabilities::compiled_profile(),
163        "backend": {
164            "kind": "browser-loopback-http",
165            "available": native_available,
166            "engine_version": crate::ENGINE_VERSION,
167        },
168        "capabilities": capabilities,
169        "security": {
170            "token_header": "X-Qualia-Token",
171            "origin_checked": true,
172            "private_network_access": true,
173            "user_gesture_required_by_client": true,
174        }
175    })
176}
177
178/// One capability entry for both machine and human tooling.
179pub fn capability_json(id: &str, native_available: bool) -> serde_json::Value {
180    let boundary = boundary_for(id);
181    let schema = crate::poet_host::invoke::coverage::schema_for(id);
182    let (route, semantics, available) = if native_available {
183        (boundary.native_route, boundary.native_semantics, true)
184    } else {
185        (
186            boundary.standalone_route,
187            boundary.standalone_semantics,
188            boundary.standalone_semantics != SemanticGuarantee::Unavailable,
189        )
190    };
191    serde_json::json!({
192        "id": id,
193        "mode": route.as_str(),
194        "semantics": semantics.as_str(),
195        "available": available,
196        "requires_native": boundary.standalone_semantics == SemanticGuarantee::Unavailable,
197        "transport": if route == CapabilityRoute::NativeBridge { "browser-loopback-http" } else { "none" },
198        "family": schema.map(|value| value.family).unwrap_or("unclassified"),
199        "honesty": schema.map(|value| value.honesty).unwrap_or("unclassified"),
200        "effect_class": schema.map(|value| value.effect_class).unwrap_or("unknown"),
201        "arg_schema": schema
202            .and_then(|value| serde_json::from_str::<serde_json::Value>(value.arg_shape).ok())
203            .unwrap_or(serde_json::Value::Null),
204        "return_schema": schema
205            .and_then(|value| serde_json::from_str::<serde_json::Value>(value.return_shape).ok())
206            .unwrap_or(serde_json::Value::Null),
207    })
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn graph_write_is_never_described_as_persistent_in_standalone_wasm() {
216        let graph = capability_json("graph.write", false);
217        assert_eq!(graph["mode"], "standalone-snapshot");
218        assert_eq!(graph["semantics"], "isolated-snapshot");
219    }
220
221    #[test]
222    fn native_only_capability_is_explicit_when_daemon_is_absent() {
223        let model = capability_json("Inference.load_model", false);
224        assert_eq!(model["mode"], "native-bridge");
225        assert_eq!(model["available"], false);
226        assert_eq!(model["requires_native"], true);
227    }
228
229    #[test]
230    fn negotiation_uses_versioned_protocol_and_vibe_host_name() {
231        let document = negotiation_document(true);
232        assert_eq!(document["protocol"], BRIDGE_PROTOCOL);
233        assert_eq!(document["execution_host"], "vibe-host");
234        let capabilities = document["capabilities"].as_array().unwrap();
235        assert_eq!(
236            capabilities.len(),
237            crate::poet_host::invoke::ids::ALL_BOUND.len()
238        );
239        assert!(capabilities
240            .iter()
241            .any(|entry| entry["id"] == "Audio.oscillator"));
242        assert!(capabilities
243            .iter()
244            .any(|entry| entry["id"] == "Scene.render"));
245    }
246}