Make NPC initiative resolution atomic
This commit is contained in:
parent
934afe67e1
commit
17244b9618
5 changed files with 150 additions and 78 deletions
|
|
@ -451,9 +451,10 @@ pub enum WorldCommand {
|
|||
event_summary: String,
|
||||
reactions: Vec<ActorReaction>,
|
||||
},
|
||||
BeginNpcAction {
|
||||
ResolveNpcAction {
|
||||
expected_revision: u64,
|
||||
proposal: WorldActionProposal,
|
||||
assessment: ActionAssessment,
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -493,9 +493,10 @@ fn execute(
|
|||
});
|
||||
commit(store, row, campaign, "reaction_wave", None)
|
||||
}
|
||||
WorldCommand::BeginNpcAction {
|
||||
WorldCommand::ResolveNpcAction {
|
||||
expected_revision,
|
||||
proposal,
|
||||
assessment,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
let selected = crate::initiative::winner(&campaign.pending_world_proposals)
|
||||
|
|
@ -510,14 +511,70 @@ fn execute(
|
|||
.get(&proposal.actor_id)
|
||||
.ok_or_else(|| KernelError::Invalid("initiative actor is unknown".into()))?;
|
||||
validate_world_proposal(actor, &proposal)?;
|
||||
let intent = ActionIntent {
|
||||
actor_id: proposal.actor_id.clone(),
|
||||
description: proposal.intent.clone(),
|
||||
intended_effect: proposal.intended_effect.clone(),
|
||||
};
|
||||
if assessment.campaign_id != campaign.id
|
||||
|| assessment.revision != campaign.revision
|
||||
|| assessment.intent != intent
|
||||
|| assessment.expires_at < Utc::now()
|
||||
|| crate::assessor::assessment_digest(&assessment)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?
|
||||
!= assessment.digest
|
||||
{
|
||||
return Err(KernelError::Invalid(
|
||||
"NPC assessment is stale or invalid".into(),
|
||||
));
|
||||
}
|
||||
for effect in [
|
||||
&assessment.strong_effect,
|
||||
&assessment.success_effect,
|
||||
&assessment.mixed_effect,
|
||||
&assessment.failure_effect,
|
||||
] {
|
||||
crate::assessor::validate_effect(&campaign, actor, effect)
|
||||
.map_err(|error| KernelError::Invalid(error.to_string()))?;
|
||||
}
|
||||
let actor_name = actor.name.clone();
|
||||
let actor_location = actor.location_id.clone();
|
||||
campaign.pending_world_proposals.clear();
|
||||
let roll = if assessment.admissible {
|
||||
let roll = receipt(
|
||||
assessment.digest.clone(),
|
||||
rand::rng().random_range(1..=20),
|
||||
assessment.modifier_total,
|
||||
assessment.dc,
|
||||
);
|
||||
let (text, effect) = match roll.outcome {
|
||||
OutcomeBand::StrongSuccess => {
|
||||
(&assessment.success_stake, &assessment.strong_effect)
|
||||
}
|
||||
OutcomeBand::Success => (&assessment.success_stake, &assessment.success_effect),
|
||||
OutcomeBand::Mixed => (&assessment.mixed_stake, &assessment.mixed_effect),
|
||||
OutcomeBand::Failure => (&assessment.failure_stake, &assessment.failure_effect),
|
||||
};
|
||||
apply_world_effect(&mut campaign, effect)?;
|
||||
campaign.transcript.push(NarrativeTurn {
|
||||
revision: campaign.revision + 1,
|
||||
at: Utc::now(),
|
||||
speaker: "world".into(),
|
||||
text: text.clone(),
|
||||
});
|
||||
Some(roll)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
campaign.events.push(Event {
|
||||
id: format!("npc-action-begun:{}", campaign.revision + 1),
|
||||
id: format!("npc-action-resolved:{}", campaign.revision + 1),
|
||||
at: campaign.world_time,
|
||||
kind: "npc_action_begun".into(),
|
||||
summary: format!("{} attempts {}", actor_name, proposal.intent),
|
||||
kind: "npc_action_resolved".into(),
|
||||
summary: if assessment.admissible {
|
||||
format!("{} attempts {}", actor_name, proposal.intent)
|
||||
} else {
|
||||
format!("{} cannot yet attempt {}", actor_name, proposal.intent)
|
||||
},
|
||||
actor_ids: vec![proposal.actor_id.clone()],
|
||||
institution_ids: vec![],
|
||||
location_ids: vec![actor_location],
|
||||
|
|
@ -527,7 +584,7 @@ fn execute(
|
|||
&mut campaign,
|
||||
std::iter::once(proposal.actor_id.as_str()),
|
||||
);
|
||||
commit(store, row, campaign, "begin_npc_action", None)
|
||||
commit(store, row, campaign, "resolve_npc_action", roll)
|
||||
}
|
||||
WorldCommand::CreateCampaign { .. } => unreachable!(),
|
||||
}
|
||||
|
|
@ -2070,6 +2127,7 @@ mod tests {
|
|||
);
|
||||
}
|
||||
let activity = seed.last_player_activity;
|
||||
let campaign_id = seed.id;
|
||||
kernel
|
||||
.command(WorldCommand::CreateCampaign {
|
||||
campaign: seed,
|
||||
|
|
@ -2108,58 +2166,90 @@ mod tests {
|
|||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let assessment_for = |actor: &str| ActionIntent {
|
||||
actor_id: actor.into(),
|
||||
description: "intervene".into(),
|
||||
intended_effect: "take control of the immediate situation".into(),
|
||||
};
|
||||
let CommandResult::Assessed {
|
||||
assessment: bert_assessment,
|
||||
} = kernel
|
||||
.command(WorldCommand::Assess {
|
||||
expected_revision: 1,
|
||||
intent: assessment_for("bert"),
|
||||
proposal: None,
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(
|
||||
kernel
|
||||
.command(WorldCommand::BeginNpcAction {
|
||||
.command(WorldCommand::ResolveNpcAction {
|
||||
expected_revision: 1,
|
||||
proposal: bert,
|
||||
assessment: bert_assessment,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let begun = kernel
|
||||
.command(WorldCommand::BeginNpcAction {
|
||||
let CommandResult::Assessed { assessment } = kernel
|
||||
.command(WorldCommand::Assess {
|
||||
expected_revision: 1,
|
||||
intent: assessment_for("anna"),
|
||||
proposal: None,
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let mut malformed = assessment.clone();
|
||||
malformed
|
||||
.success_effect
|
||||
.actor_conditions
|
||||
.insert("invented-actor".into(), ConditionDelta::default());
|
||||
malformed.digest = crate::assessor::assessment_digest(&malformed).unwrap();
|
||||
assert!(
|
||||
kernel
|
||||
.command(WorldCommand::ResolveNpcAction {
|
||||
expected_revision: 1,
|
||||
proposal: anna.clone(),
|
||||
assessment: malformed,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let unchanged = store
|
||||
.load::<Campaign>("campaign.v1", &campaign_id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1;
|
||||
assert_eq!(unchanged.revision, 1);
|
||||
assert_eq!(unchanged.pending_world_proposals.len(), 2);
|
||||
let resolved = kernel
|
||||
.command(WorldCommand::ResolveNpcAction {
|
||||
expected_revision: 1,
|
||||
proposal: anna,
|
||||
assessment,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let CommandResult::Committed {
|
||||
campaign: begun, ..
|
||||
} = begun
|
||||
campaign: resolved, ..
|
||||
} = resolved
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(begun.pending_world_proposals.is_empty());
|
||||
let intent = ActionIntent {
|
||||
actor_id: "anna".into(),
|
||||
description: "intervene".into(),
|
||||
intended_effect: "take control of the immediate situation".into(),
|
||||
};
|
||||
let assessed = kernel
|
||||
.command(WorldCommand::Assess {
|
||||
expected_revision: 2,
|
||||
intent,
|
||||
proposal: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let CommandResult::Assessed { assessment } = assessed else {
|
||||
panic!()
|
||||
};
|
||||
kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
assessment_digest: assessment.digest,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(resolved.pending_world_proposals.is_empty());
|
||||
let persisted = store
|
||||
.load::<Campaign>("campaign.v1", &begun.id.to_string())
|
||||
.load::<Campaign>("campaign.v1", &resolved.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.1;
|
||||
assert_eq!(persisted.last_player_activity, activity);
|
||||
assert_eq!(persisted.revision, 3);
|
||||
assert_eq!(persisted.revision, 2);
|
||||
let CommandResult::Committed { campaign, .. } = wave else {
|
||||
panic!()
|
||||
};
|
||||
|
|
|
|||
|
|
@ -632,54 +632,31 @@ async fn resolve_npc_initiative(
|
|||
else {
|
||||
return Ok(serde_json::Value::Null);
|
||||
};
|
||||
let begun = runtime
|
||||
.kernel
|
||||
.command(WorldCommand::BeginNpcAction {
|
||||
expected_revision: campaign.revision,
|
||||
proposal: proposal.clone(),
|
||||
})
|
||||
.await?;
|
||||
let CommandResult::Committed {
|
||||
campaign: begun_campaign,
|
||||
..
|
||||
} = &begun
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
let assessor = state
|
||||
.assessor
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("NPC initiative requires the action assessor"))?;
|
||||
let intent = ActionIntent {
|
||||
actor_id: proposal.actor_id,
|
||||
description: proposal.intent,
|
||||
intended_effect: proposal.intended_effect,
|
||||
actor_id: proposal.actor_id.clone(),
|
||||
description: proposal.intent.clone(),
|
||||
intended_effect: proposal.intended_effect.clone(),
|
||||
};
|
||||
let (assessment, receipt) = assessor.assess(begun_campaign, intent.clone()).await?;
|
||||
let (assessment, receipt) = assessor.assess(campaign, intent).await?;
|
||||
let _ = runtime.store.insert(
|
||||
"persona_stage_receipt.v1",
|
||||
"ghostlight.persona_stage_receipt.v1",
|
||||
&receipt.output_hash,
|
||||
&receipt,
|
||||
);
|
||||
let assessed = runtime
|
||||
let resolved = runtime
|
||||
.kernel
|
||||
.command(WorldCommand::Assess {
|
||||
expected_revision: begun_campaign.revision,
|
||||
intent,
|
||||
proposal: Some(assessment.clone()),
|
||||
.command(WorldCommand::ResolveNpcAction {
|
||||
expected_revision: campaign.revision,
|
||||
proposal: proposal.clone(),
|
||||
assessment,
|
||||
})
|
||||
.await?;
|
||||
if !assessment.admissible {
|
||||
return Ok(serde_json::json!({"begun":begun,"assessment":assessed,"attempt":null}));
|
||||
}
|
||||
let attempted = runtime
|
||||
.kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
assessment_digest: assessment.digest,
|
||||
})
|
||||
.await?;
|
||||
Ok(serde_json::json!({"begun":begun,"assessment":assessed,"attempt":attempted}))
|
||||
Ok(serde_json::to_value(resolved)?)
|
||||
}
|
||||
|
||||
async fn publish_latest_narration(
|
||||
|
|
@ -1122,7 +1099,7 @@ fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) ->
|
|||
| WorldCommand::IndividuateGestaltMember { .. }
|
||||
| WorldCommand::ReconcileGestaltPresence { .. }
|
||||
| WorldCommand::ResolveReactionWave { .. }
|
||||
| WorldCommand::BeginNpcAction { .. } => false,
|
||||
| WorldCommand::ResolveNpcAction { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -152,20 +152,23 @@ source intent
|
|||
- **Owner:** `WorldKernel` owns the transition from a pending reaction proposal
|
||||
to the single NPC action opportunity for that revision.
|
||||
- **Inputs:** the complete validated proposal set committed by the reaction
|
||||
wave, expected campaign revision, and the deterministic initiative winner.
|
||||
- **Outputs:** one `npc_action_begun` commit that records the selected attempt
|
||||
and consumes the entire stale proposal set; assessment and resolution then
|
||||
operate on the resulting revision.
|
||||
wave, expected campaign revision, deterministic initiative winner, and a
|
||||
locally validated assessment bound to that same revision.
|
||||
- **Outputs:** one `npc_action_resolved` commit that consumes the proposal set,
|
||||
obtains the server-side roll when admissible, applies the selected typed
|
||||
outcome, and stores the roll and commit receipts atomically.
|
||||
- **Derived state:** priority ordering and the selected winner are calculations,
|
||||
not world truth and not commits.
|
||||
- **Forbidden writers:** Persona output, the initiative selector, narrator, and
|
||||
HTTP handler cannot begin or resolve an NPC action directly.
|
||||
- **Shared paths:** live reactions, interrupts, and future offscreen
|
||||
individualized actions all submit `BeginNpcAction`, then use the same
|
||||
`Assess -> Attempt` resolution spine as player attempts.
|
||||
individualized actions all submit `ResolveNpcAction`; it applies the same
|
||||
assessment validation, d20 bands, and typed outcome rules as player attempts.
|
||||
- **Cut line:** pending proposals are no longer a durable action queue. Once one
|
||||
proposal gains the opportunity, every sibling proposal from that snapshot is
|
||||
consumed; actors reappraise the committed result before another action.
|
||||
consumed in the same commit as its resolution; actors reappraise that result
|
||||
before another action. Model or validation failure before this command cannot
|
||||
leave an action-begun half-state.
|
||||
|
||||
This deliberately serializes canonical consequence while keeping perception
|
||||
parallel. It prevents two proposals assessed against the same world snapshot
|
||||
|
|
|
|||
|
|
@ -103,9 +103,10 @@ All affected scene participants appraise a committed event in parallel. Actor-pr
|
|||
|
||||
Canonical NPC consequence is serialized one opportunity at a time. The
|
||||
deterministic initiative projection chooses the highest-priority stable winner;
|
||||
`BeginNpcAction` verifies that exact proposal against the committed wave,
|
||||
consumes its siblings, and advances the revision. The chosen NPC then traverses
|
||||
the same assessment and server-side d20 path as the player without resetting
|
||||
`ResolveNpcAction` verifies that exact proposal and its same-revision assessment
|
||||
against the committed wave, then consumes its siblings, obtains the server-side
|
||||
d20, and applies the typed outcome in one atomic commit. A malformed assessment
|
||||
therefore leaves no action-begun half-state. NPC resolution never resets
|
||||
player-activity or away-time state.
|
||||
|
||||
Use DeepSeek’s current API directly:
|
||||
|
|
|
|||
Loading…
Reference in a new issue