react derives the player's room, keys Gestalt sections by handle, routes non-Persona subjects
WorldSnapshot::co_located is the owner's room query; react with no subjects reacts co_located(player) minus the turn's dispatched subjects, the derived list recorded so a resume keeps it. The Gestalt call's headers carry the unique handle (handle_for moves to the library beside id_text), a duplicate is refused, a non-Persona onlooker is named as routed and not run. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c6df934093
commit
e8b545c518
4 changed files with 471 additions and 34 deletions
|
|
@ -33,7 +33,7 @@ use ghostlight::{
|
||||||
InferenceOutput, InferencePort, InferenceRequest, KernelError, MailboxError, PersonaLane,
|
InferenceOutput, InferencePort, InferenceRequest, KernelError, MailboxError, PersonaLane,
|
||||||
PlayPort, PrincipalCommandIntent, Statement, SubjectId, TickMinutes, VerifiedPrincipalEvidence,
|
PlayPort, PrincipalCommandIntent, Statement, SubjectId, TickMinutes, VerifiedPrincipalEvidence,
|
||||||
WorldMailbox, WorldPatch, WorldSnapshot, actor_tools, authoring_tools, decode_actor_call,
|
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,
|
table_view,
|
||||||
};
|
};
|
||||||
use ghostlight_persona_projection::{PersonaTurn, SourceSpan};
|
use ghostlight_persona_projection::{PersonaTurn, SourceSpan};
|
||||||
|
|
@ -2130,7 +2130,11 @@ impl PlayTable {
|
||||||
let (subjects, refusals) = match recorded {
|
let (subjects, refusals) = match recorded {
|
||||||
Some(RecordedCall::Dispatch(subjects)) => (subjects, Vec::new()),
|
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
|
// PA.f125: this call's own body — which subjects it
|
||||||
// intends to dispatch — is recorded and persisted
|
// intends to dispatch — is recorded and persisted
|
||||||
// before `execute_dispatch` runs any persona turn,
|
// before `execute_dispatch` runs any persona turn,
|
||||||
|
|
@ -2164,7 +2168,11 @@ impl PlayTable {
|
||||||
// refused in the tool result, quoting what was given, never
|
// refused in the tool result, quoting what was given, never
|
||||||
// dropped silently.
|
// dropped silently.
|
||||||
let result = if refusals.is_empty() {
|
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 {
|
} else {
|
||||||
let refusals = refusals.join("; ");
|
let refusals = refusals.join("; ");
|
||||||
if dispatch_summary.is_empty() {
|
if dispatch_summary.is_empty() {
|
||||||
|
|
@ -2646,7 +2654,7 @@ impl PlayTable {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let label = subject_label(&snapshot, *subject);
|
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 {
|
} else {
|
||||||
// PA.f124: printed through the library's own `id_text`,
|
// PA.f124: printed through the library's own `id_text`,
|
||||||
// the same printer `table_view` and `dispatch`'s own
|
// the same printer `table_view` and `dispatch`'s own
|
||||||
|
|
@ -2675,6 +2683,21 @@ impl PlayTable {
|
||||||
return Ok((RoundOutcome::Closed, finished_summary(summary_slots)));
|
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
|
let Some(opportunity) = snapshot
|
||||||
.opportunities
|
.opportunities
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -2770,7 +2793,7 @@ impl PlayTable {
|
||||||
// already generic over every call's recorded `result`,
|
// already generic over every call's recorded `result`,
|
||||||
// so recording the prose here is the whole fix.
|
// so recording the prose here is the whole fix.
|
||||||
let prose = persona_turn.source_prose().to_owned();
|
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));
|
turn.persona_turns.push((entry.subject, persona_turn));
|
||||||
// PA.f123: `execute_dispatch` was the only call kind that
|
// PA.f123: `execute_dispatch` was the only call kind that
|
||||||
// did not persist at its own site — every other tool
|
// 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())
|
.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 `<handle>__<kind>`, 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
|
/// 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
|
/// to its description (PA.f98): `dispatch` takes the id exactly as
|
||||||
/// `table_view` prints it, never the short `<handle>__` prefix these tools'
|
/// `table_view` prints it, never the short `<handle>__` prefix these tools'
|
||||||
|
|
@ -3007,14 +3013,16 @@ draft: it is in the world once you commit it through their own `<handle>__speak`
|
||||||
},
|
},
|
||||||
ToolDefinition {
|
ToolDefinition {
|
||||||
name: REACT_TOOL.into(),
|
name: REACT_TOOL.into(),
|
||||||
description: "The room reacts: one call in which every person you name, together, decides how \
|
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. Use it \
|
they take what just happened, each from their own view, and may speak, show it, act or stay silent. Omit \
|
||||||
for the onlookers when the player speaks or acts in front of others who are not the one addressed, so the \
|
`subjects` to react everyone in the player's room who has not yet had a turn this turn; name people (full \
|
||||||
room is never frozen around a conversation; give the person addressed their own turn with `dispatch`. \
|
ids as table_view prints them in brackets) only to react a chosen few. Use it for the onlookers when the \
|
||||||
Names are full ids as table_view prints them in brackets. Like `dispatch`, what comes back is draft prose \
|
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 `<handle>__speak` tool."
|
for you to commit through each person's own `<handle>__speak` tool."
|
||||||
.into(),
|
.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 {
|
ToolDefinition {
|
||||||
name: ADVANCE_TIME_TOOL.into(),
|
name: ADVANCE_TIME_TOOL.into(),
|
||||||
|
|
@ -3089,6 +3097,44 @@ fn parse_dispatch(arguments: &str, snapshot: &WorldSnapshot) -> (Vec<SubjectId>,
|
||||||
(subjects, refusals)
|
(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::<Value>(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<SubjectId> {
|
||||||
|
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 {
|
fn parse_ask_player(arguments: &str) -> String {
|
||||||
serde_json::from_str::<Value>(arguments)
|
serde_json::from_str::<Value>(arguments)
|
||||||
.ok()
|
.ok()
|
||||||
|
|
@ -6418,6 +6464,345 @@ pub(crate) mod tests {
|
||||||
assert_eq!(turn.persona_turns.len(), 1);
|
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<InferenceOutput>,
|
||||||
|
rounds: Vec<InferenceOutput>,
|
||||||
|
store: &std::path::Path,
|
||||||
|
) -> (PlayTable, Arc<ScriptedPort>) {
|
||||||
|
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<String> {
|
||||||
|
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<SubjectId> = 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}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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
|
/// PA.f124: `execute_dispatch`'s own summaries print a subject through
|
||||||
/// the library's `id_text` — the same printer `table_view` and
|
/// the library's `id_text` — the same printer `table_view` and
|
||||||
/// `dispatch`'s own matching use — never `{subject:?}`'s raw
|
/// `dispatch`'s own matching use — never `{subject:?}`'s raw
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ use crate::{
|
||||||
EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, Magnitude,
|
EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, Magnitude,
|
||||||
MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, Resolution, RoleBinding,
|
MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, Resolution, RoleBinding,
|
||||||
ScopeComponents, ScopeDigest, SeedPort, Statement, SubjectId, SubjectSnapshot, SubmitReceipt,
|
ScopeComponents, ScopeDigest, SeedPort, Statement, SubjectId, SubjectSnapshot, SubmitReceipt,
|
||||||
Target, TickIndex, WorldMailbox, WorldSnapshot,
|
Target, TickIndex, WorldMailbox, WorldSnapshot, handle_for,
|
||||||
};
|
};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
|
@ -3131,6 +3131,8 @@ pub enum ControllerError {
|
||||||
NoOpportunity { expected: ControllerMode },
|
NoOpportunity { expected: ControllerMode },
|
||||||
#[error("subject has more than one current decision opportunity")]
|
#[error("subject has more than one current decision opportunity")]
|
||||||
AmbiguousOpportunity,
|
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")]
|
#[error("opportunity does not match this exact controller command")]
|
||||||
OpportunityMismatch,
|
OpportunityMismatch,
|
||||||
#[error("the subject's opportunity on this scope moved to a new digest")]
|
#[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?);
|
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 {
|
let Some(first) = selected.first() else {
|
||||||
return Ok(Vec::new());
|
return Ok(Vec::new());
|
||||||
};
|
};
|
||||||
let mut blocks = String::new();
|
let mut blocks = String::new();
|
||||||
for person in &selected {
|
for person in &selected {
|
||||||
blocks.push_str(&format!(
|
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,
|
label = person.subject.label,
|
||||||
identity = person.persona_identity(),
|
identity = person.persona_identity(),
|
||||||
context = person.projector_context()?,
|
context = person.projector_context()?,
|
||||||
|
|
@ -4834,7 +4844,7 @@ impl PersonaLane {
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let prompt = format!(
|
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(),
|
guidance = first.snapshot.guidance(),
|
||||||
budget = PERSONA_WORD_BUDGET,
|
budget = PERSONA_WORD_BUDGET,
|
||||||
);
|
);
|
||||||
|
|
@ -4850,14 +4860,15 @@ impl PersonaLane {
|
||||||
let (reply, receipt) = output.prose_only(InferencePurpose::Persona)?;
|
let (reply, receipt) = output.prose_only(InferencePurpose::Persona)?;
|
||||||
let headers: Vec<String> = selected
|
let headers: Vec<String> = selected
|
||||||
.iter()
|
.iter()
|
||||||
.map(|person| format!("=== {} ===", person.subject.label))
|
.map(|person| format!("=== {}:", handle_for(person.subject.id)))
|
||||||
.collect();
|
.collect();
|
||||||
let mut turns = Vec::with_capacity(selected.len());
|
let mut turns = Vec::with_capacity(selected.len());
|
||||||
for (index, person) in selected.iter().enumerate() {
|
for (index, person) in selected.iter().enumerate() {
|
||||||
let prose = reply
|
let prose = reply
|
||||||
.find(&headers[index])
|
.find(&headers[index])
|
||||||
.map(|at| {
|
.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
|
let end = headers
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|other| reply[start..].find(other.as_str()).map(|rel| start + rel))
|
.filter_map(|other| reply[start..].find(other.as_str()).map(|rel| start + rel))
|
||||||
|
|
|
||||||
|
|
@ -141,7 +141,7 @@ pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding};
|
||||||
pub use table::{
|
pub use table::{
|
||||||
DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call,
|
DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call,
|
||||||
decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor,
|
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::{
|
pub use vault::{
|
||||||
ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError,
|
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())
|
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<SubjectId> {
|
||||||
|
let Some(position) = self
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| candidate.id == subject)
|
||||||
|
.and_then(|candidate| candidate.position)
|
||||||
|
else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut present: Vec<SubjectId> = 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
|
/// 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
|
/// owner's brief verbatim, either omitted when empty. Derived on every
|
||||||
/// read; no prompt reads `brief` directly.
|
/// read; no prompt reads `brief` directly.
|
||||||
|
|
|
||||||
|
|
@ -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 `<handle>__<kind>` 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
|
/// 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
|
/// 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
|
/// padding, no case folding, because this is plain string equality against
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue