vibe/bind/host.rs
1//! Host trait — Poet and other environments implement this.
2
3use crate::error::{DiagCode, Diagnostic};
4use crate::span::Span;
5use crate::value::{QuinRef, Value};
6
7/// Where the host is running (P16.1).
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum HostEnvironment {
10 NativeDesktop,
11 WasmSandbox,
12}
13
14/// Acceleration the host will actually use this pass (P16.1).
15/// Default is scalar. SIMD/GPU must be measured, not advertised.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum AccelerationTier {
18 ScalarCpu,
19 VectorSimd512,
20 GpuCompute512,
21}
22
23/// Host supplied by Qualia / tests.
24pub trait Host {
25 fn graph_query(&mut self, args: &[Value], take: u64, span: Span) -> Result<Value, Diagnostic>;
26
27 fn graph_stage(&mut self, term: &Value, span: Span) -> Result<Value, Diagnostic>;
28
29 fn graph_commit(&mut self, span: Span) -> Result<Value, Diagnostic>;
30
31 /// Open a transaction. Default is a no-op.
32 fn graph_begin(&mut self, _span: Span) -> Result<(), Diagnostic> {
33 Ok(())
34 }
35
36 /// Drop uncommitted staged work. Default is a no-op.
37 fn graph_abort(&mut self, _span: Span) -> Result<(), Diagnostic> {
38 Ok(())
39 }
40
41 /// Complete a `transaction { ... }` block on normal exit.
42 ///
43 /// Hosts that stage writes inside a transaction override this to commit
44 /// uncommitted work; the default delegates to `graph_abort` for backwards
45 /// compatibility with external mock hosts.
46 fn graph_end(&mut self, span: Span) -> Result<(), Diagnostic> {
47 self.graph_abort(span)
48 }
49
50 fn aura_validate(
51 &mut self,
52 node: &Value,
53 shape: &Value,
54 span: Span,
55 ) -> Result<Value, Diagnostic>;
56
57 fn pulse_publish(
58 &mut self,
59 topic: &str,
60 payload: &Value,
61 span: Span,
62 ) -> Result<Value, Diagnostic>;
63
64 /// Wall clock as seconds since Unix epoch. External (core §11): forbidden
65 /// in Pure cells. Default fails closed with E702 (WASM / hosts without a clock);
66 /// native hosts override with `SystemTime::now`. Replay uses the receipt clock,
67 /// not this binding.
68 ///
69 /// **DEPRECATED (X6, 2026-08-20):** Use `time_now` instead. Integer seconds
70 /// cannot support sub-frame animation, physics dt, or deterministic WASM
71 /// replay. Kept as a projection helper for display/logging only.
72 fn time_unix(&mut self, span: Span) -> Result<Value, Diagnostic> {
73 Err(Diagnostic::new(
74 DiagCode::E702,
75 span,
76 "no clock available on this host",
77 ))
78 }
79
80 /// The primary time primitive (X6): returns `Value::Instant` with
81 /// nanosecond resolution, explicit `TimeScale`, and optional seal.
82 /// Default fails closed with E702. Native hosts override with
83 /// `SystemTime::now` → `Instant::unix(secs, nanos)`.
84 fn time_now(&mut self, span: Span) -> Result<Value, Diagnostic> {
85 Err(Diagnostic::new(
86 DiagCode::E702,
87 span,
88 "no clock available on this host",
89 ))
90 }
91
92 /// Structured Unix time: `{ secs: I64, nanos: U64 }` (T19).
93 /// Default calls `time_unix` and wraps it into a Record.
94 fn time_unix_nanos(&mut self, span: Span) -> Result<Value, Diagnostic> {
95 let secs_val = self.time_unix(span)?;
96 let secs = secs_val.as_i64().unwrap_or(0);
97 let mut rec = std::collections::BTreeMap::new();
98 rec.insert("secs".into(), Value::I64(secs));
99 rec.insert("nanos".into(), Value::U64(0));
100 Ok(Value::Record(rec))
101 }
102
103 /// Monotonic nanos for frame timing and physics dt (T20).
104 /// Default returns 0 (WASM has no monotonic clock until W12 replay Instant).
105 fn time_monotonic_nanos(&mut self, _span: Span) -> Result<Value, Diagnostic> {
106 Ok(Value::U64(0))
107 }
108
109 fn quin_seal(
110 &mut self,
111 subject: u64,
112 predicate: u64,
113 object: u64,
114 context: u64,
115 span: Span,
116 ) -> Result<Value, Diagnostic> {
117 let _ = span;
118 Ok(Value::QuinRef(QuinRef::from_quin(
119 subject, predicate, object, context,
120 )))
121 }
122
123 fn hash_iri(&self, iri: &str) -> u64 {
124 let mut h = 0xcbf29ce484222325u64;
125 for b in iri.as_bytes() {
126 h ^= *b as u64;
127 h = h.wrapping_mul(0x100000001b3);
128 }
129 h
130 }
131
132 fn graph_snapshot(&mut self, _span: Span) -> Result<Value, Diagnostic> {
133 Ok(Value::U64(0))
134 }
135
136 fn capability_resolve(&mut self, id: &str, _span: Span) -> Result<Value, Diagnostic> {
137 let mut rec = std::collections::BTreeMap::new();
138 rec.insert("id".into(), Value::String(id.into()));
139 rec.insert("vibe_bound".into(), Value::Bool(true));
140 rec.insert("honesty".into(), Value::String("local".into()));
141 Ok(Value::Record(rec))
142 }
143
144 /// Reach an engine capability by id. Default fails closed.
145 ///
146 /// `LocalHost()` answers from in-process catalog kernels (animation, HID).
147 /// Poet and other hosts override this to reach the engine.
148 fn capability_invoke(
149 &mut self,
150 id: &str,
151 _args: &Value,
152 span: Span,
153 ) -> Result<Value, Diagnostic> {
154 Err(Diagnostic::new(
155 DiagCode::E300,
156 span,
157 format!("capability.invoke not bound on this host: {id}"),
158 ))
159 }
160
161 /// Host ABI version. Returns "vibe-host-0.1" for the current
162 /// trait surface. Hosts that add methods beyond 0.1 should
163 /// return "vibe-host-0.2" or higher.
164 fn host_version(&self) -> &str {
165 crate::HOST_VERSION
166 }
167
168 fn environment(&self) -> HostEnvironment {
169 #[cfg(target_arch = "wasm32")]
170 {
171 HostEnvironment::WasmSandbox
172 }
173 #[cfg(not(target_arch = "wasm32"))]
174 {
175 HostEnvironment::NativeDesktop
176 }
177 }
178
179 fn acceleration_tier(&self) -> AccelerationTier {
180 AccelerationTier::ScalarCpu
181 }
182
183 /// What the machine could run. Default equals this pass (`acceleration_tier`).
184 fn available_acceleration(&self) -> AccelerationTier {
185 self.acceleration_tier()
186 }
187
188 /// Proper time along a worldline, in seconds. Default: not available
189 /// (E702). Hosts with a manifold metric implementation override this.
190 fn time_proper_time(&mut self, _worldline_id: u64, span: Span) -> Result<Value, Diagnostic> {
191 Err(Diagnostic::new(
192 DiagCode::E702,
193 span,
194 "proper_time not available on this host",
195 ))
196 }
197
198 /// Deterministic replay clock for WASM. Returns None when no
199 /// replay clock is configured. When Some, the returned
200 /// { secs, nanos } is used instead of wall-clock time.
201 fn receipt_clock(&mut self, span: Span) -> Result<Value, Diagnostic> {
202 Err(Diagnostic::new(
203 DiagCode::E702,
204 span,
205 "no receipt clock configured on this host",
206 ))
207 }
208
209 /// Sample a field at a pose. Returns a Quantity. Default: E702.
210 fn field_sample(
211 &mut self,
212 _field_ref: u64,
213 _pose: &Value,
214 span: Span,
215 ) -> Result<Value, Diagnostic> {
216 Err(Diagnostic::new(
217 DiagCode::E702,
218 span,
219 "field_sample not available on this host",
220 ))
221 }
222
223 /// Apply a law to arguments. Returns a Receipt. Default: E702.
224 fn law_apply(
225 &mut self,
226 _law_ref: u64,
227 _args: &[Value],
228 span: Span,
229 ) -> Result<Value, Diagnostic> {
230 Err(Diagnostic::new(
231 DiagCode::E702,
232 span,
233 "law_apply not available on this host",
234 ))
235 }
236
237 /// Whether this host supports isolation snapshots for dry-run
238 /// evaluation. Default: false. Hosts that can create an isolated
239 /// snapshot (e.g. PoetSnapshot::fork) override this to return true.
240 fn supports_isolation(&self) -> bool {
241 false
242 }
243
244 /// Check whether a transformation preserves a conserved quantity (T34).
245 ///
246 /// Given the before and after states (as Mixtures or Records with
247 /// mass/energy/charge fields), verify that the specified conserved
248 /// quantity is preserved within tolerance. Default: E702 (no
249 /// conservation checker available).
250 fn conservation_check(
251 &mut self,
252 _quantity: &crate::value::ConservationQuantity,
253 _before: &Value,
254 _after: &Value,
255 _tolerance: f64,
256 span: Span,
257 ) -> Result<Value, Diagnostic> {
258 Err(Diagnostic::new(
259 DiagCode::E702,
260 span,
261 "conservation_check not available on this host",
262 ))
263 }
264
265 /// Determine the causal relation between two events (T35).
266 ///
267 /// Given two events (each an Instant + Pose, or a Record with `time`
268 /// and `position` fields), determine whether they are timelike,
269 /// lightlike, or spacelike separated. Default: E702 (no spacetime
270 /// metric available).
271 fn causal_relation(
272 &mut self,
273 _event_a: &Value,
274 _event_b: &Value,
275 span: Span,
276 ) -> Result<Value, Diagnostic> {
277 Err(Diagnostic::new(
278 DiagCode::E702,
279 span,
280 "causal_relation not available on this host",
281 ))
282 }
283
284 /// Execute a DAG pipeline (T24). The pipeline definition is passed
285 /// as a Record value (from JSON or VibeScript construction). The
286 /// host executes the DAG nodes in topological order, invoking
287 /// capabilities for each node. Default: E702 (no DAG executor
288 /// available on this host).
289 fn dag_execute(
290 &mut self,
291 _pipeline: &Value,
292 _blackboard: &Value,
293 span: Span,
294 ) -> Result<Value, Diagnostic> {
295 Err(Diagnostic::new(
296 DiagCode::E702,
297 span,
298 "dag.execute not available on this host",
299 ))
300 }
301
302 /// Validate a DAG pipeline definition (T24). Returns Ok(Null) if
303 /// valid, Err with diagnostic if invalid (cycle, missing budget,
304 /// missing capability). Default: E702.
305 fn dag_validate(&mut self, _pipeline: &Value, span: Span) -> Result<Value, Diagnostic> {
306 Err(Diagnostic::new(
307 DiagCode::E702,
308 span,
309 "dag.validate not available on this host",
310 ))
311 }
312
313 /// Check a deontic prohibition (T25). Given a capability ID and
314 /// the current phase, verify that the capability is allowed. If
315 /// forbidden, returns a sealed DeonticInterrupt receipt. Default:
316 /// E702 (no deontic checker available).
317 fn deontic_check(
318 &mut self,
319 _capability: &str,
320 _phase: &str,
321 span: Span,
322 ) -> Result<Value, Diagnostic> {
323 Err(Diagnostic::new(
324 DiagCode::E702,
325 span,
326 "deontic.check not available on this host",
327 ))
328 }
329
330 /// Poll for the next inbound HID event (T42). Returns the next
331 /// event from the host's HID loop, or Null if no event is
332 /// available (non-blocking). Default: E702 (no HID loop on this
333 /// host).
334 fn hid_poll(&mut self, span: Span) -> Result<Value, Diagnostic> {
335 Err(Diagnostic::new(
336 DiagCode::E702,
337 span,
338 "hid.poll not available on this host",
339 ))
340 }
341
342 /// Wait for the next inbound HID event with a timeout (T42).
343 /// Returns the next event, or Null if the timeout expired.
344 /// Default: E702.
345 fn hid_wait(&mut self, _timeout_ns: u64, span: Span) -> Result<Value, Diagnostic> {
346 Err(Diagnostic::new(
347 DiagCode::E702,
348 span,
349 "hid.wait not available on this host",
350 ))
351 }
352
353 /// Post an outbound cue (T45) — haptic, audio, visual, or
354 /// accessibility. The cue ID identifies the output channel and
355 /// the payload carries the cue data. Default: E702.
356 fn cue_post(
357 &mut self,
358 _cue_id: &str,
359 _payload: &Value,
360 span: Span,
361 ) -> Result<Value, Diagnostic> {
362 Err(Diagnostic::new(
363 DiagCode::E702,
364 span,
365 "cue.post not available on this host",
366 ))
367 }
368
369 // ── Crypto operations (T-crypto) ────────────────────────────────
370
371 /// Compute a cryptographic hash (T-crypto). The algorithm is one of
372 /// "SHA-256", "SHA-512", "BLAKE3". The data is a String (UTF-8) or
373 /// hex-encoded String. Returns a Record `{ algorithm, hex, bytes }`.
374 /// Default: E702 (no crypto provider on this host).
375 fn crypto_hash(
376 &mut self,
377 _algorithm: &str,
378 _data: &str,
379 span: Span,
380 ) -> Result<Value, Diagnostic> {
381 Err(Diagnostic::new(
382 DiagCode::E702,
383 span,
384 "crypto.hash not available on this host",
385 ))
386 }
387
388 /// Derive a key using HKDF-SHA256 (T-crypto). Returns the derived
389 /// key as a hex-encoded String. Default: E702.
390 fn crypto_hkdf(
391 &mut self,
392 _ikm: &str,
393 _info: &str,
394 _length: u64,
395 span: Span,
396 ) -> Result<Value, Diagnostic> {
397 Err(Diagnostic::new(
398 DiagCode::E702,
399 span,
400 "crypto.hkdf not available on this host",
401 ))
402 }
403
404 /// AEAD encrypt (T-crypto). Returns a Record
405 /// `{ algorithm, ciphertext_hex, tag_hex, nonce_hex }`.
406 /// Default: E702.
407 fn crypto_aead_encrypt(
408 &mut self,
409 _algorithm: &str,
410 _key_hex: &str,
411 _nonce_hex: &str,
412 _plaintext: &str,
413 _aad: &str,
414 span: Span,
415 ) -> Result<Value, Diagnostic> {
416 Err(Diagnostic::new(
417 DiagCode::E702,
418 span,
419 "crypto.aead_encrypt not available on this host",
420 ))
421 }
422
423 /// AEAD decrypt (T-crypto). Returns the plaintext as a String, or
424 /// an error if decryption fails. Default: E702.
425 fn crypto_aead_decrypt(
426 &mut self,
427 _algorithm: &str,
428 _key_hex: &str,
429 _nonce_hex: &str,
430 _ciphertext_hex: &str,
431 _tag_hex: &str,
432 _aad: &str,
433 span: Span,
434 ) -> Result<Value, Diagnostic> {
435 Err(Diagnostic::new(
436 DiagCode::E702,
437 span,
438 "crypto.aead_decrypt not available on this host",
439 ))
440 }
441
442 /// Sign data with a key (T-crypto). The key_id identifies the key
443 /// in the host's key vault. Returns a Record
444 /// `{ key_id, signature_hex, algorithm }`. Default: E702.
445 fn crypto_sign(&mut self, _key_id: &str, _data: &str, span: Span) -> Result<Value, Diagnostic> {
446 Err(Diagnostic::new(
447 DiagCode::E702,
448 span,
449 "crypto.sign not available on this host",
450 ))
451 }
452
453 /// Verify a signature (T-crypto). Returns Bool. Default: E702.
454 fn crypto_verify(
455 &mut self,
456 _key_id: &str,
457 _data: &str,
458 _signature_hex: &str,
459 span: Span,
460 ) -> Result<Value, Diagnostic> {
461 Err(Diagnostic::new(
462 DiagCode::E702,
463 span,
464 "crypto.verify not available on this host",
465 ))
466 }
467
468 /// Generate a new key (T-crypto). The algorithm is one of "Ed25519",
469 /// "ML-DSA-65". Returns the key_id String. Default: E702.
470 fn crypto_generate_key(&mut self, _algorithm: &str, span: Span) -> Result<Value, Diagnostic> {
471 Err(Diagnostic::new(
472 DiagCode::E702,
473 span,
474 "crypto.generate_key not available on this host",
475 ))
476 }
477
478 // ── ZK proof operations (zk-SNARKs) ─────────────────────────────
479
480 /// Prove, in zero knowledge, that a private `value` satisfies
481 /// `value >= threshold`. Returns a Record
482 /// `{ proof_hex, vk_hex, proof_id, circuit_id }`.
483 /// Default: E702 (no ZK proof system on this host).
484 fn zk_prove_threshold(
485 &mut self,
486 _value: u64,
487 _threshold: u64,
488 span: Span,
489 ) -> Result<Value, Diagnostic> {
490 Err(Diagnostic::new(
491 DiagCode::E702,
492 span,
493 "zk.prove_threshold not available on this host",
494 ))
495 }
496
497 /// Verify a ZK threshold proof against a public `threshold`.
498 /// Returns Bool. Default: E702.
499 fn zk_verify_threshold(
500 &mut self,
501 _proof_hex: &str,
502 _vk_hex: &str,
503 _threshold: u64,
504 span: Span,
505 ) -> Result<Value, Diagnostic> {
506 Err(Diagnostic::new(
507 DiagCode::E702,
508 span,
509 "zk.verify_threshold not available on this host",
510 ))
511 }
512
513 /// Prove, in zero knowledge, that a private `value` satisfies
514 /// `lo <= value <= hi`. Returns a Record
515 /// `{ proof_hex, vk_hex, proof_id, circuit_id }`.
516 /// Default: E702.
517 fn zk_prove_range(
518 &mut self,
519 _value: u64,
520 _lo: u64,
521 _hi: u64,
522 span: Span,
523 ) -> Result<Value, Diagnostic> {
524 Err(Diagnostic::new(
525 DiagCode::E702,
526 span,
527 "zk.prove_range not available on this host",
528 ))
529 }
530
531 /// Verify a ZK range proof against public bounds `lo` and `hi`.
532 /// Returns Bool. Default: E702.
533 fn zk_verify_range(
534 &mut self,
535 _proof_hex: &str,
536 _vk_hex: &str,
537 _lo: u64,
538 _hi: u64,
539 span: Span,
540 ) -> Result<Value, Diagnostic> {
541 Err(Diagnostic::new(
542 DiagCode::E702,
543 span,
544 "zk.verify_range not available on this host",
545 ))
546 }
547
548 /// Prove a matrix multiplication: given public A, B, and claimed
549 /// C = A·B, prove the multiplication is correct without revealing
550 /// the witness. Returns a Record `{ valid, result }`.
551 /// Default: E702.
552 fn zk_prove_matmul(
553 &mut self,
554 _m: u64,
555 _k: u64,
556 _n: u64,
557 _a: &[i128],
558 _b: &[i128],
559 span: Span,
560 ) -> Result<Value, Diagnostic> {
561 Err(Diagnostic::new(
562 DiagCode::E702,
563 span,
564 "zk.prove_matmul not available on this host",
565 ))
566 }
567
568 /// List all registered ZK circuits. Returns a List of circuit IDs.
569 /// Default: E702.
570 fn zk_list_circuits(&mut self, span: Span) -> Result<Value, Diagnostic> {
571 Err(Diagnostic::new(
572 DiagCode::E702,
573 span,
574 "zk.list_circuits not available on this host",
575 ))
576 }
577}