From 98cd97f8212adfefa9d99548ebf0b61ab46bc456 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:06:58 -0600 Subject: [PATCH 1/4] feat(id): add native shell session state --- pkgs/id/crates/id-native-shell/src/lib.rs | 4 + pkgs/id/crates/id-native-shell/src/session.rs | 258 ++++++++++++++++++ 2 files changed, 262 insertions(+) create mode 100644 pkgs/id/crates/id-native-shell/src/session.rs diff --git a/pkgs/id/crates/id-native-shell/src/lib.rs b/pkgs/id/crates/id-native-shell/src/lib.rs index baab5f2044..4c6ce191d9 100644 --- a/pkgs/id/crates/id-native-shell/src/lib.rs +++ b/pkgs/id/crates/id-native-shell/src/lib.rs @@ -16,6 +16,10 @@ //! machine-readable contract. Step 2 adds the window/render plugins and //! the live contract-parity session harness. +mod session; + +pub use session::{ServerUpdate, SessionState, SessionView, join_frame}; + use id::world_presentation::WorldSurface; use serde_json::{Value, json}; diff --git a/pkgs/id/crates/id-native-shell/src/session.rs b/pkgs/id/crates/id-native-shell/src/session.rs new file mode 100644 index 0000000000..26cca1e50b --- /dev/null +++ b/pkgs/id/crates/id-native-shell/src/session.rs @@ -0,0 +1,258 @@ +//! Contract-frame state for one native shell session. +//! +//! This stays independent of Bevy so the network task can validate and +//! accumulate frames before handing state to the render thread. The native +//! client does not opt in to screen patches: every received view is therefore +//! a complete view, not a delta that needs a revision cache. + +use anyhow::{Context, Result, bail}; +use id::world_presentation::{WorldSurface, parse_surface}; +use serde_json::{Value, json}; + +/// Create the initial join frame. `None` requests a fresh snapshot; this +/// deliberately omits `screen_patches` until the shell tracks patch revisions. +#[must_use] +pub fn join_frame(capability: &str, after: Option) -> Value { + json!({ + "type": "join", + "capability": capability, + "after": after, + }) +} + +/// A host view in the existing F13.1 contract. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SessionView { + /// Durable world sequence the view reflects. + pub sequence: u64, + /// Safe legacy text fallback supplied by the host. + pub data: String, + /// A recognized, validated presentation surface, if supplied. + pub surface: Option, +} + +impl SessionView { + fn from_frame(frame: &Value) -> Result { + let sequence = frame["sequence"] + .as_u64() + .context("view frame has no unsigned sequence")?; + let data = frame["data"] + .as_str() + .context("view frame has no text data")? + .to_owned(); + let surface = frame + .get("surface") + .and_then(|surface| serde_json::to_string(surface).ok()) + .and_then(|surface| parse_surface(&surface).ok().flatten()); + Ok(Self { + sequence, + data, + surface, + }) + } + + /// Plain-text projection for headless output and safe renderer fallback. + #[must_use] + pub fn text_projection(&self) -> String { + self.surface + .as_ref() + .map_or_else(|| self.data.clone(), WorldSurface::text_projection) + } +} + +/// The kind of update applied from a validated host frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ServerUpdate { + /// A complete snapshot arrived, including after a server-side resync. + Snapshot, + /// A durable event arrived. + Event, + /// An ephemeral full view arrived. + View, +} + +/// Accumulated host state for a single session stream. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SessionState { + snapshot: Option, + events: Vec, + view: Option, +} + +impl SessionState { + /// Apply one host frame after checking it against the embedded F13.1 + /// contract. Unknown reply kinds are not interpreted as session state. + /// + /// # Errors + /// + /// Returns an error for malformed, out-of-contract, or non-session frames. + pub fn apply_server_frame(&mut self, frame: Value) -> Result { + let contract = id::shell_contract::ShellContract::embedded() + .map_err(anyhow::Error::msg) + .context("load shell contract")?; + let kind = contract + .check_server_frame(&frame) + .map_err(anyhow::Error::msg) + .context("validate host frame")?; + + match kind { + "snapshot" => { + self.snapshot = Some(frame["snapshot"].clone()); + self.events.clear(); + Ok(ServerUpdate::Snapshot) + } + "event" => { + self.events.push(frame["event"].clone()); + Ok(ServerUpdate::Event) + } + "view" => { + self.view = Some(SessionView::from_frame(&frame)?); + Ok(ServerUpdate::View) + } + "error" => { + bail!( + "world host refused the session: {}", + frame["message"].as_str().unwrap_or("unspecified error") + ); + } + _ => bail!("unexpected host frame `{kind}` in world session"), + } + } + + /// Most recent complete snapshot received on this stream. + #[must_use] + pub fn snapshot(&self) -> Option<&Value> { + self.snapshot.as_ref() + } + + /// Durable events received since the most recent snapshot. + #[must_use] + pub fn events(&self) -> &[Value] { + &self.events + } + + /// Most recent ephemeral view. A view is not a durable event and is not + /// assumed to follow every event. + #[must_use] + pub fn view(&self) -> Option<&SessionView> { + self.view.as_ref() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn join_starts_from_a_fresh_snapshot_without_requesting_patches() { + assert_eq!( + join_frame("capability", None), + json!({"type":"join", "capability":"capability", "after":null}) + ); + assert_eq!( + join_frame("capability", Some(7)), + json!({"type":"join", "capability":"capability", "after":7}) + ); + } + + #[test] + fn session_tracks_snapshot_events_and_ephemeral_views_separately() { + let mut state = SessionState::default(); + assert_eq!( + state + .apply_server_frame(json!({"type":"snapshot", "snapshot":{"sequence":4}})) + .unwrap(), + ServerUpdate::Snapshot + ); + assert_eq!( + state + .apply_server_frame( + json!({"type":"event", "event":{"sequence":5,"kind":{"kind":"input"}}}) + ) + .unwrap(), + ServerUpdate::Event + ); + assert_eq!( + state + .apply_server_frame( + json!({"type":"view", "sequence":5, "data":"fallback", "view_revision":0}) + ) + .unwrap(), + ServerUpdate::View + ); + + assert_eq!(state.snapshot(), Some(&json!({"sequence":4}))); + assert_eq!( + state.events(), + &[json!({"sequence":5,"kind":{"kind":"input"}})] + ); + let view = state.view().unwrap(); + assert_eq!(view.sequence, 5); + assert_eq!(view.text_projection(), "fallback"); + } + + #[test] + fn a_new_snapshot_resets_events_but_keeps_the_latest_view_until_replaced() { + let mut state = SessionState::default(); + state + .apply_server_frame(json!({"type":"snapshot", "snapshot":{"sequence":1}})) + .unwrap(); + state + .apply_server_frame(json!({"type":"event", "event":{"sequence":2}})) + .unwrap(); + state + .apply_server_frame( + json!({"type":"view", "sequence":2, "data":"old", "view_revision":0}), + ) + .unwrap(); + state + .apply_server_frame(json!({"type":"snapshot", "snapshot":{"sequence":9}})) + .unwrap(); + + assert!(state.events().is_empty()); + assert_eq!(state.view().unwrap().text_projection(), "old"); + } + + #[test] + fn only_a_validated_surface_replaces_the_legacy_data_fallback() { + let mut state = SessionState::default(); + state + .apply_server_frame(json!({ + "type":"view", "sequence":1, "data":"fallback", + "surface":{"kind":"screen","version":1,"width":2,"height":1,"rows":["hi"]}, + "view_revision":0 + })) + .unwrap(); + assert_eq!(state.view().unwrap().text_projection(), "hi"); + + state + .apply_server_frame(json!({ + "type":"view", "sequence":2, "data":"safe fallback", + "surface":{"kind":"future-kind","version":99}, + "view_revision":1 + })) + .unwrap(); + let view = state.view().unwrap(); + assert!(view.surface.is_none()); + assert_eq!(view.text_projection(), "safe fallback"); + } + + #[test] + fn malformed_and_non_session_host_frames_are_rejected() { + let mut state = SessionState::default(); + assert!( + state + .apply_server_frame( + json!({"type":"view", "data":"missing sequence", "view_revision":0}) + ) + .is_err() + ); + assert!( + state + .apply_server_frame( + json!({"type":"module_info", "world_id":"w", "current_sequence":1}) + ) + .is_err() + ); + } +} From 4b3b279fbe1ac0109bf4eb003ae493e13549c4eb Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:56:40 -0600 Subject: [PATCH 2/4] test(id-native-shell): check scripted frames against F13.1 --- .../id-native-shell/tests/transcript.rs | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/pkgs/id/crates/id-native-shell/tests/transcript.rs b/pkgs/id/crates/id-native-shell/tests/transcript.rs index 200529ee46..313db300b0 100644 --- a/pkgs/id/crates/id-native-shell/tests/transcript.rs +++ b/pkgs/id/crates/id-native-shell/tests/transcript.rs @@ -5,7 +5,11 @@ //! contract's bounds. This is the step-1 stand-in for the live //! `id world contract --check` session harness (step 2). -use serde_json::Value; +use id::shell_contract::{ShellContract, check_transcript}; +use id_native_shell::{ + SessionState, chat_frame, input_frame, join_frame, paste_frame, resize_frame, +}; +use serde_json::{Value, json}; use std::collections::BTreeSet; use std::path::PathBuf; @@ -101,3 +105,42 @@ fn transcript_records_a_view_with_data() { .contains("welcome") ); } + +#[test] +fn native_session_builders_pass_the_f13_1_contract_checker() { + let mut state = SessionState::default(); + let mut lines = Vec::new(); + let mut record = |from: &str, frame: Value| { + lines.push(json!({"from": from, "frame": frame}).to_string()); + }; + + record("client", join_frame("capability", None)); + for (frame, expected) in [ + ( + json!({"type":"snapshot", "snapshot":{"sequence":0}}), + id_native_shell::ServerUpdate::Snapshot, + ), + ( + json!({"type":"event", "event":{"sequence":1,"kind":{"kind":"input"}}}), + id_native_shell::ServerUpdate::Event, + ), + ( + json!({"type":"view", "sequence":1, "data":"welcome", "view_revision":0}), + id_native_shell::ServerUpdate::View, + ), + ] { + assert_eq!(state.apply_server_frame(frame.clone()).unwrap(), expected); + record("server", frame); + } + + record("client", input_frame(b"look\r")); + record("client", paste_frame("a pasted line").unwrap()); + record("client", resize_frame(80, 24).unwrap()); + record("client", chat_frame("hello from the native shell")); + + let transcript = lines.join("\n"); + let contract = ShellContract::embedded().expect("embedded F13.1 contract"); + let violations = check_transcript(&contract, &transcript).expect("parse transcript"); + assert!(violations.is_empty(), "{violations:#?}\n{transcript}"); + assert_eq!(state.view().unwrap().text_projection(), "welcome"); +} From 4e7fa0171e7b9ad86c26be19c025fac5d2c01298 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Thu, 12 Nov 2026 21:25:08 -0600 Subject: [PATCH 3/4] fix(id-native-shell): accept program_changed frames and decode host screen surfaces Dispositions both Codex P2 findings on PR #7197: apply_server_frame now handles the mandatory program_changed lifecycle notification (snapshot, program_changed, replacement view) as ServerUpdate::ProgramChanged and records the new module hash; SessionView now decodes the surface in the host normalized WorldSurface wire format (row-major cells for screens, re-validated via ScreenSurface::from_cells) instead of feeding the frame to the guest-document parse_surface, which silently discarded every real screen. Tests cover both paths. Found uncommitted in this worktree with the main merge cfd0965ff7; verified and landed by lane code-d (task 9341). --- pkgs/id/crates/id-native-shell/src/session.rs | 89 +++++++++++++++++-- 1 file changed, 83 insertions(+), 6 deletions(-) diff --git a/pkgs/id/crates/id-native-shell/src/session.rs b/pkgs/id/crates/id-native-shell/src/session.rs index 26cca1e50b..01a684eab7 100644 --- a/pkgs/id/crates/id-native-shell/src/session.rs +++ b/pkgs/id/crates/id-native-shell/src/session.rs @@ -6,7 +6,7 @@ //! a complete view, not a delta that needs a revision cache. use anyhow::{Context, Result, bail}; -use id::world_presentation::{WorldSurface, parse_surface}; +use id::world_presentation::{ScreenSurface, WorldSurface}; use serde_json::{Value, json}; /// Create the initial join frame. `None` requests a fresh snapshot; this @@ -40,10 +40,7 @@ impl SessionView { .as_str() .context("view frame has no text data")? .to_owned(); - let surface = frame - .get("surface") - .and_then(|surface| serde_json::to_string(surface).ok()) - .and_then(|surface| parse_surface(&surface).ok().flatten()); + let surface = frame.get("surface").and_then(decode_host_surface); Ok(Self { sequence, data, @@ -60,6 +57,33 @@ impl SessionView { } } +/// Decode a view frame's `surface` in the host's normalized wire format. +/// +/// The host sends the surface it built from the guest document, serialized +/// as a [`WorldSurface`] — for a screen that is the row-major `cells` +/// format, NOT the guest's `rows` document that +/// `id::world_presentation::parse_surface` accepts. Decoding the frame +/// value directly is the only path that sees real host screens; anything +/// unrecognized or invalid falls back to `None` (the caller then uses the +/// frame's legacy `data` text, exactly as for a surface-less view). +fn decode_host_surface(surface: &Value) -> Option { + let decoded: WorldSurface = serde_json::from_value(surface.clone()).ok()?; + match decoded { + WorldSurface::Screen(screen) => { + // Re-validate the normalized buffer (dimensions, cell count, + // glyph safety) instead of trusting the wire value as-is. + let validated = ScreenSurface::from_cells( + usize::from(screen.width), + usize::from(screen.height), + screen.cells, + ) + .ok()?; + Some(WorldSurface::Screen(validated)) + } + other => Some(other), + } +} + /// The kind of update applied from a validated host frame. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ServerUpdate { @@ -69,6 +93,9 @@ pub enum ServerUpdate { Event, /// An ephemeral full view arrived. View, + /// The host replaced the world's program mid-session (a live install + /// sends snapshot, then this notification, then a replacement view). + ProgramChanged, } /// Accumulated host state for a single session stream. @@ -77,6 +104,7 @@ pub struct SessionState { snapshot: Option, events: Vec, view: Option, + program_module_hash: Option, } impl SessionState { @@ -109,6 +137,14 @@ impl SessionState { self.view = Some(SessionView::from_frame(&frame)?); Ok(ServerUpdate::View) } + "program_changed" => { + // A live program install is a normal point in a session + // stream (snapshot, this notification, replacement view), + // not a protocol failure: record the new module and let + // the caller keep processing the stream. + self.program_module_hash = frame["module_hash"].as_str().map(str::to_owned); + Ok(ServerUpdate::ProgramChanged) + } "error" => { bail!( "world host refused the session: {}", @@ -137,6 +173,13 @@ impl SessionState { pub fn view(&self) -> Option<&SessionView> { self.view.as_ref() } + + /// Module hash named by the most recent `program_changed` notification, + /// if the host has replaced the world's program during this session. + #[must_use] + pub fn program_module_hash(&self) -> Option<&str> { + self.program_module_hash.as_deref() + } } #[cfg(test)] @@ -216,10 +259,15 @@ mod tests { #[test] fn only_a_validated_surface_replaces_the_legacy_data_fallback() { let mut state = SessionState::default(); + // The host's normalized wire format: a screen surface arrives as + // row-major `cells`, not the guest document's `rows`. state .apply_server_frame(json!({ "type":"view", "sequence":1, "data":"fallback", - "surface":{"kind":"screen","version":1,"width":2,"height":1,"rows":["hi"]}, + "surface":{"kind":"screen","version":1,"width":2,"height":1,"cells":[ + {"symbol":"h","fg":0,"bg":0,"bold":false,"columns":1}, + {"symbol":"i","fg":0,"bg":0,"bold":false,"columns":1} + ]}, "view_revision":0 })) .unwrap(); @@ -237,6 +285,35 @@ mod tests { assert_eq!(view.text_projection(), "safe fallback"); } + #[test] + fn program_changed_is_a_normal_mid_stream_notification() { + // A live program install reaches a session as snapshot, then + // program_changed, then a replacement view (the host's own + // world_session contract test streams exactly this sequence). + let mut state = SessionState::default(); + state + .apply_server_frame(json!({"type":"snapshot", "snapshot":{"sequence":4}})) + .unwrap(); + assert_eq!( + state + .apply_server_frame( + json!({"type":"program_changed", "module_hash":"blake3:new", "sequence":5}) + ) + .unwrap(), + ServerUpdate::ProgramChanged + ); + assert_eq!(state.program_module_hash(), Some("blake3:new")); + assert_eq!( + state + .apply_server_frame( + json!({"type":"view", "sequence":5, "data":"new program", "view_revision":1}) + ) + .unwrap(), + ServerUpdate::View + ); + assert_eq!(state.view().unwrap().text_projection(), "new program"); + } + #[test] fn malformed_and_non_session_host_frames_are_rejected() { let mut state = SessionState::default(); From 74edbfbca20e7e4c314533f4d12e5e4e19747429 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Thu, 12 Nov 2026 21:25:10 -0600 Subject: [PATCH 4/4] fix(id): gate BoardGraph::replay_game_lineage behind the sandbox feature replay_game_lineage uses crate::sandbox, which only exists under the sandbox feature, but boards is an unconditional module: any build of the id lib without the sandbox feature (id-native-shell builds id with default-features=false, features=[world]) failed with E0433 on current main. Its only callers are boards tests, which run under the default (sandbox-on) build. Found while running cargo test -p id-native-shell for task 9341 / PR #7197. --- pkgs/id/src/boards.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pkgs/id/src/boards.rs b/pkgs/id/src/boards.rs index 574310a470..3b7156681d 100644 --- a/pkgs/id/src/boards.rs +++ b/pkgs/id/src/boards.rs @@ -1503,6 +1503,7 @@ impl BoardGraph { /// interface. Replay therefore refuses a genesis that does not /// restore to the package's initial state rather than execute a /// signed turn under a possibly wrong participant. + #[cfg(feature = "sandbox")] pub fn replay_game_lineage( &self, game_post: &ArtifactHash,