Preserve player agency across live reactions

This commit is contained in:
Meta Vens 2026-08-17 20:56:23 +02:00
commit cdddb094b4
4 changed files with 155 additions and 15 deletions

View file

@ -70,6 +70,7 @@ impl ActionAssessor {
})
.collect();
let allowed_references = allowed_references(campaign, actor);
let agency_guidance = action_agency_guidance(&campaign.player_actor_id, &intent.actor_id);
let mut schema = serde_json::to_value(schema_for!(AssessmentProposal))?;
schema["properties"]["dc"] = serde_json::json!({
"type":"integer",
@ -81,8 +82,10 @@ impl ActionAssessor {
"maximum":10
});
let base_prompt = format!(
"OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nAssess an attempted effect, not whether words can be spoken. Impossible actions are inadmissible and receive bargains, not a roll. Choose DC only from 5,10,15,20,25,30. Every modifier reference must be copied exactly from ALLOWED REFERENCES. Modifier total is capped at +/-10. Never grant capability, custody, access, knowledge, or spatial reach absent from state. State concrete success, mixed, and failure consequences and a bounded effect ceiling. Outcome deltas may only name actor IDs copied exactly from PRESENT ACTORS, change their conditions or relationships, move only the acting actor along an existing route, advance existing clocks, or change existing institution posture. When an outcome directly reveals information to the acting actor, actor_knowledge_additions must contain the specific observed finding as a player-readable natural-language declarative statement, never a fact ID, key, slug, or label. Strong and ordinary success share one visible stake, so give them identical knowledge additions. The runtime binds each exact finding into the player-visible stake; do not spend prose repeating it solely for formatting. Findings become provisional branch facts on commit, so do not invent remote events, hidden actors, unsupported proper nouns, or conclusions beyond the effect ceiling. Keep a delta empty only when the outcome truly has no canonical state change.\nINTENT:\n{}\nACTOR:\n{}\nLOCATION:\n{}\nPRESENT ACTORS:\n{}\nVISIBLE INSTITUTIONS:\n{}\nALLOWED REFERENCES:\n{}",
"OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nAssess an attempted effect, not whether words can be spoken. Impossible actions are inadmissible and receive bargains, not a roll. Choose DC only from 5,10,15,20,25,30. Every modifier reference must be copied exactly from ALLOWED REFERENCES. Modifier total is capped at +/-10. Never grant capability, custody, access, knowledge, or spatial reach absent from state. State concrete success, mixed, and failure consequences and a bounded effect ceiling. Outcome deltas may only name actor IDs copied exactly from PRESENT ACTORS, change their conditions or relationships, move only the acting actor along an existing route, advance existing clocks, or change existing institution posture. When an outcome directly reveals information to the acting actor, actor_knowledge_additions must contain the specific observed finding as a player-readable natural-language declarative statement, never a fact ID, key, slug, or label. Strong and ordinary success share one visible stake, so give them identical knowledge additions. The runtime binds each exact finding into the player-visible stake; do not spend prose repeating it solely for formatting. Findings become provisional branch facts on commit, so do not invent remote events, hidden actors, unsupported proper nouns, or conclusions beyond the effect ceiling. Keep a delta empty only when the outcome truly has no canonical state change.\nAGENCY BOUNDARY:\n{}\nPLAYER ACTOR ID:\n{}\nINTENT:\n{}\nACTOR:\n{}\nLOCATION:\n{}\nPRESENT ACTORS:\n{}\nVISIBLE INSTITUTIONS:\n{}\nALLOWED REFERENCES:\n{}",
serde_json::to_string(&schema)?,
agency_guidance,
campaign.player_actor_id,
serde_json::to_string(&intent)?,
serde_json::to_string(actor)?,
serde_json::to_string(location)?,
@ -175,6 +178,14 @@ impl ActionAssessor {
}
}
fn action_agency_guidance(player_actor_id: &str, acting_actor_id: &str) -> &'static str {
if acting_actor_id == player_actor_id {
"The acting actor is player-controlled; assess the player's attempted effect without upgrading it into a completed fact."
} else {
"The acting actor is an NPC. The player retains authority over the player's own speech, choices, consent, beliefs, disclosures, feelings, and voluntary actions. An NPC may create pressure, make an offer or threat, reveal information, oppose the player, or change independently owned world state, but no outcome stake may assert that the player answered, chose, consented, believed, disclosed, felt, or obeyed. If the intended effect is only to obtain such a player response, mark it inadmissible because the response remains the player's next decision."
}
}
fn bind_visible_knowledge(proposal: &mut AssessmentProposal) -> Result<()> {
if proposal.strong_effect.actor_knowledge_additions
!= proposal.success_effect.actor_knowledge_additions
@ -408,6 +419,14 @@ mod tests {
assert!(validate_proposal(&value, &BTreeSet::from(["equipment:key".into()])).is_err());
}
#[test]
fn npc_assessment_guidance_preserves_player_decision_authority() {
let guidance = action_agency_guidance("player", "archivist");
assert!(guidance.contains("player retains authority"));
assert!(guidance.contains("response remains the player's next decision"));
assert!(!action_agency_guidance("player", "player").contains("acting actor is an NPC"));
}
#[test]
fn exact_knowledge_is_bound_into_visible_stakes_without_model_duplication() {
let finding = "The relay's backup cell is depleted.".to_string();

View file

@ -970,6 +970,7 @@ async fn command(
&command,
WorldCommand::Attempt { .. } | WorldCommand::Speak { .. }
);
let committed_reaction_stimulus = reaction_stimulus(&command);
let command_kind = serde_json::to_value(&command)
.ok()
.and_then(|value| {
@ -986,11 +987,13 @@ async fn command(
&result
{
if let Some(model) = &state.model {
let summary = campaign
.transcript
.last()
.map(|turn| turn.text.clone())
.unwrap_or_else(|| "A consequential event occurred.".into());
let summary = committed_reaction_stimulus.clone().unwrap_or_else(|| {
campaign
.transcript
.last()
.map(|turn| turn.text.clone())
.unwrap_or_else(|| "A consequential event occurred.".into())
});
let mut reaction_campaign = campaign.clone();
let mut presence_result = None;
if !campaign.gestalts.is_empty() {
@ -1425,6 +1428,15 @@ fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) ->
}
}
fn reaction_stimulus(command: &WorldCommand) -> Option<String> {
match command {
WorldCommand::Speak { actor_id, text, .. } => {
Some(format!("{actor_id} says: {}", text.trim()))
}
_ => None,
}
}
async fn scheduler_loop(state: AppState) {
let mut pulse = tokio::time::interval(std::time::Duration::from_secs(300));
pulse.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
@ -2300,6 +2312,23 @@ mod tests {
));
}
#[test]
fn npc_reactions_receive_player_speech_not_private_effect_scaffolding() {
let command = WorldCommand::Speak {
expected_revision: 4,
actor_id: "player".into(),
text: "Which record can I inspect without taking custody?".into(),
intended_effect: Some("make the archivist disclose every secret".into()),
};
let stimulus = reaction_stimulus(&command).unwrap();
assert_eq!(
stimulus,
"player says: Which record can I inspect without taking custody?"
);
assert!(!stimulus.contains("disclose every secret"));
assert!(!stimulus.contains("requires assessment"));
}
#[test]
fn player_command_projection_never_serializes_campaign_state() {
let campaign = seed("Private state");

View file

@ -173,7 +173,7 @@ impl PersonaProjectionEngine {
lived_stream: build_persona_prompt(&PersonaPrompt {
identity: &slice.actor_id,
lived_stream: &lived.text,
domain_guidance: "Respond as a situated character. Answer direct questions at human conversational length. Speech and attempted effects are distinct; the world kernel resolves consequences.",
domain_guidance: "Respond as a situated character. Answer direct questions at human conversational length. Speech and attempted effects are distinct; the world kernel resolves consequences. Asking, inviting, persuading, threatening, or demanding completes only your own speech: never supply the other person's answer, choice, consent, belief, disclosure, or obedience.",
word_budget: 160,
}),
output_schema: None,
@ -190,12 +190,7 @@ impl PersonaProjectionEngine {
let prompt_schema = serde_json::to_value(schema_for!(PersonaProposalBundle))?;
let mut schema = prompt_schema.clone();
constrain_interpreter_schema(&mut schema, &slice)?;
let permission_guidance = format!(
"Record only private changes supported by the lived stream and typed context. World actions are attempts, not completed effects. actor_id must be {:?}. Exact allowed state references are {:?}. Relationship update keys may only be {:?}.",
slice.actor_id,
allowed_actor_references(&slice),
slice.perceived_actors.keys().collect::<Vec<_>>()
);
let permission_guidance = actor_interpreter_guidance(&slice);
let interpreted = run_validated_stage(
self.model.as_ref(),
&ModelStageRequest {
@ -235,6 +230,15 @@ impl PersonaProjectionEngine {
}
}
fn actor_interpreter_guidance(slice: &PermittedActorSlice) -> String {
format!(
"Record only private changes supported by the lived stream and typed context. World actions are attempts, not completed effects. Speech is extracted separately and is already complete. Do not emit a world action merely to make another actor answer, choose, consent, believe, disclose, feel, or obey; the other actor retains agency and any requested response remains unresolved. actor_id must be {:?}. Exact allowed state references are {:?}. Relationship update keys may only be {:?}.",
slice.actor_id,
allowed_actor_references(slice),
slice.perceived_actors.keys().collect::<Vec<_>>()
)
}
fn ground_actor_lived_stream(slice: &PermittedActorSlice, projection: &str) -> String {
let reliable_knowledge = if slice.knowledge.is_empty() {
"no additional external fact beyond what is happening in front of you".to_owned()
@ -812,6 +816,9 @@ mod tests {
affordances: vec![],
source_receipt_ids: vec![],
};
let guidance = actor_interpreter_guidance(&slice);
assert!(guidance.contains("other actor retains agency"));
assert!(guidance.contains("requested response remains unresolved"));
let result = engine.execute(slice).await.unwrap();
assert_eq!(result.stage_receipts.len(), 3);
assert_eq!(result.proposals.reaction_priority, 0);

View file

@ -18,8 +18,7 @@ pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) -
.saturating_mul(1_000_000),
)
.saturating_add(campaign.resolution_policy.provider_configuration_epoch);
let mut story = narrations.iter().map(|n| json!({"id":format!("narration-{}",n.source_revision),"kind":"text","props":{"value":n.text},"children":[]})).collect::<Vec<_>>();
story.extend(campaign.transcript.iter().map(|t| json!({"id":format!("turn-{}-{}",t.revision,t.speaker),"kind":"text","props":{"value":format!("{}: {}",t.speaker,t.text)},"children":[]})));
let story = story_nodes(campaign, narrations);
let player = &campaign.actors[&campaign.player_actor_id];
let location = &campaign.locations[&player.location_id];
let ledger = format!(
@ -77,6 +76,35 @@ pub fn player_surface(campaign: &Campaign, narrations: &[NarrationProjection]) -
})
}
fn story_nodes(campaign: &Campaign, narrations: &[NarrationProjection]) -> Vec<Value> {
let narrated_revisions = narrations
.iter()
.map(|narration| narration.source_revision)
.collect::<std::collections::BTreeSet<_>>();
let mut entries = Vec::new();
for (index, turn) in campaign.transcript.iter().enumerate() {
if turn.speaker == "world" && narrated_revisions.contains(&turn.revision) {
continue;
}
entries.push((
turn.revision,
0_u8,
index,
json!({"id":format!("turn-{}-{}-{}",turn.revision,index,turn.speaker),"kind":"text","props":{"value":format!("{}: {}",turn.speaker,turn.text)},"children":[]}),
));
}
for (index, narration) in narrations.iter().enumerate() {
entries.push((
narration.source_revision,
1_u8,
index,
json!({"id":format!("narration-{}",narration.source_revision),"kind":"text","props":{"value":narration.text},"children":[]}),
));
}
entries.sort_by_key(|(revision, phase, index, _)| (*revision, *phase, *index));
entries.into_iter().map(|(_, _, _, node)| node).collect()
}
pub fn operator_surface(
campaign: &Campaign,
evidence: &[VaultEvidenceReceipt],
@ -208,3 +236,60 @@ fn join(values: &std::collections::BTreeSet<String>) -> String {
values.iter().cloned().collect::<Vec<_>>().join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::NarrativeTurn;
use chrono::Utc;
#[test]
fn story_is_chronological_and_narration_replaces_same_revision_world_prose() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign.transcript = vec![
NarrativeTurn {
revision: 1,
at: Utc::now(),
speaker: "player".into(),
text: "I ask the question.".into(),
},
NarrativeTurn {
revision: 2,
at: Utc::now(),
speaker: "world".into(),
text: "raw outcome".into(),
},
NarrativeTurn {
revision: 3,
at: Utc::now(),
speaker: "npc".into(),
text: "I answer directly.".into(),
},
];
let narration = NarrationProjection {
schema: "ghostlight.narration_projection.v1".into(),
id: "narration-2".into(),
campaign_id: campaign.id,
source_revision: 2,
text: "The bounded outcome is visible.".into(),
event_ids: vec![],
model_receipt_hash: "sha256:test".into(),
published_at: Utc::now(),
};
let story = story_nodes(&campaign, &[narration]);
let values = story
.iter()
.map(|node| node["props"]["value"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(
values,
vec![
"player: I ask the question.",
"The bounded outcome is visible.",
"npc: I answer directly."
]
);
assert!(!values.iter().any(|value| value.contains("raw outcome")));
}
}