diff --git a/crates/ghostlight-dungeon/src/play.rs b/crates/ghostlight-dungeon/src/play.rs index e30c412..eea15f6 100644 --- a/crates/ghostlight-dungeon/src/play.rs +++ b/crates/ghostlight-dungeon/src/play.rs @@ -33,7 +33,7 @@ use ghostlight::{ InferenceOutput, InferencePort, InferenceRequest, KernelError, MailboxError, PersonaLane, PlayPort, PrincipalCommandIntent, Statement, SubjectId, TickMinutes, VerifiedPrincipalEvidence, WorldMailbox, WorldPatch, WorldSnapshot, actor_tools, authoring_tools, decode_actor_call, - decode_authoring_calls, describe_refusal, describe_refusal_to_actor, id_text, id_text_matches, + decode_authoring_calls, describe_refusal, describe_refusal_to_actor, handle_for, id_text, id_text_matches, table_view, }; use ghostlight_persona_projection::{PersonaTurn, SourceSpan}; @@ -2130,7 +2130,11 @@ impl PlayTable { let (subjects, refusals) = match recorded { Some(RecordedCall::Dispatch(subjects)) => (subjects, Vec::new()), _ => { - let (subjects, refusals) = parse_dispatch(arguments, &snapshot); + let (subjects, refusals) = if name == REACT_TOOL && react_omits_subjects(arguments) { + (react_room(&snapshot, player.as_ref(), &turn.dispatched_subjects()), Vec::new()) + } else { + parse_dispatch(arguments, &snapshot) + }; // PA.f125: this call's own body — which subjects it // intends to dispatch — is recorded and persisted // before `execute_dispatch` runs any persona turn, @@ -2164,7 +2168,11 @@ impl PlayTable { // refused in the tool result, quoting what was given, never // dropped silently. let result = if refusals.is_empty() { - dispatch_summary + if dispatch_summary.is_empty() && subjects.is_empty() && name == REACT_TOOL { + "no one else is in the room who has not already acted this turn".to_owned() + } else { + dispatch_summary + } } else { let refusals = refusals.join("; "); if dispatch_summary.is_empty() { @@ -2646,7 +2654,7 @@ impl PlayTable { } }; let label = subject_label(&snapshot, *subject); - summary_slots[index] = Some(format!("{label} (draft, not yet in the world; commit through `{}__speak`): {prose}", handle_for(*subject))); + summary_slots[index] = Some(draft_line(&label, *subject, &prose, grouped)); } else { // PA.f124: printed through the library's own `id_text`, // the same printer `table_view` and `dispatch`'s own @@ -2675,6 +2683,21 @@ impl PlayTable { return Ok((RoundOutcome::Closed, finished_summary(summary_slots))); } }; + if grouped + && snapshot + .subjects + .iter() + .find(|row| row.id == *subject) + .is_some_and(|row| row.controller_mode != Some(ControllerMode::NarrativePersona)) + { + // The room's Gestalt round runs Personas only; anyone else acts + // on their own lane and is named here, not run. + summary_slots[index] = Some(format!( + "{} is not a Persona: it acts on its own lane and was not run in this round", + subject_label(&snapshot, *subject) + )); + continue; + } let Some(opportunity) = snapshot .opportunities .iter() @@ -2770,7 +2793,7 @@ impl PlayTable { // already generic over every call's recorded `result`, // so recording the prose here is the whole fix. let prose = persona_turn.source_prose().to_owned(); - summary_slots[entry.index] = Some(format!("{label} (draft, not yet in the world; commit through `{}__speak`): {prose}", handle_for(entry.subject))); + summary_slots[entry.index] = Some(draft_line(&label, entry.subject, &prose, grouped)); turn.persona_turns.push((entry.subject, persona_turn)); // PA.f123: `execute_dispatch` was the only call kind that // did not persist at its own site — every other tool @@ -2911,23 +2934,6 @@ fn subject_label(snapshot: &WorldSnapshot, subject: SubjectId) -> String { .map_or_else(|| "an unknown subject".to_owned(), |row| row.label.clone()) } -/// A subject's own short handle: the first 8 hex digits of its id -/// (PA.f97). Actor tool names are `__`, and a kind may run up -/// to 48 chars, so the full 36-char uuid text a handle used to carry could -/// reach 86 chars against a common 64-char function-name limit; 8 hex -/// digits plus the `__` separator keeps every name well under that limit -/// (`the_longest_possible_actor_tool_name_is_64_chars_or_fewer`) while still -/// reading as the same bracketed id prefix `table_view` prints. The id text -/// itself comes from the library's own `id_text` (PA.f113/PA.f129) — no -/// second, hand-written debug-paren strip here. -/// Collision between two subjects sharing a handle is astronomically -/// unlikely but not impossible; `round_tools` refuses the whole round as a -/// turn fault rather than silently addressing the wrong subject -/// (`find_handle_collision`). -fn handle_for(id: SubjectId) -> String { - id_text(id).chars().filter(char::is_ascii_hexdigit).take(8).collect() -} - /// Appends one actor tool's own acting subject's label and full canonical id /// to its description (PA.f98): `dispatch` takes the id exactly as /// `table_view` prints it, never the short `__` prefix these tools' @@ -3007,14 +3013,16 @@ draft: it is in the world once you commit it through their own `__speak` }, ToolDefinition { name: REACT_TOOL.into(), - description: "The room reacts: one call in which every person you name, together, decides how \ -they take what just happened, each from their own view, and may speak, show it, act or stay silent. Use it \ -for the onlookers when the player speaks or acts in front of others who are not the one addressed, so the \ -room is never frozen around a conversation; give the person addressed their own turn with `dispatch`. \ -Names are full ids as table_view prints them in brackets. Like `dispatch`, what comes back is draft prose \ + description: "The room reacts: one call in which every person present, together, decides how \ +they take what just happened, each from their own view, and may speak, show it, act or stay silent. Omit \ +`subjects` to react everyone in the player's room who has not yet had a turn this turn; name people (full \ +ids as table_view prints them in brackets) only to react a chosen few. Use it for the onlookers when the \ +player speaks or acts in front of others who are not the one addressed, so the room is never frozen around \ +a conversation; give the person addressed their own turn with `dispatch`. The result says who reacted, who \ +stayed silent and who is not a Persona and so was not run. Like `dispatch`, what comes back is draft prose \ for you to commit through each person's own `__speak` tool." .into(), - parameters_json: r#"{"type":"object","properties":{"subjects":{"type":"array","items":{"type":"string"}}},"required":["subjects"]}"#.into(), + parameters_json: r#"{"type":"object","properties":{"subjects":{"type":"array","items":{"type":"string"}}},"required":[]}"#.into(), }, ToolDefinition { name: ADVANCE_TIME_TOOL.into(), @@ -3089,6 +3097,44 @@ fn parse_dispatch(arguments: &str, snapshot: &WorldSnapshot) -> (Vec, (subjects, refusals) } +/// Whether a `react` call names nobody: its `subjects` key is missing or an empty +/// array, so the call means the player's room. Anything else (a malformed body, a +/// named list) goes through `parse_dispatch` and its refusals. +fn react_omits_subjects(arguments: &str) -> bool { + match serde_json::from_str::(arguments) { + Ok(Value::Object(fields)) => match fields.get("subjects") { + None => true, + Some(Value::Array(items)) => items.is_empty(), + Some(_) => false, + }, + _ => false, + } +} + +/// The audience of a `react` that names nobody: everyone co-located with the +/// player (non-human controllers only) who has not already acted this turn. +/// Derived once, when the call's body is first recorded; a resumed call reads the +/// recorded list and never re-derives it. +fn react_room(snapshot: &WorldSnapshot, player: Option<&SubjectRow>, dispatched: &[SubjectId]) -> Vec { + let Some(player) = player else { + return Vec::new(); + }; + snapshot + .co_located(player.id) + .into_iter() + .filter(|subject| !dispatched.contains(subject)) + .collect() +} + +/// One subject's line in a `dispatch` or `react` result: a draft to commit, or, +/// in the room's Gestalt round, a note that the Persona stayed silent. +fn draft_line(label: &str, subject: SubjectId, prose: &str, grouped: bool) -> String { + if grouped && prose == "Silent." { + return format!("{label} stayed silent"); + } + format!("{label} (draft, not yet in the world; commit through `{}__speak`): {prose}", handle_for(subject)) +} + fn parse_ask_player(arguments: &str) -> String { serde_json::from_str::(arguments) .ok() @@ -6392,7 +6438,7 @@ pub(crate) mod tests { let personas = PersonaLane::new( ControllerPort::new(fixture.world.clone()), ScriptedPort::new(vec![ - output("gestalt", vec![text_event("=== Mara ===\nMara tightens her grip on the ledger.")]), + output("gestalt", vec![text_event(&format!("=== {}: Mara ===\nMara tightens her grip on the ledger.", handle_for(persona_id(&snapshot))))]), output("proj-narrate", vec![text_event("Quiet.")]), ]), "gpt-5.6-sol".into(), @@ -6418,6 +6464,419 @@ pub(crate) mod tests { assert_eq!(turn.persona_turns.len(), 1); } + /// Declares one subject standing in the place `place_id` names, through the + /// play door; `controller` is the authoring tag (`narrative_persona` or + /// `operational_agent`). + async fn declare_standing(world: &WorldMailbox, handle: &str, label: &str, kind: &str, controller: &str, place_id: &str) { + let snapshot = world.snapshot().await.unwrap(); + let speak = bracketed_id_after(&table_view(&snapshot), "speak ["); + let call = decode_authoring_call( + "declare_subject", + &serde_json::json!({ + "handle": handle, + "label": label, + "kind": kind, + "controller": {"type": controller}, + "affordances": [{"ref": "existing", "value": speak}], + "position": {"ref": "existing", "value": place_id}, + }) + .to_string(), + ) + .unwrap(); + PlayPort::new(world.clone()).submit_patch(CommandId::new(), call).await.unwrap(); + } + + async fn declare_cellar(world: &WorldMailbox) -> String { + let call = decode_authoring_call( + "declare_place", + &serde_json::json!({"handle": "cellar", "label": "Cellar", "container": null}).to_string(), + ) + .unwrap(); + PlayPort::new(world.clone()).submit_patch(CommandId::new(), call).await.unwrap(); + bracketed_id_after(&table_view(&world.snapshot().await.unwrap()), "Cellar [") + } + + fn commons_of(snapshot: &WorldSnapshot) -> String { + bracketed_id_after(&table_view(snapshot), "The Commons [") + } + + fn subject_by_label(snapshot: &WorldSnapshot, label: &str) -> SubjectId { + snapshot.subjects.iter().find(|row| row.label == label).unwrap().id + } + + fn react_table( + fixture: &WorldFixture, + persona_outputs: Vec, + rounds: Vec, + store: &std::path::Path, + ) -> (PlayTable, Arc) { + let persona_port = ScriptedPort::new(persona_outputs); + let personas = PersonaLane::new( + ControllerPort::new(fixture.world.clone()), + persona_port.clone(), + "gpt-5.6-sol".into(), + "gpt-5.6-sol".into(), + ) + .unwrap(); + let table = PlayTable::new( + fixture.world.clone(), + personas, + ScriptedPort::new(rounds), + "gpt-5.6-terra".into(), + Arc::new(Semaphore::new(2)), + store, + ) + .unwrap(); + (table, persona_port) + } + + fn react_then_end(arguments: serde_json::Value) -> InferenceOutput { + output( + "r0", + vec![ + call_event("c0", REACT_TOOL, arguments), + call_event("c1", END_TURN_TOOL, serde_json::json!({})), + ], + ) + } + + /// The Gestalt request the Persona port saw, as text, if the round made one. + fn gestalt_prompt(port: &ScriptedPort) -> Option { + port.seen_requests() + .iter() + .map(|request| serde_json::to_string(request).unwrap()) + .find(|text| text.contains("Several people stand in one room")) + } + + async fn call_result(table: &PlayTable, slot: usize) -> String { + let stored = table.store.lock().await; + let turn = stored.current().unwrap(); + turn.calls + .iter() + .find(|call| call.round == 0 && call.slot == slot) + .and_then(|call| call.result.clone()) + .unwrap() + } + + /// `react` with no `subjects` reacts the player's room and no one else: the + /// two Personas standing with the player get sections; the one in the cellar + /// does not. Mutation: deriving every subject instead of `co_located`. + #[tokio::test] + async fn react_with_no_subjects_reacts_the_room() { + let fixture = play_world(Some("Mara"), "player-react-room").await; + let commons = commons_of(&fixture.world.snapshot().await.unwrap()); + declare_standing(&fixture.world, "borin", "Borin", "person", "narrative_persona", &commons).await; + let cellar = declare_cellar(&fixture.world).await; + declare_standing(&fixture.world, "cass", "Cass", "person", "narrative_persona", &cellar).await; + let snapshot = fixture.world.snapshot().await.unwrap(); + let (mara, borin, cass) = ( + subject_by_label(&snapshot, "Mara"), + subject_by_label(&snapshot, "Borin"), + subject_by_label(&snapshot, "Cass"), + ); + let reply = format!( + "=== {}: Mara ===\nMara tightens her grip on the ledger.\n\n=== {}: Borin ===\nSilent.\n", + handle_for(mara), + handle_for(borin) + ); + let directory = tempfile::tempdir().unwrap(); + let (table, port) = react_table( + &fixture, + vec![output("gestalt", vec![text_event(&reply)]), output("narrate", vec![text_event("Quiet.")])], + vec![react_then_end(serde_json::json!({}))], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1301), "I slam the door.".into()).await.unwrap(); + + let prompt = gestalt_prompt(&port).expect("the room made one Gestalt call"); + assert!(prompt.contains(&format!("=== {}: Mara ===", handle_for(mara))), "{prompt}"); + assert!(prompt.contains(&format!("=== {}: Borin ===", handle_for(borin))), "{prompt}"); + assert!(!prompt.contains(&handle_for(cass)), "the cellar's Persona is not in the room: {prompt}"); + let result = call_result(&table, 0).await; + assert!(result.contains("Mara (draft") && result.contains("tightens her grip"), "{result}"); + assert!(result.contains("Borin stayed silent"), "{result}"); + let stored = table.store.lock().await; + assert_eq!(stored.current().unwrap().persona_turns.len(), 2); + } + + /// Two Personas with one label each get their own section and their own + /// draft, because the split keys on the handle. Mutation: splitting on the + /// label. + #[tokio::test] + async fn two_onlookers_with_the_same_label_each_get_their_own_draft() { + let fixture = play_world(Some("Guard"), "player-react-twins").await; + let commons = commons_of(&fixture.world.snapshot().await.unwrap()); + declare_standing(&fixture.world, "guard2", "Guard", "person", "narrative_persona", &commons).await; + let snapshot = fixture.world.snapshot().await.unwrap(); + let guards: Vec = snapshot.co_located(player_id(&snapshot)); + assert_eq!(guards.len(), 2); + let reply = format!( + "=== {}: Guard ===\nThe first guard shifts his spear.\n=== {}: Guard ===\nThe second guard laughs aloud.\n", + handle_for(guards[0]), + handle_for(guards[1]) + ); + let directory = tempfile::tempdir().unwrap(); + let (table, _port) = react_table( + &fixture, + vec![output("gestalt", vec![text_event(&reply)]), output("narrate", vec![text_event("Quiet.")])], + vec![react_then_end(serde_json::json!({}))], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1302), "Hello.".into()).await.unwrap(); + let stored = table.store.lock().await; + let turns = &stored.current().unwrap().persona_turns; + let prose = |id: SubjectId| turns.iter().find(|(who, _)| *who == id).unwrap().1.source_prose().to_owned(); + assert_eq!(prose(guards[0]), "The first guard shifts his spear."); + assert_eq!(prose(guards[1]), "The second guard laughs aloud."); + } + + /// A list that names one subject twice is refused rather than split on an + /// ambiguous header. + #[tokio::test] + async fn a_gestalt_round_refuses_a_duplicate_subject() { + let fixture = play_world(Some("Mara"), "player-gestalt-dup").await; + let snapshot = fixture.world.snapshot().await.unwrap(); + let mara = persona_id(&snapshot); + let opportunity = snapshot + .opportunities + .iter() + .find(|opportunity| opportunity.scope.subject_id == mara) + .cloned() + .unwrap(); + let personas = PersonaLane::new( + ControllerPort::new(fixture.world.clone()), + ScriptedPort::new(vec![]), + "gpt-5.6-sol".into(), + "gpt-5.6-sol".into(), + ) + .unwrap(); + let error = personas.gestalt(CommandId::new(), &[opportunity.clone(), opportunity]).await.unwrap_err(); + assert!(matches!(error, ghostlight::ControllerError::DuplicateGestaltHandle { .. }), "{error:?}"); + } + + /// An institution run by an operational agent stands in the room: the call + /// still runs the Personas, and the result names it as routed. Mutation: + /// sending every co-located subject into the Gestalt call. + #[tokio::test] + async fn a_non_persona_subject_in_the_room_is_routed_not_run() { + let fixture = play_world(Some("Mara"), "player-react-routed").await; + let commons = commons_of(&fixture.world.snapshot().await.unwrap()); + declare_standing(&fixture.world, "guild", "Weavers Guild", "institution", "operational_agent", &commons).await; + let snapshot = fixture.world.snapshot().await.unwrap(); + let mara = persona_id(&snapshot); + let reply = format!("=== {}: Mara ===\nMara eyes the guild's banner.\n", handle_for(mara)); + let directory = tempfile::tempdir().unwrap(); + let (table, port) = react_table( + &fixture, + vec![output("gestalt", vec![text_event(&reply)]), output("narrate", vec![text_event("Quiet.")])], + vec![react_then_end(serde_json::json!({}))], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1303), "Hello.".into()).await.unwrap(); + let result = call_result(&table, 0).await; + assert!(result.contains("Mara (draft") && result.contains("eyes the guild's banner"), "{result}"); + assert!(result.contains("Weavers Guild is not a Persona"), "{result}"); + let prompt = gestalt_prompt(&port).unwrap(); + assert!(!prompt.contains("Weavers Guild ==="), "{prompt}"); + } + + /// A room whose only onlooker is not a Persona makes no Gestalt call. + #[tokio::test] + async fn a_room_with_no_persona_onlookers_makes_no_call() { + let fixture = play_world(None, "player-react-no-persona").await; + let commons = commons_of(&fixture.world.snapshot().await.unwrap()); + declare_standing(&fixture.world, "guild", "Weavers Guild", "institution", "operational_agent", &commons).await; + let directory = tempfile::tempdir().unwrap(); + let (table, port) = react_table( + &fixture, + vec![output("narrate", vec![text_event("Quiet.")])], + vec![react_then_end(serde_json::json!({}))], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1304), "Hello.".into()).await.unwrap(); + assert!(gestalt_prompt(&port).is_none()); + assert!(call_result(&table, 0).await.contains("Weavers Guild is not a Persona")); + } + + /// A subject dispatched earlier in the turn is absent from the derived room. + #[tokio::test] + async fn dispatched_subjects_are_not_re_reacted() { + let fixture = play_world(Some("Mara"), "player-react-after-dispatch").await; + let commons = commons_of(&fixture.world.snapshot().await.unwrap()); + declare_standing(&fixture.world, "borin", "Borin", "person", "narrative_persona", &commons).await; + let snapshot = fixture.world.snapshot().await.unwrap(); + let (mara, borin) = (subject_by_label(&snapshot, "Mara"), subject_by_label(&snapshot, "Borin")); + let reply = format!("=== {}: Borin ===\nBorin grunts.\n", handle_for(borin)); + let round = output( + "r0", + vec![ + call_event("c0", DISPATCH_TOOL, serde_json::json!({"subjects": [subject_id_text(&snapshot, mara)]})), + call_event("c1", REACT_TOOL, serde_json::json!({})), + call_event("c2", END_TURN_TOOL, serde_json::json!({})), + ], + ); + let directory = tempfile::tempdir().unwrap(); + let (table, port) = react_table( + &fixture, + vec![ + output("proj-mara", vec![text_event("Mara considers.")]), + output("persona-mara", vec![text_event("Mara nods once.")]), + output("gestalt", vec![text_event(&reply)]), + output("narrate", vec![text_event("Quiet.")]), + ], + vec![round], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1305), "Mara, a word.".into()).await.unwrap(); + let prompt = gestalt_prompt(&port).unwrap(); + assert!(prompt.contains(&format!("=== {}: Borin ===", handle_for(borin))), "{prompt}"); + assert!(!prompt.contains(&format!("=== {}:", handle_for(mara))), "{prompt}"); + } + + /// A crash after react's body is recorded resumes with the derived list + /// even though someone walked into the room meanwhile. + #[tokio::test] + async fn a_resumed_react_keeps_the_room_it_derived() { + let fixture = play_world(Some("Mara"), "player-react-resume").await; + let before = fixture.world.snapshot().await.unwrap(); + let mara = persona_id(&before); + let opening = format!("{}\n\nThe player writes:\n{}\n", table_view(&before), "Hello."); + // Borin walks in after the crash and before the resume. + let commons = commons_of(&before); + declare_standing(&fixture.world, "borin", "Borin", "person", "narrative_persona", &commons).await; + let borin = subject_by_label(&fixture.world.snapshot().await.unwrap(), "Borin"); + let turn_id = test_turn_id(1306); + let crashed = PlayTurn { + turn_id: turn_id.clone(), + applied_keys: Vec::new(), + opening_prompt: opening, + player_prose: vec!["Hello.".into()], + rounds: vec![react_then_end(serde_json::json!({}))], + calls: vec![CallRecord { + call_id: "c0".into(), + round: 0, + slot: 0, + body: Some(RecordedCall::Dispatch(vec![mara])), + result: None, + }], + persona_turns: Vec::new(), + question: None, + question_token: None, + refusal: None, + narration: None, + fault: None, + state: PlayTurnState::Running, + }; + let directory = tempfile::tempdir().unwrap(); + let store_path = directory.path().join("play-turn-v1.cc"); + { + let mut store = PlayTurnStore::open(&store_path).unwrap(); + store.open_new_turn(crashed).unwrap(); + } + let reply = format!("=== {}: Mara ===\nMara glances up.\n", handle_for(mara)); + let (table, port) = react_table( + &fixture, + vec![output("gestalt", vec![text_event(&reply)]), output("narrate", vec![text_event("Quiet.")])], + vec![], + &store_path, + ); + table.run(&fixture.principal, turn_id, String::new().into()).await.unwrap(); + let prompt = gestalt_prompt(&port).unwrap(); + assert!(prompt.contains(&format!("=== {}: Mara ===", handle_for(mara))), "{prompt}"); + assert!(!prompt.contains(&format!("=== {}:", handle_for(borin))), "{prompt}"); + } + + + /// Naming subjects reacts exactly those, whoever else stands in the room. + /// Mutation: `react_omits_subjects` returning true. + #[tokio::test] + async fn react_with_named_subjects_reacts_only_them() { + let fixture = play_world(Some("Mara"), "player-react-named").await; + let commons = commons_of(&fixture.world.snapshot().await.unwrap()); + declare_standing(&fixture.world, "borin", "Borin", "person", "narrative_persona", &commons).await; + let snapshot = fixture.world.snapshot().await.unwrap(); + let (mara, borin) = (subject_by_label(&snapshot, "Mara"), subject_by_label(&snapshot, "Borin")); + let reply = format!("=== {}: Mara ===\nMara nods.\n", handle_for(mara)); + let directory = tempfile::tempdir().unwrap(); + let (table, port) = react_table( + &fixture, + vec![output("gestalt", vec![text_event(&reply)]), output("narrate", vec![text_event("Quiet.")])], + vec![react_then_end(serde_json::json!({"subjects": [subject_id_text(&snapshot, mara)]}))], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1307), "Hello.".into()).await.unwrap(); + let prompt = gestalt_prompt(&port).unwrap(); + assert!(!prompt.contains(&handle_for(borin)), "{prompt}"); + } + + /// `dispatch` never derives a room: with no `subjects` it is refused, as + /// before. Mutation: deriving for any tool. + #[tokio::test] + async fn dispatch_without_subjects_is_still_refused() { + let fixture = play_world(Some("Mara"), "player-dispatch-omits").await; + let round = output( + "r0", + vec![ + call_event("c0", DISPATCH_TOOL, serde_json::json!({})), + call_event("c1", END_TURN_TOOL, serde_json::json!({})), + ], + ); + let directory = tempfile::tempdir().unwrap(); + let (table, _port) = react_table( + &fixture, + vec![output("narrate", vec![text_event("Quiet.")])], + vec![round], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1308), "Hello.".into()).await.unwrap(); + let result = call_result(&table, 0).await; + assert!(result.contains("no `subjects` key"), "{result}"); + let stored = table.store.lock().await; + assert!(stored.current().unwrap().persona_turns.is_empty()); + } + + /// With nobody else present, react says so; an explicit empty dispatch does + /// not claim a room. Mutations on the empty-result guard. + #[tokio::test] + async fn react_in_an_empty_room_says_so() { + let fixture = play_world(None, "player-react-empty").await; + let round = output( + "r0", + vec![ + call_event("c0", REACT_TOOL, serde_json::json!({})), + call_event("c1", DISPATCH_TOOL, serde_json::json!({"subjects": []})), + call_event("c2", END_TURN_TOOL, serde_json::json!({})), + ], + ); + let directory = tempfile::tempdir().unwrap(); + let (table, port) = react_table( + &fixture, + vec![output("narrate", vec![text_event("Quiet.")])], + vec![round], + &directory.path().join("play-turn-v1.cc"), + ); + table.run(&fixture.principal, test_turn_id(1309), "Hello.".into()).await.unwrap(); + assert!(call_result(&table, 0).await.contains("no one else is in the room")); + assert!(!call_result(&table, 1).await.contains("no one else")); + assert!(gestalt_prompt(&port).is_none()); + } + /// `co_located` is the owner's room query: live non-Human subjects sharing + /// the subject's place, never the subject itself, ascending. + #[tokio::test] + async fn co_located_lists_the_live_non_human_subjects_in_the_same_place() { + let fixture = play_world(Some("Mara"), "player-co-located").await; + let commons = commons_of(&fixture.world.snapshot().await.unwrap()); + declare_standing(&fixture.world, "borin", "Borin", "person", "narrative_persona", &commons).await; + let cellar = declare_cellar(&fixture.world).await; + declare_standing(&fixture.world, "cass", "Cass", "person", "narrative_persona", &cellar).await; + let snapshot = fixture.world.snapshot().await.unwrap(); + let player = player_id(&snapshot); + let mut want = vec![subject_by_label(&snapshot, "Mara"), subject_by_label(&snapshot, "Borin")]; + want.sort(); + assert_eq!(snapshot.co_located(player), want); + assert!(!snapshot.co_located(subject_by_label(&snapshot, "Cass")).contains(&player)); + } + /// PA.f124: `execute_dispatch`'s own summaries print a subject through /// the library's `id_text` — the same printer `table_view` and /// `dispatch`'s own matching use — never `{subject:?}`'s raw diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index edabb7a..2444c1a 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -27,7 +27,7 @@ use crate::{ EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, Resolution, RoleBinding, ScopeComponents, ScopeDigest, SeedPort, Statement, SubjectId, SubjectSnapshot, SubmitReceipt, - Target, TickIndex, WorldMailbox, WorldSnapshot, + Target, TickIndex, WorldMailbox, WorldSnapshot, handle_for, }; use async_trait::async_trait; use chrono::Utc; @@ -3131,6 +3131,8 @@ pub enum ControllerError { NoOpportunity { expected: ControllerMode }, #[error("subject has more than one current decision opportunity")] AmbiguousOpportunity, + #[error("a Gestalt round names handle {handle} twice (the same subject listed twice, or two subjects sharing a handle)")] + DuplicateGestaltHandle { handle: String }, #[error("opportunity does not match this exact controller command")] OpportunityMismatch, #[error("the subject's opportunity on this scope moved to a new digest")] @@ -4820,13 +4822,21 @@ impl PersonaLane { } selected.push(self.select(opportunity).await?); } + let mut handles = std::collections::BTreeSet::new(); + for person in &selected { + let handle = handle_for(person.subject.id); + if !handles.insert(handle.clone()) { + return Err(ControllerError::DuplicateGestaltHandle { handle }); + } + } let Some(first) = selected.first() else { return Ok(Vec::new()); }; let mut blocks = String::new(); for person in &selected { blocks.push_str(&format!( - "=== {label} ===\nWho you are:\n{identity}\n\nWhere you stand:\n{context}\n\nWhat you have seen and heard (rows marked new are the most recent):\n{stimulus}\n\n", + "=== {handle}: {label} ===\nWho you are:\n{identity}\n\nWhere you stand:\n{context}\n\nWhat you have seen and heard (rows marked new are the most recent):\n{stimulus}\n\n", + handle = handle_for(person.subject.id), label = person.subject.label, identity = person.persona_identity(), context = person.projector_context()?, @@ -4834,7 +4844,7 @@ impl PersonaLane { )); } let prompt = format!( - "Several people stand in one room as something just happened. Below, each person's own view of the moment, and nothing of what anyone else thinks. For each person in turn, be that person and respond only from what their own view establishes: they may speak, react with a look or a movement, act, or stay silent. Do not give anyone a temperament, history or turn of phrase their view did not give them; do not let one person know another's mind; do not announce an outside consequence as already accomplished.\n\nVoice and setting guidance:\n{guidance}\n\n{blocks}Write one section per person, in the order above. Begin each section with its header line exactly as written above (`=== name ===`), then that person's natural response in first-person prose, at most {budget} words each; for a person who does nothing, write only `Silent.` under their header. Return only the sections.", + "Several people stand in one room as something just happened. Below, each person's own view of the moment, and nothing of what anyone else thinks. For each person in turn, be that person and respond only from what their own view establishes: they may speak, react with a look or a movement, act, or stay silent. Do not give anyone a temperament, history or turn of phrase their view did not give them; do not let one person know another's mind; do not announce an outside consequence as already accomplished.\n\nVoice and setting guidance:\n{guidance}\n\n{blocks}Write one section per person, in the order above. Begin each section with its header line exactly as written above (`=== handle: name ===`), then that person's natural response in first-person prose, at most {budget} words each; for a person who does nothing, write only `Silent.` under their header. Return only the sections.", guidance = first.snapshot.guidance(), budget = PERSONA_WORD_BUDGET, ); @@ -4850,14 +4860,15 @@ impl PersonaLane { let (reply, receipt) = output.prose_only(InferencePurpose::Persona)?; let headers: Vec = selected .iter() - .map(|person| format!("=== {} ===", person.subject.label)) + .map(|person| format!("=== {}:", handle_for(person.subject.id))) .collect(); let mut turns = Vec::with_capacity(selected.len()); for (index, person) in selected.iter().enumerate() { let prose = reply .find(&headers[index]) .map(|at| { - let start = at + headers[index].len(); + let after = at + headers[index].len(); + let start = reply[after..].find('\n').map_or(reply.len(), |rel| after + rel); let end = headers .iter() .filter_map(|other| reply[start..].find(other.as_str()).map(|rel| start + rel)) @@ -16705,6 +16716,108 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur task.await.unwrap(); } + /// The owner's room query over a real world: Iris and Mara share the + /// commons, Otho stands alone in the vault. + #[tokio::test] + async fn co_located_lists_the_others_standing_in_the_same_place() { + let (_directory, mailbox, _task, _stale, _mara, _a, _b) = persona_lane_world().await; + let snapshot = mailbox.snapshot().await.unwrap(); + let by = |prefix: &str| { + snapshot.subjects.iter().find(|subject| subject.label.starts_with(prefix)).unwrap().id + }; + let (iris, mara, otho) = (by("Iris"), by("Mara"), by("Otho")); + assert_eq!(snapshot.co_located(iris), vec![mara]); + assert_eq!(snapshot.co_located(mara), vec![iris]); + assert!(snapshot.co_located(otho).is_empty(), "Otho is alone in the vault"); + let mut room = vec![iris, mara]; + room.sort(); + assert_eq!(room.iter().filter(|id| snapshot.co_located(**id).len() == 1).count(), 2); + } + + /// The Human is the player, not an onlooker: no human subject is ever listed. + #[tokio::test] + async fn co_located_never_lists_a_human_or_the_subject_itself() { + let (_directory, _mailbox, _task, snapshot, human, _operational, _heard, _secret) = + mixed_controller_world().await; + let room = snapshot.co_located(human); + assert!(!room.contains(&human)); + for id in &room { + let mode = snapshot.subjects.iter().find(|subject| subject.id == *id).unwrap().controller_mode; + assert_ne!(mode, Some(ControllerMode::Human)); + } + assert!(!room.is_empty(), "the fixture's other subjects share the human's place"); + } + + /// Runs one Gestalt round over the named people of `persona_lane_world`, + /// the scripted reply built from their handles in order. + async fn gestalt_round( + who: &[&str], + reply: impl Fn(&[String]) -> String, + ) -> (Vec, String, Vec) { + let (_directory, mailbox, _task, _stale, _mara, _a, _b) = persona_lane_world().await; + let snapshot = mailbox.snapshot().await.unwrap(); + let ids: Vec = who + .iter() + .map(|prefix| snapshot.subjects.iter().find(|s| s.label.starts_with(prefix)).unwrap().id) + .collect(); + let handles: Vec = ids.iter().map(|id| handle_for(*id)).collect(); + let opportunities: Vec = ids.iter().map(|id| opportunity_for(&snapshot, *id)).collect(); + let capturing = Arc::new(CapturingPort { + prepared: Mutex::new(Vec::new()), + outputs: Mutex::new(vec![output(vec![InferenceEvent::Text(reply(&handles))], "gestalt")]), + }); + let lane = PersonaLane::new( + ControllerPort::new(mailbox.clone()), + capturing.clone(), + "projector-model".into(), + "persona-model".into(), + ) + .unwrap(); + let turns = lane.gestalt(CommandId::new(), &opportunities).await.unwrap(); + let prompt = request_text(&capturing.prepared.lock().unwrap()[0]); + (turns, prompt, ids) + } + + /// Each section is the text between its handle's header line and the next + /// handle's; a header whose label the model rewrote still splits; the prompt + /// names every handle with its label. + #[tokio::test] + async fn gestalt_splits_the_reply_on_handles() { + let (turns, prompt, ids) = gestalt_round(&["Iris", "Mara"], |h| { + format!( + "=== {}: Iris, renamed by the model ===\nIris counts the coins twice.\nShe frowns.\n=== {}: Mara at the rain gate ===\nMara laughs.", + h[0], h[1] + ) + }) + .await; + assert_eq!(turns.len(), 2); + assert_eq!(turns[0].source_prose(), "Iris counts the coins twice.\nShe frowns."); + assert_eq!(turns[1].source_prose(), "Mara laughs."); + assert!(prompt.contains(&format!("=== {}: Iris in the tollhouse ===", handle_for(ids[0]))), "{prompt}"); + assert!(prompt.contains(&format!("=== {}: Mara at the rain gate ===", handle_for(ids[1]))), "{prompt}"); + } + + /// A person the reply leaves out, or who writes nothing, is silent. + #[tokio::test] + async fn gestalt_keeps_silent_for_a_missing_or_empty_section() { + let (turns, _prompt, _ids) = + gestalt_round(&["Iris", "Mara"], |h| format!("=== {}: Iris ===\n\n", h[0])).await; + assert_eq!(turns[0].source_prose(), "Silent."); + assert_eq!(turns[1].source_prose(), "Silent."); + } + + /// The handle is the first 8 hex digits of the id's own text. + #[tokio::test] + async fn handle_for_is_eight_hex_digits_of_the_id() { + let (_directory, mailbox, _task, _stale, mara, _a, _b) = persona_lane_world().await; + let _ = mailbox; + let handle = handle_for(mara); + assert_eq!(handle.len(), 8); + assert!(handle.chars().all(|c| c.is_ascii_hexdigit())); + assert!(crate::id_text(mara).replace('-', "").starts_with(&handle)); + assert_ne!(handle, "xyzzy"); + } + /// Adjacency is a scheduler projection, not a subject view. Two subjects in /// one room are related through the kernel's own containment closure, which /// no union of `SubjectSnapshot`s could produce for a channel, and the diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index 7fc0588..069c021 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -141,7 +141,7 @@ pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding}; pub use table::{ DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call, decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor, - id_text, id_text_matches, table_view, + handle_for, id_text, id_text_matches, table_view, }; pub use vault::{ ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError, @@ -1303,6 +1303,36 @@ impl WorldSnapshot { self.places.iter().find(|place| place.id == position).map(|place| place.label.as_str()) } + /// The live subjects with a controller other than a human's that stand in + /// the same place as `subject`, ascending by id; `subject` itself is never + /// among them. For the owner's own surfaces (the Dungeon's room-level + /// reaction derives its audience here): no controller lane reads it, since + /// one subject must not learn who else stands beside it from a list the + /// kernel built for the table. + pub fn co_located(&self, subject: SubjectId) -> Vec { + let Some(position) = self + .subjects + .iter() + .find(|candidate| candidate.id == subject) + .and_then(|candidate| candidate.position) + else { + return Vec::new(); + }; + let mut present: Vec = self + .subjects + .iter() + .filter(|other| { + other.id != subject + && !other.retired + && other.position == Some(position) + && matches!(other.controller_mode, Some(mode) if mode != ControllerMode::Human) + }) + .map(|other| other.id) + .collect(); + present.sort(); + present + } + /// What every lane reads as the world's guidance: the era line, then the /// owner's brief verbatim, either omitted when empty. Derived on every /// read; no prompt reads `brief` directly. diff --git a/crates/ghostlight/src/table.rs b/crates/ghostlight/src/table.rs index ea013fb..6adf521 100644 --- a/crates/ghostlight/src/table.rs +++ b/crates/ghostlight/src/table.rs @@ -1095,6 +1095,17 @@ pub fn id_text(id: impl std::fmt::Debug) -> String { } } +/// A subject's own short handle: the first 8 hex digits of its id. Actor tool +/// names are `__` and a kind may run to 48 chars, so the full id +/// text would break a common 64-char function-name limit; the Gestalt round's +/// section headers carry the same handle, so a reply splits on a token that +/// names exactly one subject even when two share a label. A collision between +/// two subjects is astronomically unlikely but not impossible; each caller that +/// keys on handles refuses it rather than addressing the wrong subject. +pub fn handle_for(id: crate::SubjectId) -> String { + id_text(id).chars().filter(char::is_ascii_hexdigit).take(8).collect() +} + /// The parser matching `id_text` above (PA.f113): `text` names `id` only /// when it is exactly the bytes `id_text(id)` would print — no brackets, no /// padding, no case folding, because this is plain string equality against