open-standards/wai/wai-web/src/feed.rs
Transaction Science df20c392d8 wai: interactive + temporal cargo classes, provenance, telepresence
Adds the "carries whatever it can reconstruct, verifies whatever it
carries" surface on top of the existing neural/codec WAI. All builds
green against this base (wai-rs all-features tests + clippy, wai-web
wasm, wai-spz-gen, wai-relay).

Reconstruct half — each a spec + conformance corpus + in-tab browser
sink that re-derives the corpus hash, over one wai.det.fixed64 floor:
  - interactive worlds      replay-equivalence   (3 sim registrants,
    relay multiplayer, session receipts, glTF + real-SPZ assets)
  - spatial audio           mixdown-equivalence
  - haptics                 sample-equivalence
  - state-feeds             replay-equivalence  (non-physics sim)
  - avatars / digital humans  pose-equivalence  (+ telepresence)
  - volumetric / 4D splats  frame-state-equivalence (WebGPU EWA render)

Verify half (lever 4):
  - asset provenance — signed, energy-accounted lineage for opaque
    captured content WAI does not reconstruct; tamper-evident in-tab.

Cross-cutting: per-class JWP receipt profiles; a native energy meter
(IOReport via macmon, no sudo) emitting receipts with real measured
joules. Codecs gated behind a `codecs` feature (default on) so the
world/wasm sinks build without the C codec chain.

Excludes the separately-evolving neural subsystem (semantic path, GLC
rANS, ONNX tooling) to avoid reverting newer origin work.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-13 23:16:42 -04:00

121 lines
4.3 KiB
Rust

//! Browser sink for `wai.feed.state` — the state-feeds extension.
//!
//! Not a port: it binds the same `wai` engine native sinks run. A feed
//! is a non-physics world (`wai.world.sim.feed0`, the identity step), so
//! this is the [`crate::world::WorldSink`] story specialized to records:
//! `verify_seal` replays a sealed feed and compares the state hash
//! (replay-equivalence, in a tab), and `records_json` exposes the live
//! typed-cell state for a scoreboard / telemetry / ticker view.
use wasm_bindgen::prelude::*;
use wai::world::feed::Cell;
use wai::world::{CausalOp, FeedRecord, FeedState, LiveWorld, WorldContainer};
#[wasm_bindgen]
pub struct FeedSink {
engine: LiveWorld<FeedState>,
sim: String,
seal: Option<(u64, [u8; 32])>,
}
fn js_err(e: impl std::fmt::Display) -> JsError {
JsError::new(&e.to_string())
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
#[wasm_bindgen]
impl FeedSink {
/// Open WWLD feed bytes. A seal, if present, is lifted out for
/// `verify_seal`; playback runs the live engine.
#[wasm_bindgen(constructor)]
pub fn new(bytes: &[u8]) -> Result<FeedSink, JsError> {
let mut c = WorldContainer::from_bytes(bytes).map_err(js_err)?;
let seal = c.seal.take().map(|s| (s.final_tick, s.final_hash));
let sim = c.contract.sim.clone();
if sim != wai::world::CAP_SIM_FEED0 {
return Err(JsError::new(&format!(
"not a state-feed: contract sim is `{sim}`, expected wai.world.sim.feed0"
)));
}
let engine = LiveWorld::open(FeedState, c).map_err(js_err)?;
Ok(FeedSink { engine, sim, seal })
}
pub fn sim(&self) -> String {
self.sim.clone()
}
pub fn current_tick(&self) -> u64 {
self.engine.current_tick()
}
pub fn final_tick(&self) -> u64 {
self.seal.map(|(t, _)| t).unwrap_or(0)
}
pub fn seal_hash_hex(&self) -> Option<String> {
self.seal.map(|(_, h)| hex(&h))
}
/// Step (or re-derive) the engine to `tick`.
pub fn advance_to(&mut self, tick: u64) -> Result<(), JsError> {
self.engine.advance_to(tick).map(|_| ()).map_err(js_err)
}
/// BLAKE3 state hash at the current tick — what replay-equivalence
/// is defined over, computed by the corpus-generating code.
pub fn state_hash_hex(&self) -> String {
hex(&self.engine.state().state_hash(&FeedState))
}
/// Replay to the sealed final tick and compare hashes. `true` = this
/// browser re-derived the publisher's exact feed state.
pub fn verify_seal(&mut self) -> Result<bool, JsError> {
let (final_tick, final_hash) = self
.seal
.ok_or_else(|| JsError::new("no seal: live feeds have nothing to verify"))?;
self.advance_to(final_tick)?;
Ok(self.state_hash_hex() == hex(&final_hash))
}
/// Ingest one signed CausalOp (a live feed publisher's update).
pub fn ingest_op(&mut self, bytes: &[u8]) -> Result<(), JsError> {
let (op, _) = CausalOp::from_bytes(bytes).map_err(js_err)?;
self.engine.ingest(op).map(|_| ()).map_err(js_err)
}
pub fn record_count(&self) -> u32 {
self.engine.state().nodes.len() as u32
}
/// The live state as JSON: `[{ "id": "<hex16>", "cells": [ {t,v}… ] }]`,
/// records in canonical node-id order. Cell `t` ∈ {"int","fixed",
/// "text"}; `fixed` carries both exact `bits` and a display `v`.
pub fn records_json(&self) -> String {
let recs: Vec<serde_json::Value> = self
.engine
.state()
.nodes
.iter()
.map(|(id, rec)| {
serde_json::json!({ "id": hex(id), "cells": cells_json(rec) })
})
.collect();
serde_json::Value::Array(recs).to_string()
}
}
fn cells_json(rec: &FeedRecord) -> Vec<serde_json::Value> {
rec.cells
.iter()
.map(|c| match c {
Cell::Int(v) => serde_json::json!({ "t": "int", "v": v }),
Cell::Fixed(v) => {
serde_json::json!({ "t": "fixed", "bits": v.to_bits(), "v": v.approx_f64() })
}
Cell::Text(s) => {
serde_json::json!({ "t": "text", "v": String::from_utf8_lossy(s) })
}
})
.collect()
}