diff --git a/crates/ghostlight-dungeon/src/eve.rs b/crates/ghostlight-dungeon/src/eve.rs index bc830f5..d2aef65 100644 --- a/crates/ghostlight-dungeon/src/eve.rs +++ b/crates/ghostlight-dungeon/src/eve.rs @@ -66,16 +66,29 @@ pub(crate) fn surface_version(snapshot: Option<&WorldSnapshot>) -> u64 { .unwrap_or(0) } -/// The authenticated surface's own version (Cut 9): `surface_version` folded -/// with the play row's own `revision`, when a play view is available. Additive, -/// not paired: both counters only ever grow, so the sum only ever grows, and it -/// moves whenever either one does — a play-row-only change (a fresh refusal, a -/// newly open question, a closed turn's narration, none of which necessarily -/// commit anything to the world) moves this even though `surface_version` -/// alone would not, which is what lets the SSE path wake for it. No play view -/// (no turn has opened yet, or the table is unavailable) contributes nothing, -/// matching `surface_version`'s own reach when no play card renders at all. -pub(crate) fn authenticated_surface_version( +/// Cut 10 (PA.f148/PA.f160): the wake signal a watching client polls or +/// subscribes to, never a value a client feeds back as `routeHint.sourceVersion`. +/// It folds `surface_version` with the play row's own `revision`, when a play +/// view is available, so a play-row-only change (a fresh refusal, a newly +/// open question, a closed turn's narration, none of which necessarily commit +/// anything to the world) still moves it even though `surface_version` alone +/// would not — the one thing this must do that `surface_version` cannot. +/// Additive, not paired: both counters only ever grow, so the sum only ever +/// grows. No play view (no turn has opened yet, or the table is unavailable) +/// contributes nothing, matching `surface_version`'s own reach when no play +/// card renders at all. +/// +/// Cut 9 folded this same sum into the surface document's own `version` +/// field, which a client echoes straight back as `routeHint.sourceVersion` on +/// its next command; the kernel's compare-and-swap then derives +/// `expected_revision = source_version - 1` from it (`runtime.rs`), so a +/// version that is not exactly `world.revision + 1` poisons every later +/// command with "expected revision N, current revision M" (Soul's own +/// probe). This function is now used for the wake signal alone — +/// `authenticated_surface`'s own document `version` is plain +/// `surface_version`, and the play row's revision travels beside it as its +/// own `playRevision` field instead of folded in. +pub(crate) fn authenticated_wake_version( snapshot: Option<&WorldSnapshot>, play: Option<&PlayTurnView>, ) -> u64 { @@ -101,6 +114,7 @@ pub(crate) fn mesh_surface(snapshot: Option<&WorldSnapshot>) -> Value { fn anonymous_surface_at(version: u64) -> Value { surface_document( version, + 0, "Ghostlight Dungeon", vec![ json!({ @@ -210,7 +224,13 @@ pub(crate) fn authenticated_surface( snapshot: Option<&WorldSnapshot>, play: Option<&PlayTurnView>, ) -> anyhow::Result { - let version = authenticated_surface_version(snapshot, play); + // Cut 10 (PA.f148/PA.f160): the document's own `version` names the + // world's `surface_version` alone — the one meaning `routeHint.sourceVersion` + // and the kernel's compare-and-swap require of it. The play row's own + // revision still moves, but travels as its own field beside it + // (`play_revision` below), never folded into this one. + let version = surface_version(snapshot); + let play_revision = play.map_or(0, |view| view.revision); let mut children = vec![json!({ "id":"ghostlight.identity", "kind":"heimdall.identity", @@ -239,6 +259,20 @@ pub(crate) fn authenticated_surface( "stateBindings":[local_draft("title", "string")], "children":[] }), + // Cut 10 (PA.f149): `CREATE_BINDINGS` has always advertised + // `brief` — `world_create.v4`'s `CreatePayload.brief` is + // required, not `#[serde(default)]` — but no control ever + // captured it. Driving `world.create` with the real + // vendored lowering surfaced this: nothing the lowering + // could ever submit through this form would satisfy + // `world_create.v4`, hand-built test payloads notwithstanding. + json!({ + "id":"world.create.brief", + "kind":"control.input.textarea", + "props":{"label":"Brief","rows":2,"placeholder":"One sentence of what this world is for"}, + "stateBindings":[local_draft("brief", "string")], + "children":[] + }), json!({ "id":"world.create.subject", "kind":"control.input.text", @@ -264,21 +298,21 @@ pub(crate) fn authenticated_surface( "id":"world.create.targets", "kind":"control.input.textarea", "props":{"label":"Scale target","rows":2,"placeholder":"{\"person\": 12, \"institution\": 3}"}, - "stateBindings":[local_draft("targets", "json")], + "stateBindings":[local_draft("targets", "string")], "children":[] }), json!({ "id":"world.create.jurisdictions", "kind":"control.input.textarea", "props":{"label":"Jurisdiction roots","rows":3,"placeholder":"[{\"handle\":\"low_sere\",\"label\":\"The Low Sere\",\"permille\":700}]"}, - "stateBindings":[local_draft("jurisdictions", "json")], + "stateBindings":[local_draft("jurisdictions", "string")], "children":[] }), json!({ "id":"world.create.lens_weights", "kind":"control.input.textarea", "props":{"label":"Lens weights","rows":2,"value":default_lens_weights,"placeholder":default_lens_weights}, - "stateBindings":[local_draft("lens_weights", "json")], + "stateBindings":[local_draft("lens_weights", "string")], "children":[] }), command_button( @@ -297,16 +331,14 @@ pub(crate) fn authenticated_surface( )); } Some(world) => { + // Cut 10 (PA.f159): phase and clock stay; the subject census is + // gone — nothing about who else is in the world is the player's + // own projection, invariant 8's own "nothing else." children.push(json!({ "id":"world.summary", "kind":"card", "props":{"title":world.title,"subtitle":format!("{:?} · revision {} · minute {}", world.phase, world.revision, world.now.0)}, - "children":[{ - "id":"world.summary.body", - "kind":"text", - "props":{"value":format!("{} subject(s)", world.subjects.len())}, - "children":[] - }] + "children":[] })); match world.phase { WorldPhase::Draft => { @@ -406,88 +438,87 @@ pub(crate) fn authenticated_surface( "WorldMailbox", )); } - // Cut 9: the play card. Invariant 8 — the player sees a - // projection, the question, and the refusal of their own - // act, nothing else — so this reads `play` alone, never - // the operator's own unscoped event log: no id, no other - // subject's state, no speech the player did not perceive. - // Always rendered in Active, with empty rows before any - // turn has ever opened. - let mut play_rows = Vec::new(); - if let Some(narration) = play.and_then(|view| view.narration.as_deref()) { - play_rows.push(json!({ - "id":"world.play.narration", - "kind":"text", - "props":{"value":narration}, - "children":[] + // Cut 10 (PA.f152): owner-gated, like `world.advance_time` + // and `world.seed` above — the play card, its controls, + // and the `world.play` descriptor are the owner's own + // play authority over their own world, not a public + // affordance. + if world.owner == ghostlight::PrincipalId::new(account) { + // Cut 9: the play card. Invariant 8 — the player sees + // a projection, the question, and the refusal of + // their own act, nothing else — so this reads `play` + // alone, never the operator's own unscoped event log: + // no id, no other subject's state, no speech the + // player did not perceive. Always rendered here, with + // empty rows before any turn has ever opened. + let mut play_rows = Vec::new(); + if let Some(narration) = play.and_then(|view| view.narration.as_deref()) { + play_rows.push(json!({ + "id":"world.play.narration", + "kind":"text", + "props":{"value":narration}, + "children":[] + })); + } + if let Some(question) = play.and_then(|view| view.question.as_ref()) { + play_rows.push(json!({ + "id":"world.play.question", + "kind":"text", + "props":{"value":question.text.as_str()}, + "children":[] + })); + } + if let Some(refusal) = play.and_then(|view| view.refusal.as_deref()) { + play_rows.push(json!({ + "id":"world.play.refusal", + "kind":"text", + "props":{"value":refusal}, + "children":[] + })); + } + children.push(json!({ + "id":"world.play.card", + "kind":"card", + "props":{"title":"Play"}, + "children":play_rows })); - } - if let Some(question) = play.and_then(|view| view.question.as_ref()) { - play_rows.push(json!({ - "id":"world.play.question", - "kind":"text", - "props":{"value":question.text.as_str()}, - "children":[] - })); - } - if let Some(refusal) = play.and_then(|view| view.refusal.as_deref()) { - play_rows.push(json!({ - "id":"world.play.refusal", - "kind":"text", - "props":{"value":refusal}, - "children":[] - })); - } - children.push(json!({ - "id":"world.play.card", - "kind":"card", - "props":{"title":"Play"}, - "children":play_rows - })); - // PA.f134: `answers` carries the exact `QuestionId` the - // card above is showing, JSON-encoded the same way - // `lens_weights`/`jurisdictions`/`targets` already encode - // a `local_draft("…", "json")` field's own default value - // — never a value a caller builds by hand. `None`/absent - // when no question is open, so the control still opens or - // continues a turn with plain text. With only `text` - // bound, an asked question could never be answered - // through this control at all — the world would wedge. - let answers_default = play - .and_then(|view| view.question.as_ref()) - .map(|question| serde_json::to_string(&question.id)) - .transpose() - .context("the open question's id encodes as JSON")?; - children.extend([ - json!({ - "id":"world.play.answers", - "kind":"control.input.text", - "props":{"label":"Question id","value":answers_default,"hidden":true}, - "stateBindings":[local_draft("answers", "json")], - "children":[] - }), - json!({ - "id":"world.play.text", - "kind":"control.input.textarea", - "props":{"label":"What do you do?","rows":3,"placeholder":"Write freely"}, - "stateBindings":[local_draft("text", "string")], - "children":[] - }), - command_button( + // Cut 10 (PA.f151): no `answers`/question-id control + // any more. The lowering has no authored, non-editable + // binding value (`hidden` is not a prop any renderer + // reads — Soul's own probe found it rendered as a + // plain, editable, visible text box holding the raw + // id), so the server resolves the open question + // itself instead of trusting a client-supplied id at + // all (`runtime.rs::execute_world`'s `world.play` + // arm). PA.f84's guarantee still holds: a stale + // `routeHint.sourceVersion` — one that predates the + // question the player is answering — is refused + // there, so an answer can never land on a question + // the player never saw. + children.extend([ + json!({ + "id":"world.play.text", + "kind":"control.input.textarea", + "props":{"label":"What do you do?","rows":3,"placeholder":"Write freely"}, + "stateBindings":[local_draft("text", "string")], + "children":[] + }), + command_button( + "world.play", + "Play", + "world.play", + json!({}), + &["text"], + ), + ]); + commands.push(command_descriptor( "world.play", - "Play", - "world.play", - json!({}), - &["text", "answers"], - ), - ]); - commands.push(command_descriptor( - "world.play", - "ghostlight.world_play.v0", - &["text", "answers"], - "PlayTable", - )); + "ghostlight.world_play.v0", + &["text"], + "PlayTable", + )); + } } } } @@ -508,6 +539,7 @@ pub(crate) fn authenticated_surface( )); Ok(surface_document( version, + play_revision, snapshot .map(|world| world.title.as_str()) .unwrap_or("Ghostlight Dungeon"), @@ -599,6 +631,7 @@ pub(crate) fn command_result( fn surface_document( version: u64, + play_revision: u64, title: &str, children: Vec, commands: Vec, @@ -610,6 +643,11 @@ fn surface_document( "providerKind":"narrative.simulation", "title":title, "version":version, + // Cut 10 (PA.f148): the play row's own revision, beside `version` + // rather than folded into it — one meaning per field. A client + // watches both to know a play-row-only change happened; only + // `version` is ever fed back as `routeHint.sourceVersion`. + "playRevision":play_revision, "updatedAtUtc":Utc::now().to_rfc3339(), "surface":{ "id":SURFACE_ID, @@ -648,8 +686,48 @@ fn command_descriptor(command: &str, schema: &str, bindings: &[&str], authority: }) } -fn local_draft(key: &str, value_type: &str) -> Value { - json!({"scope":"local-draft","key":key,"type":value_type}) +/// A `captureBindings` entry the vendored browser lowering +/// (`@gamecult/eve-browser-lowering`, `EveStateBindingDescriptor`) actually +/// resolves (Cut 10, PA.f149). Soul's own probe found `world.create`'s +/// buttons submitting `{"bindings":{}}` for every field: the old shape here +/// (`{"scope":"local-draft","key":key,"type":value_type}`) named none of the +/// fields `findAuthoredBindingValue`/`editableBindingContext` read +/// (`bindingName`, `pointerId`, `accessMode`), so the lowering fell back to +/// the control's own node id as the binding name (`world.create.title`, +/// never `title`), which never matches a `captureBindings` entry naming the +/// field alone. +/// +/// This is the vendored package's own working shape — its test suite +/// (`test/host-isolation.test.mjs`) builds exactly this fixture, under a +/// `ghostlight.play` surface id, for its own `composer.message` local-draft +/// binding — copied field-for-field rather than invented: `targetProp`, +/// `pointerId`, `sourceId`, `schemaId`, `routeKind`, `bindingName`, +/// `valueKind`, `accessMode`, `authority`. `bindingName` is the one field +/// that actually has to equal `key`, since `key` is also the exact string +/// Dungeon's own `captureBindings` array and `command_descriptor` advertise; +/// the rest of the descriptor's fields carry no runtime behavior in the +/// current lowering (grep confirms `valueKind` is read nowhere), but are +/// still worth stating correctly rather than leaving absent. +/// +/// `value_kind` must be one of the lowering's own `valueKind` union +/// (`"string" | "number" | "boolean" | "choice" | "string-list"`); Dungeon's +/// own JSON-textarea fields (`targets`, `jurisdictions`, `lens_weights`) are, +/// client-side, plain text controls like any other — there is no JSON +/// `valueKind` — so callers pass `"string"` for those too, and the server +/// side parses the captured text as JSON (`deserialize_json_capture` in +/// `runtime.rs`). +fn local_draft(key: &str, value_kind: &str) -> Value { + json!({ + "targetProp":"value", + "pointerId":format!("ghostlight.local.{key}"), + "sourceId":"eve.browser.local", + "schemaId":"gamecult.eve.local_draft.v1", + "routeKind":"in-process", + "bindingName":key, + "valueKind":value_kind, + "accessMode":"local-draft", + "authority":"eve.browser" + }) } fn short_principal(principal: &str) -> String { diff --git a/crates/ghostlight-dungeon/src/play.rs b/crates/ghostlight-dungeon/src/play.rs index f527c59..78478ff 100644 --- a/crates/ghostlight-dungeon/src/play.rs +++ b/crates/ghostlight-dungeon/src/play.rs @@ -647,6 +647,27 @@ pub(crate) enum RunOutcome { }, } +/// `PlayTable::admit`'s own outcome (Cut 10, PA.f153/PA.f154): a replay is +/// fully decided already — no round ever runs, so nothing is ever spawned +/// for it — while `Spawn` carries the built, already-persisted turn a caller +/// hands to `execute` in a background task. +pub(crate) enum Admission { + Replayed { + turn_id: String, + question: Option, + }, + Spawn(Admitted), +} + +/// An admitted turn, ready for `PlayTable::execute` (Cut 10). Carries the +/// table's own `run_lock` guard (owned, not borrowed — see `run_lock`'s own +/// doc comment) so the lock stays held from admission through the end of +/// execution even when the two happen in different tasks. +pub(crate) struct Admitted { + turn: PlayTurn, + _run_guard: tokio::sync::OwnedMutexGuard<()>, +} + /// The current turn's own player-facing state (PA.f134), read through /// `PlayTable::current_turn_view` — see its own doc comment for why this /// exists beside `RunOutcome`. @@ -705,7 +726,12 @@ pub(crate) struct PlayTable { /// This table is the one owner of one world's play authority, so this is /// "one running turn per world" exactly as `AppState.play` holds one /// `Arc` per world this process owns. - run_lock: Mutex<()>, + /// `Arc`-wrapped since Cut 10 (PA.f153/PA.f154): `admit` takes an owned + /// guard (`try_lock_owned`) so it can hand the guard into a spawned task + /// alongside the turn it built, rather than holding a borrowed guard for + /// a call that must return to its own caller before the turn's round loop + /// finishes. + run_lock: Arc>, poisoned: AtomicBool, /// `retry_delay`'s own base, in milliseconds (PA.f122): an ordinary /// field, always compiled, defaulting to `RETRY_DELAY_BASE_MS` — the @@ -751,7 +777,7 @@ impl PlayTable { model, permits, store: Mutex::new(store), - run_lock: Mutex::new(()), + run_lock: Arc::new(Mutex::new(())), poisoned: AtomicBool::new(false), retry_delay_base_ms: std::sync::atomic::AtomicU64::new(RETRY_DELAY_BASE_MS), #[cfg(test)] @@ -806,26 +832,45 @@ impl PlayTable { key: String, request: PlayRequest, ) -> Result { + match self.admit(key, request).await? { + Admission::Replayed { turn_id, question } => Ok(RunOutcome::Replayed { turn_id, question }), + Admission::Spawn(admitted) => self.execute(admitted, principal).await, + } + } + + /// Cut 10 (PA.f153/PA.f154): the synchronous half of `run` — replay + /// detection, the stale-answer/empty-answer/no-question-open/ + /// turn-still-running/empty-opening refusals, and building (and + /// persisting) the turn a fresh request continues or opens. None of this + /// spends an inference budget, so `runtime.rs::execute_world`'s + /// `world.play` route now awaits this directly and answers `denied` with + /// the reason on `Err`, instead of discarding every refusal inside a + /// spawned task that had already answered `accepted`. Only + /// `Admission::Spawn`'s own turn actually runs a round loop, and only + /// that is spawned, via `execute`. + pub(crate) async fn admit(&self, key: String, request: PlayRequest) -> Result { if self.poisoned.load(Ordering::SeqCst) { return Err(PlayError::Poisoned); } - // PA.f68/PA.f112: held for this whole call, so the replay/key check - // above and the turn open below happen under one acquisition and two - // concurrent `run` calls for this table can never interleave — the - // second one always observes the first one's own already-open (or - // already-closed) turn, never a stale `None`/`Closed` read racing a - // still-in-flight `open_new_turn`. + // PA.f68/PA.f112: held from here through the end of `execute`, so + // the replay/key check below and the turn open happen under one + // acquisition and two concurrent `admit` calls for this table can + // never interleave — the second one always observes the first one's + // own already-open (or already-closed) turn, never a stale + // `None`/`Closed` read racing a still-in-flight `open_new_turn`. // - // PA.f142: `try_lock`, not `lock().await` — a `world.play` route - // spawns this call in a task and returns before it resolves, so a - // second request arriving while a turn's own round loop is still - // running (up to `ROUND_BUDGET` rounds of inference) must be refused - // at once, not queued behind it with no bound and no signal. A - // request that finds the lock free — including an answer to a - // question a prior call already left open and returned from — is - // never affected: nothing holds this lock between one `run` call - // returning and the next one starting. - let Ok(_run_guard) = self.run_lock.try_lock() else { + // PA.f142: `try_lock_owned`, not `lock_owned().await` — a + // `world.play` route spawns the turn's own execution in a task and + // returns before it resolves, so a second request arriving while a + // turn's own round loop is still running (up to `ROUND_BUDGET` + // rounds of inference) must be refused at once, not queued behind it + // with no bound and no signal. A request that finds the lock free — + // including an answer to a question a prior call already left open + // and returned from — is never affected: nothing holds this lock + // between one turn's own execution finishing and the next admission + // starting. Owned (Cut 10), not borrowed, so the guard can move into + // the spawned task alongside the turn `admit` built. + let Ok(run_guard) = Arc::clone(&self.run_lock).try_lock_owned() else { return Err(PlayError::TurnStillRunning); }; let PlayRequest { text, answers } = request; @@ -842,10 +887,10 @@ impl PlayTable { .as_ref() .filter(|current| current.turn_id == turn_id && current.state == PlayTurnState::AwaitingPlayer) .and_then(open_question_of); - return Ok(RunOutcome::Replayed { turn_id, question }); + return Ok(Admission::Replayed { turn_id, question }); } - let (mut turn, is_new_turn) = match stored { + let (turn, is_new_turn) = match stored { Some(existing) if existing.state == PlayTurnState::AwaitingPlayer => { let open_question = existing.open_question_id(); match (answers, open_question.clone()) { @@ -914,7 +959,20 @@ impl PlayTable { } else { self.persist(&turn).await?; } + Ok(Admission::Spawn(Admitted { turn, _run_guard: run_guard })) + } + /// Cut 10 (PA.f153/PA.f154): the round loop `run` used to run inline — + /// the part that can spend a real inference budget across up to + /// `ROUND_BUDGET` rounds. `runtime.rs::execute_world`'s `world.play` + /// route spawns this, never `admit`, so an admission refusal is never + /// silently swallowed behind an already-sent `accepted` response. + pub(crate) async fn execute( + &self, + admitted: Admitted, + principal: &VerifiedPrincipalEvidence, + ) -> Result { + let Admitted { mut turn, _run_guard } = admitted; loop { match turn.state { PlayTurnState::AwaitingPlayer | PlayTurnState::Closed => break, @@ -949,7 +1007,7 @@ impl PlayTable { // narrate failure inside `close_turn` still closes the turn, // with the fault recorded, through `close_with_fault` // (PA.f85/PA.f93). - match self.close_turn(&turn).await { + match self.close_turn(&turn, principal).await { Ok(narration) => { turn.narration = Some(narration); turn.state = PlayTurnState::Closed; @@ -960,7 +1018,7 @@ impl PlayTable { break; } let round = turn.rounds.len(); - match self.infer_round(&turn, round).await { + match self.infer_round(&turn, round, principal).await { Ok(output) => { turn.rounds.push(output); self.persist(&turn).await?; @@ -1079,10 +1137,15 @@ impl PlayTable { /// `InferenceRequest::play` itself), or an `InferenceFault` whose own /// disposition does not retry, or that exhausted its bounded retry /// budget. - async fn infer_round(&self, turn: &PlayTurn, round: usize) -> Result { + async fn infer_round( + &self, + turn: &PlayTurn, + round: usize, + principal: &VerifiedPrincipalEvidence, + ) -> Result { let snapshot = self.round_snapshot().await?; let dispatched = turn.dispatched_subjects(); - let tools = self.round_tools(&snapshot, &dispatched)?; + let tools = self.round_tools(&snapshot, &dispatched, principal)?; let conversation = rebuild_conversation(turn, round); let command_id = CommandId::parse_uuid(&turn.turn_id).map_err(|error| error.to_string())?; @@ -1203,10 +1266,11 @@ impl PlayTable { &self, snapshot: &WorldSnapshot, dispatched: &[SubjectId], + principal: &VerifiedPrincipalEvidence, ) -> Result, String> { let mut tools = authoring_tools(PLAY_TOOLS).map_err(|error| error.to_string())?; tools.extend(control_tools()); - let Some(player) = player_subject(snapshot) else { + let Some(player) = player_subject(snapshot, principal) else { return Ok(tools); }; let mut player_tools = actor_tools(&actor_prefix(player.id), snapshot, player.id); @@ -1248,7 +1312,7 @@ impl PlayTable { return Ok(RoundOutcome::Closed); } }; - let player = player_subject(&snapshot); + let player = player_subject(&snapshot, principal); // Slotted, unresolved tool calls only: `slot` must still count a // call this loop skips as already resolved, so slot numbering never @@ -1310,7 +1374,7 @@ impl PlayTable { if name == END_TURN_TOOL { record_call(turn, call_id, round, this_slot, Some(RecordedCall::EndTurn), None); - match self.close_turn(turn).await { + match self.close_turn(turn, principal).await { Ok(narration) => { if let Some(record) = turn.call_record_mut(round, this_slot) { record.result = Some("the turn ended".to_owned()); @@ -1936,17 +2000,23 @@ impl PlayTable { Ok((RoundOutcome::Continue, finished_summary(summary_slots))) } - /// Narrates the turn's own close to the player. Takes no snapshot or - /// principal of its own (PA.f95: neither parameter was ever read) — - /// it always re-fetches its own fresh snapshot below, since the round's - /// own calls may have committed since any snapshot a caller might have - /// held. - async fn close_turn(&self, turn: &PlayTurn) -> Result { + /// Narrates the turn's own close to the player. Takes no snapshot of its + /// own (PA.f95: it was never read) — it always re-fetches its own fresh + /// snapshot below, since the round's own calls may have committed since + /// any snapshot a caller might have held. Cut 10 (PA.f159) added + /// `principal` back: `player_subject` now resolves the player by whose + /// principal is actually running this turn, not merely "the" human + /// subject in the snapshot. + async fn close_turn( + &self, + turn: &PlayTurn, + principal: &VerifiedPrincipalEvidence, + ) -> Result { // A fresh snapshot, not the round's own: this round's calls may have // committed since it was taken, and `PersonaLane::narrate` refuses // an opportunity that is not the kernel's own currently issued copy. let snapshot = self.play.snapshot().await?; - let Some(player) = player_subject(&snapshot) else { + let Some(player) = player_subject(&snapshot, principal) else { return Ok(String::new()); }; let Some(opportunity) = snapshot @@ -2007,11 +2077,23 @@ struct SubjectRow { id: SubjectId, } -fn player_subject(snapshot: &WorldSnapshot) -> Option { +/// Cut 10 (PA.f159): the subject *this principal's own turn* acts as, not +/// merely "the" human-controlled subject in the world. `WorldSnapshot` +/// already carries `human_controller: Option` on every +/// `SubjectSnapshot` (the library's own field, no library change needed); +/// this was the one production reader still ignoring it, matching by +/// `controller_mode` alone — correct only by accident, in the one-human- +/// subject worlds every fixture happens to build, and wrong the moment a +/// world has more than one. +fn player_subject(snapshot: &WorldSnapshot, principal: &VerifiedPrincipalEvidence) -> Option { + let owner = ghostlight::PrincipalId::new(principal.account_subject_hash()); snapshot .subjects .iter() - .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) + .find(|subject| { + subject.controller_mode == Some(ControllerMode::Human) + && subject.human_controller.as_ref() == Some(&owner) + }) .map(|subject| SubjectRow { id: subject.id }) } @@ -2711,8 +2793,44 @@ mod tests { } } + /// PA.f159: `player_subject` must resolve the acting subject by *whose* + /// principal is calling, not merely by finding a `ControllerMode::Human` + /// subject at all. A mutation reverting the added + /// `human_controller.as_ref() == Some(&owner)` clause — leaving only the + /// old `controller_mode == Some(Human)` check — would still find the + /// fixture's own human subject here even though the calling principal is + /// a stranger to this world entirely, so this fails under exactly that + /// mutation. + #[tokio::test] + async fn the_player_subject_follows_the_calling_principal() { + let fixture = play_world(None, "the-real-owner").await; + let snapshot = fixture.world.snapshot().await.unwrap(); + assert!( + player_subject(&snapshot, &fixture.principal).is_some(), + "the world's own owner/player principal must resolve to the human subject" + ); + let stranger = VerifiedPrincipalEvidence::new("a-stranger-principal", far_future()); + assert!( + player_subject(&snapshot, &stranger).is_none(), + "a principal that does not control any subject here must resolve to none, even though a \ + ControllerMode::Human subject exists in this world" + ); + } + + /// Test fixtures build exactly one human-controlled subject, so this + /// stays the older, principal-blind lookup deliberately (Cut 10, + /// PA.f159) rather than threading a principal through the 20-odd call + /// sites below: it is testing "which subject is the fixture's own + /// player", not the production selection rule `player_subject` now + /// enforces (that rule has its own direct coverage in + /// `the_player_subject_follows_the_calling_principal` below). fn player_id(snapshot: &WorldSnapshot) -> SubjectId { - player_subject(snapshot).unwrap().id + snapshot + .subjects + .iter() + .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) + .expect("a play fixture's own single human subject") + .id } fn persona_id(snapshot: &WorldSnapshot) -> SubjectId { @@ -2820,8 +2938,18 @@ mod tests { /// `eve::authenticated_surface`'s play card must show the narration and /// never the operator feed's own text, proving invariant 8's "nothing /// else": the player sees a projection, the question, and the refusal of - /// their own act, never an unscoped event log. Mutation M9.1: render that - /// feed into the card — this test must fail if the play card ever does. + /// their own act, never an unscoped event log. + /// + /// Mutation M9.1 named "render that feed into the card" as the mutant + /// this test kills. It is retired, not re-aimed (Cut 10, PA.f155): Cut 9 + /// had already deleted the operator-feed parameter `authenticated_surface` + /// once took, so a mutation that "renders the feed into the card" cannot + /// be expressed as a code change against the current signature — there is + /// no parameter left to wire in. The test's own assertions below (the + /// card renders narration/question/refusal and nothing else) remain a + /// live defense of invariant 8 against whatever *can* still leak — most + /// concretely, a future call site that starts threading operator-log text + /// through `narration`/`refusal` themselves. #[tokio::test] async fn the_play_surface_shows_only_the_projection() { let fixture = play_world(None, "player-projection-only").await; @@ -2915,10 +3043,9 @@ mod tests { assert!( !play_card_encoded.contains("A voice the play table never narrated."), "the play card must never render the operator log's own speech, even though it is durably \ - committed and `world.story` still legitimately shows it elsewhere on this surface pending \ - Cut 9's own deletion commit: {play_card_encoded}" + committed to the world owner's own unscoped operator log: {play_card_encoded}" ); - // Every other `world.play.*` node too — the answers/text controls + // Every other `world.play.*` node too — the text control and the // and the button — not only the card itself. for id in ["world.play.answers", "world.play.text", "world.play"] { if let Some(node) = find_surface_node(&surface, id) { @@ -2931,15 +3058,19 @@ mod tests { } } - /// PA.f134's own end-to-end proof, and the fork Self ruled on: answering - /// *through the card's own rendered `world.play.answers` binding* — the - /// id the surface actually emitted, never one this test built — resumes - /// the turn, and the closed turn's narration is then visible through the - /// same card. Also proves the ruling's own `surface_version` claim: the - /// world commits nothing across this whole exchange (`ask_player`/ - /// `end_turn` are conversational, not kernel patches), so - /// `world.revision` never moves, yet `authenticated_surface_version` - /// still does, because the play row's own `revision` carries it. + /// PA.f134's own end-to-end proof: answering *through the turn view's own + /// `question.id`* — the id `current_turn_view` actually exposes, never + /// one this test built — resumes the turn, and the closed turn's + /// narration is then visible through the same card. Cut 10 (PA.f151) + /// deleted the card's own rendered id control (the lowering had no way + /// to carry it without leaking it); `runtime.rs::execute_world`'s + /// `world.play` arm is the one production caller that resolves this id + /// now, the same way this test does. Also proves the ruling's own + /// `playRevision` claim: the world commits nothing across this whole + /// exchange (`ask_player`/`end_turn` are conversational, not kernel + /// patches), so `world.revision` — and so the document's own `version` + /// (Cut 10, PA.f148) — never moves, yet `playRevision` still does, + /// because the play row's own `revision` carries it. #[tokio::test] async fn a_question_is_answered_through_the_cards_own_binding_and_the_turn_closes_with_narration() { let fixture = play_world(None, "player-card-question").await; @@ -2989,22 +3120,19 @@ mod tests { Some(&asked_view), ) .unwrap(); - let version_before = surface_before["version"].as_u64().unwrap(); + let play_revision_before = surface_before["playRevision"].as_u64().unwrap(); let question_row = find_surface_node(&surface_before, "world.play.question") .expect("the question row"); assert_eq!(question_row["props"]["value"], "Which way?"); - let answers_control = - find_surface_node(&surface_before, "world.play.answers").expect("the answers control"); - let raw_answers = answers_control["props"]["value"] - .as_str() - .expect("the answers control carries the open question's id as a JSON string"); - // The exact value `serde_json::to_string` would encode `OpenQuestion.id` - // as (`eve.rs`'s own construction); decoded back here into the same - // private `QuestionId` type, since this test lives in `play`'s own - // module and never touches its fields directly either way. - let answers: QuestionId = - serde_json::from_str(raw_answers).expect("the rendered answers id decodes"); + assert!( + find_surface_node(&surface_before, "world.play.answers").is_none(), + "Cut 10 deleted the id-carrying control; nothing on the surface names the question" + ); + // The exact id `current_turn_view` exposes — the one a production + // caller (`runtime.rs::execute_world`) resolves server-side now, + // never a value the player's own client supplies. + let answers: QuestionId = asked_view.question.as_ref().unwrap().id.clone(); table .run( @@ -3045,13 +3173,22 @@ mod tests { find_surface_node(&surface_after, "world.play.question").is_none(), "no question is open any more; the card must not still show one" ); + // PA.f159: the subject census is gone from `world.summary` — phase + // and clock stay, but who else is in the world is not the player's + // own projection. + let summary = find_surface_node(&surface_after, "world.summary").expect("the summary card"); + assert_eq!(summary["children"], serde_json::json!([])); let narration_row = find_surface_node(&surface_after, "world.play.narration") .expect("the narration row"); assert_eq!(narration_row["props"]["value"], "The hall falls quiet."); - let version_after = surface_after["version"].as_u64().unwrap(); + assert_eq!( + surface_before["version"], surface_after["version"], + "Cut 10: the document's own version names world.revision alone, and it never moved" + ); + let play_revision_after = surface_after["playRevision"].as_u64().unwrap(); assert!( - version_after > version_before, - "surface_version must move even though world.revision did not: {version_before} -> {version_after}" + play_revision_after > play_revision_before, + "playRevision must move even though world.revision did not: {play_revision_before} -> {play_revision_after}" ); } @@ -4341,6 +4478,13 @@ mod tests { serde_json::json!({"question": "Which way?"}), )], ); + // PA.f155/PA.f156: the row's own revision counter must survive the + // restart exactly, neither reset nor re-derived from anything but + // what was last durably committed — checked at three points below: + // right after the question opens, right after the fresh table + // reopens the same store (nothing committed yet, so unchanged), and + // once more after the answer closes the turn (moved again). + let revision_before_restart; { let personas = PersonaLane::new( ControllerPort::new(fixture.world.clone()), @@ -4366,6 +4510,7 @@ mod tests { ) .await .unwrap(); + revision_before_restart = table.current_turn_view().await.unwrap().revision; } // "Restart": a fresh `PlayTable` reopening the same store path. // `PlayTable::new` is the one production door that mints `PlayPort`; @@ -4388,6 +4533,10 @@ mod tests { &store_path, ) .unwrap(); + assert_eq!( + table.current_turn_view().await.unwrap().revision, revision_before_restart, + "reopening the store must read the same revision back, not reset or recompute it" + ); let (opening_prompt_before, turn_id_before, question_id) = { let stored = table.store.lock().await; @@ -4448,6 +4597,12 @@ mod tests { vec!["I stand at a crossroads.".to_owned(), "left".to_owned()] ); assert!(turn.narration.is_some()); + drop(stored); + let revision_after_close = table.current_turn_view().await.unwrap().revision; + assert!( + revision_after_close > revision_before_restart, + "the row's own revision must move again once the answer closes the turn: {revision_before_restart} -> {revision_after_close}" + ); } #[tokio::test] diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index a1d9804..ca7a961 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -9,7 +9,7 @@ use crate::{ TARGET as GHOSTLIGHT_TARGET, }, mesh::{self, MeshPublisher, MeshRuntimeIdentity}, - play::{PlayRequest, PlayTable, PlayTurnView, QuestionId}, + play::{Admission, PlayRequest, PlayTable, PlayTurnState, PlayTurnView}, }; use ghostlight::{ CONSUMER_BODY_LIMIT, CommandBody, CommandId, ConnectorBinding, ConsumerPort, @@ -119,18 +119,64 @@ struct CreatePayload { /// be empty: a world with no target is a deliberate choice, not a default /// that arrives because nobody said anything. A payload that omits it is /// refused, which is what `world_create.v4` means. + #[serde(deserialize_with = "deserialize_json_capture")] targets: BTreeMap, /// The jurisdiction roots, declared by genesis beside the commons because /// `resolve_patch` only resolves roots the same patch declares. A duplicate /// handle and a permille sum over 1000 are refused by the resolver, not /// pre-checked here: a pre-check would be a second reducer. + #[serde(deserialize_with = "deserialize_json_capture")] jurisdictions: Vec, /// Required, and must draw: a payload that omits it is refused, which is /// what `world_create.v4` means. An unknown lens name is refused by /// deserialization before any handler runs. + #[serde(deserialize_with = "deserialize_json_capture")] lens_weights: LensWeights, } +/// Cut 10 (PA.f149): the vendored Eve browser lowering's own +/// `createEveCommandIntent` (`vendor/eve/packages/eve-browser-lowering`) +/// sends every captured `captureBindings` value enveloped under +/// `payload.bindings` — the documented shape (Eve's own +/// `docs/surface-contract-v1.md`: "Operations declare captureBindings and +/// receive those values under payload.bindings"), confirmed by driving the +/// real lowering over a real Dungeon surface (`tools/eve_client_bridge.mjs`). +/// Dungeon's own payload structs are flat. Rather than teach every payload +/// struct the envelope, this unwraps it once, so a real client's payload +/// deserializes exactly like the flat, hand-built payloads the existing +/// tests already send. A payload with no `bindings` object (no +/// `captureBindings` advertised at all, e.g. `world.approve`/ +/// `world.activate`, whose actions capture nothing) passes through +/// unchanged — `commandPayload` on the lowering's own side never sets +/// `bindings` when `captureBindings` is empty. +fn unwrap_bindings(payload: &Value) -> &Value { + payload + .as_object() + .and_then(|object| object.get("bindings")) + .filter(|bindings| bindings.is_object()) + .unwrap_or(payload) +} + +/// Cut 10 (PA.f149): every one of these three fields is edited in a plain +/// `control.input.textarea` — the vendored Eve browser lowering has no +/// JSON-typed control — so a real client always captures the field as the +/// JS string the textarea holds (Dungeon's own `eve::local_draft` calls +/// these fields' `valueKind` `"string"` for exactly this reason), never a +/// parsed object or array. A hand-built payload (existing tests) may still +/// supply the already-parsed value directly. This accepts either: a JSON +/// string is parsed as JSON text; anything else is deserialized as the typed +/// value directly. +fn deserialize_json_capture<'de, D, T>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, + T: serde::de::DeserializeOwned, +{ + match Value::deserialize(deserializer)? { + Value::String(text) => serde_json::from_str(&text).map_err(serde::de::Error::custom), + other => serde_json::from_value(other).map_err(serde::de::Error::custom), + } +} + #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct CreateJurisdiction { @@ -166,16 +212,19 @@ fn is_handle_shape(value: &str) -> bool { && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-') } -/// `world.play`'s own payload (Cut 8b): the player's prose, plus `answers` -/// naming the question this request answers (PA.f84) — `None` for the plain -/// opening/continue shape. Follows `ghostlight.world_speak.v0`'s own field -/// pattern above. +/// `world.play`'s own payload (Cut 8b): the player's prose alone. Cut 10 +/// (PA.f151) deleted the client-supplied `answers` field: the vendored Eve +/// browser lowering has no authored, non-editable binding value (`hidden` is +/// not a prop any renderer reads), so the id-carrying control it used to +/// name would have rendered as a plain, visible, editable text box holding +/// the raw `QuestionId` — a leak, and once editable, a forgeable one. The +/// server resolves the currently open question itself now +/// (`execute_world`'s `world.play` arm), refusing a stale +/// `routeHint.sourceVersion` instead of trusting a client-named id. #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct PlayPayload { text: String, - #[serde(default)] - answers: Option, } #[derive(Debug, Deserialize)] @@ -740,7 +789,7 @@ async fn eve_command( } async fn begin_authentication(state: &AppState, invocation: EveCommandInvocation) -> Response { - if let Err(error) = serde_json::from_value::(invocation.payload.clone()) { + if let Err(error) = serde_json::from_value::(unwrap_bindings(&invocation.payload).clone()) { return Json(eve::command_result( &invocation, "denied", @@ -808,7 +857,7 @@ async fn begin_authentication(state: &AppState, invocation: EveCommandInvocation } async fn complete_authentication(state: &AppState, invocation: EveCommandInvocation) -> Response { - let payload = match serde_json::from_value::(invocation.payload.clone()) { + let payload = match serde_json::from_value::(unwrap_bindings(&invocation.payload).clone()) { Ok(payload) => payload, Err(error) => { return Json(eve::command_result( @@ -952,7 +1001,7 @@ async fn logout( state: &AppState, invocation: EveCommandInvocation, ) -> Response { - if let Err(error) = serde_json::from_value::(invocation.payload.clone()) { + if let Err(error) = serde_json::from_value::(unwrap_bindings(&invocation.payload).clone()) { return Json(eve::command_result( &invocation, "denied", @@ -1091,7 +1140,7 @@ async fn execute_world( .unwrap_or(""), )?; if invocation.operation.operation_id == "world.create" { - let payload: CreatePayload = serde_json::from_value(invocation.payload.clone()) + let payload: CreatePayload = serde_json::from_value(unwrap_bindings(&invocation.payload).clone()) .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; if let Some(root) = payload .jurisdictions @@ -1138,19 +1187,61 @@ async fn execute_world( })); } if invocation.operation.operation_id == "world.play" { - // A play turn is not one kernel command: `PlayTable::run` submits as - // many as its own round loop decides, and a round can spend a real - // inference budget before any of them commit. Routed to the table in - // a spawned task, exactly as the map calls for, rather than held - // open behind this request — the caller polls the world/story - // surface for what the turn actually did, the same way it already - // observes any other committed consequence. - let payload: PlayPayload = serde_json::from_value(invocation.payload.clone()) + // Cut 10 (PA.f152): owner-gated, like `world.advance_time` and + // `world.seed` below — `eve::authenticated_surface` already hides + // the card and the button from anyone else, but the route is the + // actual authority boundary. + let snapshot = current_world(state) + .await + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))? + .ok_or_else(|| RuntimeCommandError::Payload("world has not been created".into()))?; + if snapshot.owner != PrincipalId::new(verified_principal.account_subject_hash()) { + return Err(RuntimeCommandError::Payload( + "only the world's owner may play".into(), + )); + } + let payload: PlayPayload = serde_json::from_value(unwrap_bindings(&invocation.payload).clone()) .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; let table = state .play .clone() .ok_or_else(|| RuntimeCommandError::Payload("the play table is unavailable".into()))?; + // Cut 10 (PA.f151): the server resolves the open question itself — + // the client no longer supplies one at all. No question open: this + // is a plain continue/opening, `answers: None`. A question open: the + // caller must be answering it, and PA.f84's own guarantee (an answer + // cannot land on a question the player never saw) is upheld by + // refusing a `routeHint.sourceVersion` that predates the surface + // version the question first appeared on — the exact + // `authenticated_wake_version` this command's own snapshot and play + // view compute right now, monotonic, so any version at or after the + // question's own first appearance is at least this value once it has + // been reached, and the client always echoes back the most recent + // `version`/`playRevision` pair it was actually served. + let view = table.current_turn_view().await; + // PA.f155: `PlayTurnView::state` is the actual rule this branches + // on — the turn is currently waiting on the player — rather than + // `question.is_some()` standing in for it; `question` is set + // whenever the state is, so this and `question.is_some()` can never + // disagree, but the state is the thing the rule is actually about. + let is_awaiting_player = view + .as_ref() + .is_some_and(|view| view.state == PlayTurnState::AwaitingPlayer); + let answers = match view.as_ref().and_then(|view| view.question.as_ref()).filter(|_| is_awaiting_player) { + None => None, + Some(question) => { + let served = eve::authenticated_wake_version(Some(&snapshot), view.as_ref()); + let source_version = invocation.operation.route_hint.source_version.unwrap_or(0); + if source_version < served { + return Err(RuntimeCommandError::Payload(format!( + "the answer is stale: it names a surface older than the one the question \ + \"{}\" first appeared on", + question.text + ))); + } + Some(question.id.clone()) + } + }; // PA.f147 (reported, not fixed — see Hands' own report): the // unconditional `command_id = CommandId::parse_uuid(...)?` at the // top of this function already refuses a missing or non-uuid key @@ -1161,20 +1252,42 @@ async fn execute_world( // only if it could be shown to matter; it could not, so it was not // kept as unreachable code. let key = invocation.operation.idempotency_key.clone().unwrap_or_default(); + // Cut 10 (PA.f153/PA.f154): `admit` runs synchronously, here, so a + // replayed key, a stale/empty answer, a busy table, and a poisoned + // table all answer `denied` with the reason, instead of being + // decided inside a spawned task whose result nothing ever read. Only + // the turn's own round loop — the part that can spend a real + // inference budget — is spawned. + let admission = table + .admit(key, PlayRequest { text: payload.text, answers }) + .await + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + let admitted = match admission { + Admission::Replayed { .. } => { + return Ok(json!({"kind":"accepted","outcome":"replayed"})); + } + Admission::Spawn(admitted) => admitted, + }; let principal = verified_principal.clone(); + let spawned_state = state.clone(); tokio::spawn(async move { - if let Err(error) = table - .run( - &principal, - key, - PlayRequest { - text: payload.text, - answers: payload.answers, - }, - ) - .await - { - tracing::warn!(%error, "a play turn ended in error"); + if let Err(error) = table.execute(admitted, &principal).await { + // PA.f155: `PlayTurnView::turn_id` names which turn faulted, + // for an operator reading this log against the store — the + // one production reader it had none of before. + let turn_id = table.current_turn_view().await.map(|view| view.turn_id); + tracing::warn!(%error, ?turn_id, "a play turn ended in error"); + } + // Cut 10 (PA.f150): a play-row-only change (a fresh refusal, a + // newly open question, a closed turn's narration) commits + // nothing to the world, so nothing on the `eve_command` Ok arm's + // own `publish_projection` call (`dispatch_world`) would ever + // fire for it — that call only runs for this same command's own + // immediate `accepted` response, sent before this turn's own + // execution even started. This is the turn's own commit, + // published on the same door. + if let Err(error) = publish_projection(&spawned_state).await { + tracing::warn!(%error, "play turn projection publish failed"); } }); return Ok(json!({"kind":"accepted"})); @@ -1194,17 +1307,17 @@ async fn execute_world( })?; let body = match invocation.operation.operation_id.as_str() { "world.approve" => { - serde_json::from_value::(invocation.payload.clone()) + serde_json::from_value::(unwrap_bindings(&invocation.payload).clone()) .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; CommandBody::ApproveDraft } "world.activate" => { - serde_json::from_value::(invocation.payload.clone()) + serde_json::from_value::(unwrap_bindings(&invocation.payload).clone()) .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; CommandBody::ActivateWorld } "world.advance_time" => { - let payload: AdvanceTimePayload = serde_json::from_value(invocation.payload.clone()) + let payload: AdvanceTimePayload = serde_json::from_value(unwrap_bindings(&invocation.payload).clone()) .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; CommandBody::AdvanceTime { minutes: TickMinutes::new(payload.minutes).ok_or_else(|| { @@ -1216,7 +1329,7 @@ async fn execute_world( // through its own port, as the owner, and the receipt reports what one // session did rather than what one command committed. "world.seed" => { - let payload: SeedPayload = serde_json::from_value(invocation.payload.clone()) + let payload: SeedPayload = serde_json::from_value(unwrap_bindings(&invocation.payload).clone()) .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; let outcome = seed_once(state, verified_principal, &snapshot, payload).await?; let after = current_world(state) @@ -1300,8 +1413,22 @@ async fn current_play_view(state: &AppState) -> Option { async fn publish_projection(state: &AppState) -> anyhow::Result { let snapshot = current_world(state).await?; + // Cut 10 (PA.f148/PA.f150): `version` is the one meaning a caller ever + // feeds back as `routeHint.sourceVersion` — this function's own return + // value, used by `dispatch_world` as `command_result.sourceVersion` — so + // it stays plain `surface_version`, never folded with the play row's own + // revision. The SSE broadcast below is a different field with a + // different job (wake a watching client up; it is never echoed back), + // so it carries `authenticated_wake_version` instead, the one value that + // also moves on a play-row-only change — this is the fix for PA.f150: + // before Cut 10, this function was the *only* production caller of + // `publish_projection`/its SSE send outside `eve_command`'s own Ok arm, + // and a play commit never reached either, so nothing ever woke a + // watching client up for a fresh question, narration, or refusal. let version = eve::surface_version(snapshot.as_ref()); - let _ = state.revisions.send(version); + let play_view = current_play_view(state).await; + let wake_version = eve::authenticated_wake_version(snapshot.as_ref(), play_view.as_ref()); + let _ = state.revisions.send(wake_version); if let Some(mesh) = state.mesh.clone() { let _projection = tokio::task::spawn_blocking(move || { if let Err(error) = mesh.publish(snapshot.as_ref()) { @@ -2244,6 +2371,175 @@ mod tests { serde_json::from_slice(&bytes).unwrap() } + async fn get(state: &AppState, cookie: &str, path: &str) -> Value { + let response = api_router(state.clone()) + .oneshot( + Request::builder() + .method("GET") + .uri(path) + .header(header::COOKIE, format!("{COOKIE_NAME}={cookie}")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + /// Cut 10 (PA.f149): drives the real vendored Eve browser lowering + /// (`vendor/eve/packages/eve-browser-lowering`, submodule pin unmoved) + /// over a surface document this process actually served, through + /// `tools/eve_client_bridge.mjs`. `steps` is the bridge's own + /// `{"set":{node_id:text}}`/`{"click":node_id}` step list; returns the + /// command intent(s) the click(s) produced, in order, exactly as a real + /// client would build and send them — never a hand-built payload + /// asserting its own shape is correct. + fn client_intents(surface: &Value, provider: &Value, steps: Value) -> Vec { + let bridge = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .join("tools") + .join("eve_client_bridge.mjs"); + let input = serde_json::to_vec(&json!({ + "surface": surface, + "provider": provider, + "steps": steps, + })) + .unwrap(); + let mut child = std::process::Command::new("node") + .arg(&bridge) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("node must be on PATH to run the client bridge"); + { + use std::io::Write; + child.stdin.take().unwrap().write_all(&input).unwrap(); + } + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "eve_client_bridge.mjs failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout) + .unwrap() + .lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| serde_json::from_str(line).unwrap()) + .collect() + } + + /// PA.f149's own end-to-end proof: `world.create`, `world.approve`, + /// `world.seed`, and `world.activate` intents, built by the real + /// vendored lowering over surfaces this process actually served, and + /// posted through `api_router` — every one of them accepted. Before + /// this cut, every one of them submitted `{"bindings":{}}` (wrong + /// binding names) and, even with the names fixed, `{"payload": + /// {"bindings":{...}}}` (the envelope) against Dungeon's flat payload + /// structs — either alone was enough to refuse every field as missing. + /// + /// `world.play` is included through "the route accepts it and the turn + /// reaches the play table" (the same proof + /// `world_play_reaches_the_play_table_and_is_accepted` already gives + /// hand-built payloads, given here to the real client's own payload + /// instead). This fixture's inference organ is an unreachable test + /// address (`127.0.0.1:9`, see `fixture()`), so the turn it opens can + /// never actually reach `AwaitingPlayer` here to prove the "answer" leg + /// through this same harness — that would need a scripted inference + /// port, which lives only inside `play.rs`'s own private test module + /// (`ScriptedPort`) and is not reachable from here. PA.f151's own + /// server-resolved-answer mechanism has its own direct proof instead, at + /// the play-table layer: + /// `play::tests::a_question_is_answered_through_the_cards_own_binding_and_the_turn_closes_with_narration`. + #[tokio::test] + async fn world_create_seed_activate_and_play_round_trip_through_the_real_client() { + let fixture = fixture().await; + let provider = get(&fixture.state, &fixture.cookie, "/api/eve/provider").await; + + let empty_surface = get(&fixture.state, &fixture.cookie, "/api/eve/surfaces/ghostlight.play").await; + let create_intents = client_intents( + &empty_surface, + &provider, + json!([ + {"set": { + "world.create.title": "Bridge World", + "world.create.brief": "A world built by the real client bridge.", + "world.create.subject": "The Bridge Operator", + "world.create.targets": "{}", + "world.create.jurisdictions": "[]", + "world.create.lens_weights": "{\"patina\":1,\"charter\":1,\"ledger\":1,\"hearth\":1,\"tangle\":1,\"veil\":1,\"ember\":1,\"numen\":1}" + }}, + {"click": "world.create"} + ]), + ); + assert_eq!(create_intents.len(), 1); + let created = post(&fixture.state, &fixture.cookie, create_intents.into_iter().next().unwrap()).await; + assert_eq!(created["state"], "accepted", "world.create via the real client: {created}"); + + let draft_surface = get(&fixture.state, &fixture.cookie, "/api/eve/surfaces/ghostlight.play").await; + let approve_intents = client_intents(&draft_surface, &provider, json!([{"click": "world.approve"}])); + assert_eq!(approve_intents.len(), 1); + let approved = post(&fixture.state, &fixture.cookie, approve_intents.into_iter().next().unwrap()).await; + assert_eq!(approved["state"], "accepted", "world.approve via the real client: {approved}"); + + let approved_surface = get(&fixture.state, &fixture.cookie, "/api/eve/surfaces/ghostlight.play").await; + let seed_intents = client_intents(&approved_surface, &provider, json!([{"click": "world.seed"}])); + assert_eq!(seed_intents.len(), 1); + let seeded = post(&fixture.state, &fixture.cookie, seed_intents.into_iter().next().unwrap()).await; + // No test fixture in this crate configures `GHOSTLIGHT_SEED_VAULT_ROOT` + // (`world_seed_is_owner_only_and_draft_only_before_it_spends_anything` + // asserts the same denial), so a real vault read is out of reach + // here regardless of payload shape. The proof this leg carries is + // narrower: the payload itself was accepted and reached the vault + // lookup at all — `SeedPayload` has no required field, so + // `captureBindings: []` (the click alone) is this operation's own + // envelope-only proof — never refused as a payload/binding shape + // problem the way every operation was before this cut. + assert_eq!( + seeded["message"], "invalid command payload: GHOSTLIGHT_SEED_VAULT_ROOT is not configured", + "world.seed via the real client must reach the vault lookup, not refuse the payload shape: {seeded}" + ); + + let seeded_surface = get(&fixture.state, &fixture.cookie, "/api/eve/surfaces/ghostlight.play").await; + let activate_intents = client_intents(&seeded_surface, &provider, json!([{"click": "world.activate"}])); + assert_eq!(activate_intents.len(), 1); + let activated = post(&fixture.state, &fixture.cookie, activate_intents.into_iter().next().unwrap()).await; + assert_eq!(activated["state"], "accepted", "world.activate via the real client: {activated}"); + + let active_surface = get(&fixture.state, &fixture.cookie, "/api/eve/surfaces/ghostlight.play").await; + let play_intents = client_intents( + &active_surface, + &provider, + json!([ + {"set": {"world.play.text": "The new owner looks around."}}, + {"click": "world.play"} + ]), + ); + assert_eq!(play_intents.len(), 1); + let played = post(&fixture.state, &fixture.cookie, play_intents.into_iter().next().unwrap()).await; + assert_eq!(played["state"], "accepted", "world.play via the real client: {played}"); + + let table = fixture.state.play.clone().unwrap(); + let observed = tokio::time::timeout(Duration::from_secs(5), async move { + loop { + if table.current_turn_view().await.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + assert!( + observed.is_ok(), + "the real client's own world.play intent must reach PlayTable::run and open a turn row" + ); + } + #[tokio::test] async fn http_eve_journey_uses_one_world_owner() { let fixture = fixture().await; @@ -2403,6 +2699,328 @@ mod tests { ); } + /// PA.f148/PA.f160: Soul's own probe — the served document's `version` + /// used to fold the play row's own revision in, so a play commit alone + /// (no kernel patch) could move `version` to a number `world.revision` + /// never reached, and every later command's compare-and-swap derived + /// `expected_revision` from it and was permanently denied. This drives + /// the exact same shape: open a play turn (it commits nothing to the + /// world here — the fixture's own inference organ is unreachable, so it + /// faults immediately, which still exercises the row's own revision + /// counter the same way a real committed refusal or question would), + /// wait for the row to move, then read `sourceVersion` from the actually + /// served surface document — as a client does — and submit + /// `world.advance_time` against it. It must still be accepted. + #[tokio::test] + async fn a_play_commit_does_not_poison_the_next_world_commands_compare_and_swap() { + let fixture = fixture().await; + let created = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.create", + "ghostlight.world_create.v4", + 0, + json!({ + "title":"CAS World", + "brief":"", + "subject_label":"Operator", + "targets":{}, + "jurisdictions":[], + "lens_weights":{"patina":1,"charter":1,"ledger":1,"hearth":1,"tangle":1,"veil":1,"ember":1,"numen":1} + }), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(created["state"], "accepted"); + let approved = post( + &fixture.state, + &fixture.cookie, + invocation("world.approve", "ghostlight.world_approve.v0", 1, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(approved["state"], "accepted"); + let activated = post( + &fixture.state, + &fixture.cookie, + invocation("world.activate", "ghostlight.world_activate.v0", 2, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(activated["state"], "accepted"); + assert_eq!(activated["sourceVersion"], 3, "world.revision is 3, and nothing has folded anything else into it yet"); + + let played = post( + &fixture.state, + &fixture.cookie, + invocation("world.play", "ghostlight.world_play.v0", 3, json!({"text":"I look around."}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(played["state"], "accepted"); + + let table = fixture.state.play.clone().unwrap(); + tokio::time::timeout(Duration::from_secs(5), async move { + loop { + if let Some(view) = table.current_turn_view().await { + if view.revision > 0 { + break; + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the play row's own revision must move once the turn commits its own row"); + + // As a client does: read `version` off the actually served document, + // never re-derive it from `world.revision` directly. + let surface = get(&fixture.state, &fixture.cookie, "/api/eve/surfaces/ghostlight.play").await; + let served_version = surface["version"].as_u64().expect("the surface document names a version"); + assert_eq!( + served_version, 3, + "PA.f148: the document's own version must still name world.revision alone, not the play row's \ + revision folded in — Soul's own probe was a version that did not" + ); + + let advanced = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.advance_time", + "ghostlight.world_advance_time.v0", + served_version, + json!({"minutes": 5}), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!( + advanced["state"], "accepted", + "a play commit must never poison the next world command's compare-and-swap: {advanced}" + ); + } + + /// PA.f150: `publish_projection` used to be called only at startup and + /// from `eve_command`'s own Ok arm — which answers a `world.play` + /// request before its own turn ever executes — so a play-row-only + /// change (a fresh refusal, a newly open question, a closed turn's + /// narration, none of which move `world.revision`) never republished at + /// all, and a watching client's SSE subscription never woke for it. + /// Drives a real play turn to a fault (the fixture's own inference organ + /// is unreachable, so this always happens quickly) and asserts the + /// `state.revisions` channel — what `/api/eve/events` relays — receives + /// a fresh value for it, on the same door `eve_command`'s own commits use. + #[tokio::test] + async fn a_play_row_only_change_wakes_the_revisions_channel() { + let fixture = fixture().await; + let created = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.create", + "ghostlight.world_create.v4", + 0, + json!({ + "title":"Wake World", + "brief":"", + "subject_label":"Operator", + "targets":{}, + "jurisdictions":[], + "lens_weights":{"patina":1,"charter":1,"ledger":1,"hearth":1,"tangle":1,"veil":1,"ember":1,"numen":1} + }), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(created["state"], "accepted"); + let approved = post( + &fixture.state, + &fixture.cookie, + invocation("world.approve", "ghostlight.world_approve.v0", 1, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(approved["state"], "accepted"); + let activated = post( + &fixture.state, + &fixture.cookie, + invocation("world.activate", "ghostlight.world_activate.v0", 2, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(activated["state"], "accepted"); + + // Subscribed after every world-commit publish above has already + // happened, so only the play turn's own publish (or a lagged + // catch-up of it) can satisfy this recv. + let mut revisions = fixture.state.revisions.subscribe(); + + let played = post( + &fixture.state, + &fixture.cookie, + invocation("world.play", "ghostlight.world_play.v0", 3, json!({"text":"I look around."}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(played["state"], "accepted"); + + let woke = tokio::time::timeout(Duration::from_secs(5), revisions.recv()).await; + assert!( + woke.is_ok(), + "the play turn's own commit must publish a fresh revision to the SSE channel, not only \ + eve_command's own already-sent accepted response" + ); + } + + /// PA.f153/PA.f154: before this cut, `world.play`'s route spawned + /// `PlayTable::run` in a task and answered `{"kind":"accepted"}` + /// unconditionally, discarding whatever `run` returned into a log line + /// nothing read — a replayed key, a stale/empty answer, a busy table, and + /// a poisoned table all looked exactly like success to the caller. + /// `admit` now runs synchronously in the route, so an admission refusal + /// — here, an empty/whitespace-only opening with no turn currently open + /// to continue — reaches the caller as `denied`, with the reason, + /// instead. + #[tokio::test] + async fn an_admission_refusal_reaches_the_caller_as_denied_not_accepted() { + let fixture = fixture().await; + let created = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.create", + "ghostlight.world_create.v4", + 0, + json!({ + "title":"Admission World", + "brief":"", + "subject_label":"Operator", + "targets":{}, + "jurisdictions":[], + "lens_weights":{"patina":1,"charter":1,"ledger":1,"hearth":1,"tangle":1,"veil":1,"ember":1,"numen":1} + }), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(created["state"], "accepted"); + let approved = post( + &fixture.state, + &fixture.cookie, + invocation("world.approve", "ghostlight.world_approve.v0", 1, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(approved["state"], "accepted"); + let activated = post( + &fixture.state, + &fixture.cookie, + invocation("world.activate", "ghostlight.world_activate.v0", 2, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(activated["state"], "accepted"); + + let opened_empty = post( + &fixture.state, + &fixture.cookie, + invocation("world.play", "ghostlight.world_play.v0", 3, json!({"text":" "}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!( + opened_empty["state"], "denied", + "an empty/whitespace-only opening with no turn open must be denied, not accepted: {opened_empty}" + ); + assert!( + opened_empty["message"].as_str().unwrap().contains("empty"), + "the denial must carry the admission refusal's own reason: {opened_empty}" + ); + + // No turn was ever admitted, so nothing was ever spawned either. + let table = fixture.state.play.clone().unwrap(); + assert!( + table.current_turn_view().await.is_none(), + "a denied admission must never open a turn row" + ); + } + + /// PA.f152: `world.play` is owner-gated like `world.advance_time` and + /// `world.seed` — both the surface (no card, no controls, no descriptor + /// for anyone else) and the route itself, since the surface is only a + /// hint a hostile client can ignore. + #[tokio::test] + async fn world_play_is_owner_gated_on_the_surface_and_the_route() { + let fixture = fixture().await; + let created = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.create", + "ghostlight.world_create.v4", + 0, + json!({ + "title":"Owner-Gated World", + "brief":"", + "subject_label":"Operator", + "targets":{}, + "jurisdictions":[], + "lens_weights":{"patina":1,"charter":1,"ledger":1,"hearth":1,"tangle":1,"veil":1,"ember":1,"numen":1} + }), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(created["state"], "accepted"); + let approved = post( + &fixture.state, + &fixture.cookie, + invocation("world.approve", "ghostlight.world_approve.v0", 1, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(approved["state"], "accepted"); + let activated = post( + &fixture.state, + &fixture.cookie, + invocation("world.activate", "ghostlight.world_activate.v0", 2, json!({}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!(activated["state"], "accepted"); + + // A stranger's own authenticated session — a different account, so a + // different `PrincipalId`, never the world's own owner. + let mut sessions = fixture.state.sessions.lock().await; + let stranger_cookie = sessions + .create_session(heimdall::VerifiedSessionAdmission::fixture( + "a-stranger-account", + "heimdall-session-stranger", + 2, + Utc::now() + chrono::Duration::hours(1), + Utc::now() + chrono::Duration::days(1), + "fixture-refresh-stranger", + )) + .unwrap(); + drop(sessions); + + let stranger_surface = get(&fixture.state, &stranger_cookie, "/api/eve/surfaces/ghostlight.play").await; + let encoded = serde_json::to_string(&stranger_surface).unwrap(); + assert!( + !encoded.contains("world.play"), + "a non-owner's own surface must carry no play card, control, or command descriptor: {encoded}" + ); + + let played = post( + &fixture.state, + &stranger_cookie, + invocation("world.play", "ghostlight.world_play.v0", 3, json!({"text":"I look around."}), &uuid::Uuid::new_v4().to_string()), + ) + .await; + assert_eq!( + played["state"], "denied", + "the route itself must refuse a non-owner's world.play, not only hide the affordance: {played}" + ); + + let table = fixture.state.play.clone().unwrap(); + assert!( + table.current_turn_view().await.is_none(), + "a non-owner's own denied world.play must never open a turn row" + ); + } + /// Same route, with `state.play` unavailable (mirrors `controllers: /// None` elsewhere in this suite): refused, not a panic or a hang. #[tokio::test]