Attitude: opinion modifiers with causes are typed kernel state; prejudice reads what the holder knows
A holder's regard for another subject is now a sum of sourced modifiers (a subject or a trait, a bounded delta, a cause of Prejudice, Grievance, Favor or Rumour, a stamp, an optional fade), never a stored opinion. attitude::opinion derives it, and a trait prejudice reaches a subject only while the holder knows, at Believed or better, a fact the world declared as evidence of the trait. The reducer is the only writer, through AdjustAttitude (a deed, whose cause is named for the command; also an affordance effect with the regarded party fixed to the actor), DeclareAttitude (prejudice or rumour without a deed) and DeclareTrait. State is additive and absent when empty, so existing worlds keep their digests and the schema tag does not move. The derived opinion rides every subject's snapshot; the table view the Dungeon Master reads, a Persona's own view and the narrator's account of who stands with the player all word that one reading and its causes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
09bd3f94ae
commit
c87676c4a1
10 changed files with 1629 additions and 4 deletions
|
|
@ -928,6 +928,14 @@ fn lower(
|
|||
source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)),
|
||||
target: subject(0)?,
|
||||
},
|
||||
// The regarded subject is the actor, so a proposer cannot aim one
|
||||
// person's grudge at a third party; the delta is the entry's.
|
||||
ComponentOpKind::AdjustAttitude { delta, decay } => patch::ComponentOp::AdjustAttitude {
|
||||
holder: subject(0)?,
|
||||
toward: patch::Ref::Existing(actor),
|
||||
delta: *delta,
|
||||
decay: *decay,
|
||||
},
|
||||
ComponentOpKind::Relocate => patch::ComponentOp::Relocate {
|
||||
subject: subject(0)?,
|
||||
via: edge(1)?,
|
||||
|
|
@ -2834,7 +2842,8 @@ mod tests {
|
|||
| ComponentOpKind::CreateCommitment { .. }
|
||||
| ComponentOpKind::AdvancePressure { .. }
|
||||
| ComponentOpKind::ReducePressure { .. }
|
||||
| ComponentOpKind::ResolvePressure => false,
|
||||
| ComponentOpKind::ResolvePressure
|
||||
| ComponentOpKind::AdjustAttitude { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
313
crates/ghostlight/src/attitude.rs
Normal file
313
crates/ghostlight/src/attitude.rs
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
//! Attitude: how one subject regards another, as typed kernel state.
|
||||
//!
|
||||
//! The kernel stores *modifiers*, never an opinion. Each is a sourced, bounded,
|
||||
//! possibly fading term (the Crusader Kings shape); `opinion` derives the sum on
|
||||
//! demand and nothing stores it. A modifier points at one subject, or at a
|
||||
//! *trait* (species, faction, a look, a rumour about a person) and a trait
|
||||
//! modifier is prejudice: it applies to a subject only while the holder knows,
|
||||
//! at `Believed` or better, a fact the world declared as evidence that the
|
||||
//! subject carries that trait. A prejudice against outlanders does nothing to a
|
||||
//! stranger the holder has never learned is one.
|
||||
//!
|
||||
//! The reducer is the only writer: `ResolvedOp::AdjustAttitude` and
|
||||
//! `ResolvedOp::DeclareTrait` land here, through patches and affordance
|
||||
//! effects. Persona prose, the narrator, and host code write nothing.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::clock::{FictionalMinutes, TickMinutes};
|
||||
use super::patch::{Confidence, Ref};
|
||||
use super::{CommandId, EntityId, SubjectId, WorldState};
|
||||
|
||||
/// The bound on one stored modifier and on a derived opinion: a grudge or a
|
||||
/// fondness saturates here, so no run of insults reaches an unrecoverable
|
||||
/// number and the model-facing schema can say the range.
|
||||
pub(crate) const MAX_ATTITUDE: i16 = 100;
|
||||
|
||||
/// How many of an opinion's causes a view names. The rest are summed in.
|
||||
pub(crate) const OPINION_CAUSES_SHOWN: usize = 3;
|
||||
|
||||
/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`: the
|
||||
/// same shape as an authority kind, because it is the same kind of word.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct TraitName(pub(crate) String);
|
||||
|
||||
/// What a modifier regards.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeToward {
|
||||
Subject(SubjectId),
|
||||
Trait(TraitName),
|
||||
}
|
||||
|
||||
/// Why a modifier exists. `Grievance` and `Favor` name the command that did the
|
||||
/// deed, so one act is one row and two acts are two. `Rumour` is a belief the
|
||||
/// holder acted on, and holds only while the holder still knows its fact.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "cause", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeCause {
|
||||
Prejudice,
|
||||
Grievance { command: CommandId },
|
||||
Favor { command: CommandId },
|
||||
Rumour { fact: EntityId },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct AttitudeKey {
|
||||
pub(crate) toward: AttitudeToward,
|
||||
pub(crate) cause: AttitudeCause,
|
||||
}
|
||||
|
||||
/// Nonzero and within `MAX_ATTITUDE` by construction of every writer. `since`
|
||||
/// is the world clock at the last write; with `decay` it sets how the term
|
||||
/// fades, and with none the term is permanent.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct AttitudeModifier {
|
||||
pub(crate) delta: i16,
|
||||
pub(crate) since: FictionalMinutes,
|
||||
pub(crate) decay: Option<TickMinutes>,
|
||||
}
|
||||
|
||||
/// The proposal-time twin of [`AttitudeToward`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeTowardRef {
|
||||
Subject(Ref<SubjectId>),
|
||||
Trait(TraitName),
|
||||
}
|
||||
|
||||
/// What an authored declaration rests on. A deed is not one of these: a deed
|
||||
/// is `AdjustAttitude`, whose cause the kernel derives from the command.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "basis", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeBasisRef {
|
||||
Prejudice,
|
||||
Rumour { fact: Ref<EntityId> },
|
||||
}
|
||||
|
||||
/// One cause of a derived opinion, with the delta it contributes right now.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct OpinionCause {
|
||||
pub(crate) toward: AttitudeToward,
|
||||
pub(crate) cause: AttitudeCause,
|
||||
pub(crate) delta: i32,
|
||||
}
|
||||
|
||||
/// Holder's regard for one subject: the clamped sum and its causes, strongest
|
||||
/// first. Derived, never stored.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Opinion {
|
||||
pub(crate) total: i32,
|
||||
pub(crate) causes: Vec<OpinionCause>,
|
||||
}
|
||||
|
||||
/// A modifier's contribution at `now`: a decaying term fades linearly to zero
|
||||
/// across its period, truncating toward zero.
|
||||
fn effective(modifier: &AttitudeModifier, now: FictionalMinutes) -> i32 {
|
||||
let delta = i64::from(modifier.delta);
|
||||
match modifier.decay {
|
||||
None => delta as i32,
|
||||
Some(period) => {
|
||||
let span = i64::from(period.minutes());
|
||||
let elapsed = i64::try_from(now.since(modifier.since)).unwrap_or(i64::MAX);
|
||||
if elapsed >= span {
|
||||
0
|
||||
} else {
|
||||
(delta * (span - elapsed) / span) as i32
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `holder` holds `fact` at `Believed` or better. A doubted rumour
|
||||
/// moves nobody.
|
||||
fn believes(state: &WorldState, holder: SubjectId, fact: EntityId) -> bool {
|
||||
state
|
||||
.knowledge
|
||||
.get(&holder)
|
||||
.and_then(|held| held.get(&fact))
|
||||
.is_some_and(|entry| entry.confidence >= Confidence::Believed)
|
||||
}
|
||||
|
||||
/// Whether the modifier at `key` applies to `subject` for `holder` right now.
|
||||
fn applies(state: &WorldState, holder: SubjectId, key: &AttitudeKey, subject: SubjectId) -> bool {
|
||||
let reaches = match &key.toward {
|
||||
AttitudeToward::Subject(target) => *target == subject,
|
||||
AttitudeToward::Trait(name) => state
|
||||
.traits
|
||||
.get(&subject)
|
||||
.and_then(|carried| carried.get(name))
|
||||
.is_some_and(|evidence| evidence.iter().any(|fact| believes(state, holder, *fact))),
|
||||
};
|
||||
reaches
|
||||
&& match &key.cause {
|
||||
AttitudeCause::Rumour { fact } => believes(state, holder, *fact),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `holder`'s opinion of `subject`: every applicable modifier, summed and
|
||||
/// clamped. Causes with no remaining weight are dropped; ordered by strength,
|
||||
/// then by key, so the answer is deterministic.
|
||||
pub(crate) fn opinion(state: &WorldState, holder: SubjectId, subject: SubjectId) -> Opinion {
|
||||
let mut causes: Vec<(&AttitudeKey, OpinionCause)> = state
|
||||
.attitudes
|
||||
.get(&holder)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(key, _)| applies(state, holder, key, subject))
|
||||
.map(|(key, modifier)| {
|
||||
(
|
||||
key,
|
||||
OpinionCause {
|
||||
toward: key.toward.clone(),
|
||||
cause: key.cause.clone(),
|
||||
delta: effective(modifier, state.now),
|
||||
},
|
||||
)
|
||||
})
|
||||
.filter(|(_, cause)| cause.delta != 0)
|
||||
.collect();
|
||||
causes.sort_by(|(left_key, left), (right_key, right)| {
|
||||
right
|
||||
.delta
|
||||
.abs()
|
||||
.cmp(&left.delta.abs())
|
||||
.then_with(|| left_key.cmp(right_key))
|
||||
});
|
||||
let total = causes
|
||||
.iter()
|
||||
.map(|(_, cause)| cause.delta)
|
||||
.sum::<i32>()
|
||||
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE));
|
||||
Opinion {
|
||||
total,
|
||||
causes: causes.into_iter().map(|(_, cause)| cause).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every subject `holder` has a nonzero opinion of, in subject order. The
|
||||
/// candidates come from the holder's own rows, so the cost follows what the
|
||||
/// holder feels, never the size of the world.
|
||||
pub(crate) fn opinions_held(state: &WorldState, holder: SubjectId) -> BTreeMap<SubjectId, Opinion> {
|
||||
let Some(rows) = state.attitudes.get(&holder) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut candidates: BTreeSet<SubjectId> = BTreeSet::new();
|
||||
for key in rows.keys() {
|
||||
match &key.toward {
|
||||
AttitudeToward::Subject(target) => {
|
||||
candidates.insert(*target);
|
||||
}
|
||||
AttitudeToward::Trait(name) => candidates.extend(
|
||||
state
|
||||
.traits
|
||||
.iter()
|
||||
.filter(|(_, carried)| carried.contains_key(name))
|
||||
.map(|(subject, _)| *subject),
|
||||
),
|
||||
}
|
||||
}
|
||||
candidates
|
||||
.into_iter()
|
||||
.map(|subject| (subject, opinion(state, holder, subject)))
|
||||
.filter(|(_, held)| !held.causes.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The write: add `delta` to the modifier at `key`, saturating at
|
||||
/// `MAX_ATTITUDE`, and restamp it. A modifier summed to zero is removed, so
|
||||
/// absence is the only zero. Saturation at the bound is a legal write that
|
||||
/// renews the term, which is what a grudge piling on a grudge is.
|
||||
pub(crate) fn adjust(
|
||||
state: &mut WorldState,
|
||||
holder: SubjectId,
|
||||
key: AttitudeKey,
|
||||
delta: i16,
|
||||
decay: Option<TickMinutes>,
|
||||
) {
|
||||
let held = state.attitudes.entry(holder).or_default();
|
||||
let current = held.get(&key).map_or(0, |modifier| i32::from(modifier.delta));
|
||||
let next = (current + i32::from(delta))
|
||||
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE)) as i16;
|
||||
if next == 0 {
|
||||
held.remove(&key);
|
||||
if held.is_empty() {
|
||||
state.attitudes.remove(&holder);
|
||||
}
|
||||
} else {
|
||||
held.insert(
|
||||
key,
|
||||
AttitudeModifier {
|
||||
delta: next,
|
||||
since: state.now,
|
||||
decay,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The deed's cause: a fall in regard is a grievance and a rise is a favor,
|
||||
/// both named for the command that did it.
|
||||
pub(crate) fn deed_cause(delta: i16, command: CommandId) -> AttitudeCause {
|
||||
if delta < 0 {
|
||||
AttitudeCause::Grievance { command }
|
||||
} else {
|
||||
AttitudeCause::Favor { command }
|
||||
}
|
||||
}
|
||||
|
||||
/// A delta an author or a world may write: nonzero, within the bound.
|
||||
pub(crate) fn is_valid_delta(delta: i16) -> bool {
|
||||
delta != 0 && delta.unsigned_abs() <= MAX_ATTITUDE.unsigned_abs()
|
||||
}
|
||||
|
||||
/// A fade the clock can carry: one minute to a year, the span bound every
|
||||
/// other period in the kernel obeys. `TickMinutes` is transparent in serde, so
|
||||
/// a decoded zero is possible and refused here.
|
||||
pub(crate) fn is_valid_decay(decay: Option<TickMinutes>) -> bool {
|
||||
decay.is_none_or(|span| TickMinutes::new(span.minutes()).is_some())
|
||||
}
|
||||
|
||||
/// The one wording of a derived opinion's size, so the Dungeon Master's table,
|
||||
/// a Persona's own view, and the narrator name the same feeling for the same
|
||||
/// number. Reads after "regards them with".
|
||||
pub(crate) fn regard_word(total: i32) -> &'static str {
|
||||
match total {
|
||||
..=-70 => "hatred",
|
||||
-69..=-35 => "hostility",
|
||||
-34..=-10 => "resentment",
|
||||
-9..=9 => "indifference",
|
||||
10..=34 => "liking",
|
||||
35..=69 => "warmth",
|
||||
_ => "devotion",
|
||||
}
|
||||
}
|
||||
|
||||
/// One cause as a clause a reader can act on. The statement of a rumour is the
|
||||
/// fact the holder believes, resolved by the caller from its own view.
|
||||
pub(crate) fn describe_cause(
|
||||
cause: &OpinionCause,
|
||||
fact_statement: impl Fn(EntityId) -> Option<String>,
|
||||
) -> String {
|
||||
let weight = format!("{:+}", cause.delta);
|
||||
match (&cause.cause, &cause.toward) {
|
||||
(AttitudeCause::Prejudice, AttitudeToward::Trait(name)) => {
|
||||
format!("prejudice toward the {} ({weight})", name.0)
|
||||
}
|
||||
(AttitudeCause::Prejudice, AttitudeToward::Subject(_)) => {
|
||||
format!("a feeling it cannot account for ({weight})")
|
||||
}
|
||||
(AttitudeCause::Grievance { .. }, _) => format!("a grievance ({weight})"),
|
||||
(AttitudeCause::Favor { .. }, _) => format!("a favor owed ({weight})"),
|
||||
(AttitudeCause::Rumour { fact }, _) => match fact_statement(*fact) {
|
||||
Some(statement) => format!("a rumour it believes, \"{statement}\" ({weight})"),
|
||||
None => format!("a rumour it believes ({weight})"),
|
||||
},
|
||||
}
|
||||
}
|
||||
500
crates/ghostlight/src/clock_tests/attitude_tests.rs
Normal file
500
crates/ghostlight/src/clock_tests/attitude_tests.rs
Normal file
|
|
@ -0,0 +1,500 @@
|
|||
//! Attitude is kernel state: sourced modifiers, a derived opinion, prejudice
|
||||
//! gated on what the holder knows. Every test here goes through the reducer's
|
||||
//! own doors (a patch or an affordance) and reads the derived opinion back.
|
||||
|
||||
use super::*;
|
||||
use crate::attitude::{self, AttitudeCause, AttitudeToward};
|
||||
use crate::attitude::{AttitudeBasisRef, AttitudeTowardRef, TraitName};
|
||||
|
||||
const OUTLANDER: &str = "The farmer came over the pass from the outland.";
|
||||
|
||||
fn play_patch(
|
||||
kernel: &mut WorldKernel,
|
||||
patch: WorldPatch,
|
||||
) -> Result<SubmitReceipt, KernelError> {
|
||||
submit_as(
|
||||
kernel,
|
||||
play_caller(),
|
||||
CommandBody::AdmitPatch {
|
||||
answers: None,
|
||||
patch,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn fact_with(kernel: &WorldKernel, statement: &str) -> EntityId {
|
||||
*kernel
|
||||
.state
|
||||
.facts
|
||||
.iter()
|
||||
.find(|(_, record)| record.statement.as_str() == statement)
|
||||
.expect("the declared fact")
|
||||
.0
|
||||
}
|
||||
|
||||
fn ruled_fact(handle: &str, statement: &str) -> Declaration {
|
||||
Declaration::Fact(FactDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
label: "A ruling".into(),
|
||||
statement: Statement::new(statement).unwrap(),
|
||||
standing: FactStandingRef::Ruled,
|
||||
})
|
||||
}
|
||||
|
||||
fn learn(
|
||||
kernel: &mut WorldKernel,
|
||||
subject: SubjectId,
|
||||
fact: EntityId,
|
||||
confidence: Confidence,
|
||||
) -> Result<SubmitReceipt, KernelError> {
|
||||
play_patch(
|
||||
kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::AcquireKnowledge {
|
||||
subject: Ref::Existing(subject),
|
||||
fact: Ref::Existing(fact),
|
||||
source: AuthoredSource::Witnessed,
|
||||
confidence,
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn regard(kernel: &WorldKernel, holder: SubjectId, subject: SubjectId) -> attitude::Opinion {
|
||||
attitude::opinion(&kernel.state, holder, subject)
|
||||
}
|
||||
|
||||
/// A reeve who is prejudiced against outlanders, and a farmer who is one.
|
||||
fn outlander_world(path: &Path) -> (WorldKernel, Clockwork, EntityId) {
|
||||
let (mut kernel, clockwork, _) = clock_kernel(path, "Outlanders");
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![ruled_fact("outland", OUTLANDER)],
|
||||
operations: vec![
|
||||
ComponentOp::DeclareTrait {
|
||||
subject: Ref::Existing(clockwork.farmer),
|
||||
name: TraitName("outlander".into()),
|
||||
fact: Ref::Draft(DraftHandle::new("outland")),
|
||||
},
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||
delta: -40,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
},
|
||||
],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("the play authority declares the trait and the prejudice");
|
||||
let fact = fact_with(&kernel, OUTLANDER);
|
||||
(kernel, clockwork, fact)
|
||||
}
|
||||
|
||||
/// A world-authored `insult`: the target comes to regard the actor 30 lower.
|
||||
fn grant_insult(kernel: &mut WorldKernel, to: SubjectId, delta: i16, decay: Option<TickMinutes>) {
|
||||
play_patch(
|
||||
kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
|
||||
handle: DraftHandle::new("insult"),
|
||||
kind: AffordanceKindName("insult".into()),
|
||||
roles: vec![RoleSpec {
|
||||
role: Role("target".into()),
|
||||
kind: RefKind::Subject(None),
|
||||
}],
|
||||
preconditions: Vec::new(),
|
||||
effect_slots: vec![EffectSlot {
|
||||
op_kind: ComponentOpKind::AdjustAttitude { delta, decay },
|
||||
roles: vec![Role("target".into())],
|
||||
bounds: Bounds::None,
|
||||
}],
|
||||
outcome_bands: vec![OutcomeBand {
|
||||
weight: 1,
|
||||
effects: vec![0],
|
||||
}],
|
||||
carries_speech: false,
|
||||
})],
|
||||
operations: vec![ComponentOp::GrantAffordance {
|
||||
subject: Ref::Existing(to),
|
||||
affordance: Ref::Draft(DraftHandle::new("insult")),
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("the world authors and grants the verb");
|
||||
}
|
||||
|
||||
fn insult_id(kernel: &WorldKernel) -> AffordanceId {
|
||||
*kernel
|
||||
.state
|
||||
.affordance_catalog
|
||||
.iter()
|
||||
.find(|(_, entry)| entry.kind.0 == "insult")
|
||||
.expect("the insult entry")
|
||||
.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prejudice_needs_belief() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||
|
||||
// The holder has not heard the farmer is an outlander: no opinion at all.
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
assert!(kernel.snapshot().unwrap().subjects.iter().all(|s| s.opinions.is_empty()));
|
||||
|
||||
// Somebody else knowing it does not move the reeve.
|
||||
learn(&mut kernel, clockwork.treasury, fact, Confidence::Certain).unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
|
||||
// A doubted telling does not either.
|
||||
learn(&mut kernel, clockwork.reeve, fact, Confidence::Doubted).unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
|
||||
// Believed, it does, for the farmer and for nobody who is not one.
|
||||
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -40);
|
||||
assert_eq!(held.causes[0].cause, AttitudeCause::Prejudice);
|
||||
assert_eq!(
|
||||
held.causes[0].toward,
|
||||
AttitudeToward::Trait(TraitName("outlander".into()))
|
||||
);
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.treasury).total, 0);
|
||||
assert_eq!(
|
||||
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
|
||||
0,
|
||||
"regard does not run backward"
|
||||
);
|
||||
|
||||
// Forgetting it lifts the prejudice: the opinion is derived, not stored.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::Forget {
|
||||
subject: Ref::Existing(clockwork.reeve),
|
||||
fact: Ref::Existing(fact),
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grievance_from_an_act() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Grievance");
|
||||
grant_insult(&mut kernel, clockwork.farmer, -30, None);
|
||||
let insult = insult_id(&kernel);
|
||||
|
||||
exercise(
|
||||
&mut kernel,
|
||||
clockwork.farmer,
|
||||
insult,
|
||||
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||
)
|
||||
.expect("the insult commits");
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -30);
|
||||
assert!(matches!(
|
||||
held.causes[0].cause,
|
||||
AttitudeCause::Grievance { .. }
|
||||
));
|
||||
assert_eq!(
|
||||
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
|
||||
0,
|
||||
"the insulter does not come to resent the insulted"
|
||||
);
|
||||
|
||||
// A second insult is a second act with its own cause; they add.
|
||||
exercise(
|
||||
&mut kernel,
|
||||
clockwork.farmer,
|
||||
insult,
|
||||
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||
)
|
||||
.unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -60);
|
||||
assert_eq!(held.causes.len(), 2);
|
||||
assert_ne!(held.causes[0].cause, held.causes[1].cause);
|
||||
|
||||
// A favor is the same write with the other sign.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta: 20,
|
||||
decay: None,
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -40);
|
||||
assert!(
|
||||
held.causes
|
||||
.iter()
|
||||
.any(|cause| matches!(cause.cause, AttitudeCause::Favor { .. }) && cause.delta == 20)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regard_saturates_at_the_bound_and_a_clamped_write_is_not_an_error() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Saturation");
|
||||
let wrong = |delta| ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta,
|
||||
decay: None,
|
||||
};
|
||||
// Three deeds in one command are one row of the same cause, clamped.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![wrong(-60), wrong(-60), wrong(-60)],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("a saturated write still commits");
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -100);
|
||||
assert_eq!(held.causes.len(), 1);
|
||||
|
||||
// Separate commands pile past one row, and the opinion still clamps.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![wrong(-60)],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_decaying_term_fades_and_a_grudge_does_not() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Decay");
|
||||
let write = |delta, decay| ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta,
|
||||
decay,
|
||||
};
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![write(-40, Some(minutes(100)))],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![write(20, None)],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -20);
|
||||
tick(&mut kernel, 50).unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
tick(&mut kernel, 50).unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, 20, "the faded grievance is gone, the favor stays");
|
||||
assert_eq!(held.causes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rumour_moves_only_a_holder_who_believes_it() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Rumour");
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![ruled_fact("tale", "They say the farmer poisoned a well.")],
|
||||
operations: vec![ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
|
||||
delta: -25,
|
||||
basis: AttitudeBasisRef::Rumour {
|
||||
fact: Ref::Draft(DraftHandle::new("tale")),
|
||||
},
|
||||
decay: None,
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let tale = fact_with(&kernel, "They say the farmer poisoned a well.");
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
learn(&mut kernel, clockwork.reeve, tale, Confidence::Believed).unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -25);
|
||||
assert_eq!(held.causes[0].cause, AttitudeCause::Rumour { fact: tale });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attitude_writes_with_no_meaning_are_refused_whole() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||
let before = kernel.state.clone();
|
||||
let adjust = |delta, holder, toward| ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(holder),
|
||||
toward: Ref::Existing(toward),
|
||||
delta,
|
||||
decay: None,
|
||||
};
|
||||
let refused: Vec<(&str, ComponentOp)> = vec![
|
||||
("zero delta", adjust(0, clockwork.reeve, clockwork.farmer)),
|
||||
("past the bound", adjust(101, clockwork.reeve, clockwork.farmer)),
|
||||
("regarding oneself", adjust(-5, clockwork.reeve, clockwork.reeve)),
|
||||
(
|
||||
"a zero decay",
|
||||
ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta: -5,
|
||||
decay: serde_json::from_value(serde_json::json!(0)).unwrap(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"a rumour of a trait",
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||
delta: -5,
|
||||
basis: AttitudeBasisRef::Rumour {
|
||||
fact: Ref::Existing(fact),
|
||||
},
|
||||
decay: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
"a trait that is not a name",
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("Not A Name".into())),
|
||||
delta: -5,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
"a trait declared with a bad name",
|
||||
ComponentOp::DeclareTrait {
|
||||
subject: Ref::Existing(clockwork.farmer),
|
||||
name: TraitName("".into()),
|
||||
fact: Ref::Existing(fact),
|
||||
},
|
||||
),
|
||||
];
|
||||
for (name, operation) in refused {
|
||||
let error = play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![operation],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect_err(name);
|
||||
assert!(
|
||||
format!("{error:?}").contains("InvalidAttitude"),
|
||||
"{name}: {error:?}"
|
||||
);
|
||||
}
|
||||
// An affordance whose delta is nothing is refused at declaration.
|
||||
let error = play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
|
||||
handle: DraftHandle::new("nothing"),
|
||||
kind: AffordanceKindName("nothing".into()),
|
||||
roles: vec![RoleSpec {
|
||||
role: Role("target".into()),
|
||||
kind: RefKind::Subject(None),
|
||||
}],
|
||||
preconditions: Vec::new(),
|
||||
effect_slots: vec![EffectSlot {
|
||||
op_kind: ComponentOpKind::AdjustAttitude {
|
||||
delta: 0,
|
||||
decay: None,
|
||||
},
|
||||
roles: vec![Role("target".into())],
|
||||
bounds: Bounds::None,
|
||||
}],
|
||||
outcome_bands: vec![OutcomeBand {
|
||||
weight: 1,
|
||||
effects: vec![0],
|
||||
}],
|
||||
carries_speech: false,
|
||||
})],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect_err("an entry that changes no regard");
|
||||
assert!(format!("{error:?}").contains("InvalidAttitude"), "{error:?}");
|
||||
assert_eq!(kernel.state, before, "a refused write leaves no trace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_derived_opinion_and_its_causes_reach_the_tables_view() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||
grant_insult(&mut kernel, clockwork.farmer, -30, None);
|
||||
let insult = insult_id(&kernel);
|
||||
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
|
||||
exercise(
|
||||
&mut kernel,
|
||||
clockwork.farmer,
|
||||
insult,
|
||||
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let reeve = snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.id == clockwork.reeve)
|
||||
.unwrap();
|
||||
assert_eq!(reeve.opinions.len(), 1);
|
||||
assert_eq!(reeve.opinions[0].toward, clockwork.farmer);
|
||||
assert_eq!(reeve.opinions[0].total, -70);
|
||||
assert_eq!(reeve.opinions[0].causes.len(), 2);
|
||||
|
||||
let view = crate::table_view(&snapshot);
|
||||
let line = view
|
||||
.split("Regard")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split("Persona material").next())
|
||||
.expect("the table has a regard section");
|
||||
assert!(line.contains("The Yard Reeve"), "{line}");
|
||||
assert!(line.contains("regards The Yard Farmer"), "{line}");
|
||||
assert!(line.contains("with hostility (-70)"), "{line}");
|
||||
assert!(line.contains("(-70)"), "{line}");
|
||||
assert!(line.contains("a grievance (-30)"), "{line}");
|
||||
assert!(line.contains("prejudice toward the outlander (-40)"), "{line}");
|
||||
}
|
||||
|
|
@ -4963,6 +4963,7 @@ impl SelectedDecision {
|
|||
"redress": self.projector_redress(),
|
||||
"commitments": self.projector_commitments(),
|
||||
"pressures": self.projector_pressures(),
|
||||
"regard": self.projector_regard(),
|
||||
}))
|
||||
.map_err(|error| ControllerError::Serialization(error.to_string()))
|
||||
}
|
||||
|
|
@ -4992,6 +4993,7 @@ impl SelectedDecision {
|
|||
("redress", Value::Array(self.projector_redress())),
|
||||
("commitments", Value::Array(self.projector_commitments())),
|
||||
("pressures", Value::Array(self.projector_pressures())),
|
||||
("regard", Value::Array(self.narrator_regard())),
|
||||
];
|
||||
let present: serde_json::Map<String, Value> = fields
|
||||
.into_iter()
|
||||
|
|
@ -5002,6 +5004,65 @@ impl SelectedDecision {
|
|||
.map_err(|error| ControllerError::Serialization(error.to_string()))
|
||||
}
|
||||
|
||||
/// What one derived opinion rests on, as the clauses every reader of it
|
||||
/// shares. A rumour's own words are named only if this view's subject
|
||||
/// holds the fact, which the kernel already required for it to count.
|
||||
fn regard_because(&self, held: &crate::OpinionSnapshot) -> Vec<String> {
|
||||
held.causes
|
||||
.iter()
|
||||
.map(|cause| {
|
||||
crate::attitude::describe_cause(cause, |fact| {
|
||||
self.snapshot
|
||||
.facts
|
||||
.iter()
|
||||
.find(|entry| entry.id == fact)
|
||||
.map(|entry| entry.statement.as_str().to_owned())
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// This subject's own standing grudges, fondnesses and prejudices as it
|
||||
/// carries them: how it holds each party and what that rests on. The
|
||||
/// kernel derived the number and the causes; this only words them.
|
||||
fn projector_regard(&self) -> Vec<Value> {
|
||||
self.subject
|
||||
.opinions
|
||||
.iter()
|
||||
.map(|held| {
|
||||
json!({
|
||||
"of": self.subject_label(held.toward),
|
||||
"you_regard_them_with": crate::attitude::regard_word(held.total),
|
||||
"strength": held.total,
|
||||
"because": self.regard_because(held),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How each person standing with the player holds the player, from the
|
||||
/// same derived opinion their own Persona is given, so the storyteller
|
||||
/// renders the attitude the world committed and invents none.
|
||||
fn narrator_regard(&self) -> Vec<Value> {
|
||||
let Some(here) = self.subject.position else {
|
||||
return Vec::new();
|
||||
};
|
||||
self.snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.filter(|other| other.id != self.subject.id && other.position == Some(here))
|
||||
.filter_map(|other| {
|
||||
let held = other.opinions.iter().find(|held| held.toward == self.subject.id)?;
|
||||
Some(json!({
|
||||
"who": other.label,
|
||||
"regards_the_player_with": crate::attitude::regard_word(held.total),
|
||||
"strength": held.total,
|
||||
"because": self.regard_because(held),
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The open routes that leave the subject's place, with where each leads.
|
||||
fn narrator_exits(&self) -> Vec<Value> {
|
||||
let Some(here) = self.subject.position else {
|
||||
|
|
@ -8423,6 +8484,7 @@ mod tests {
|
|||
],
|
||||
commitments: Vec::new(),
|
||||
pressures: Vec::new(),
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: false,
|
||||
material: None,
|
||||
|
|
@ -8454,6 +8516,7 @@ mod tests {
|
|||
}],
|
||||
commitments: Vec::new(),
|
||||
pressures: Vec::new(),
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: false,
|
||||
material: None,
|
||||
|
|
@ -8579,6 +8642,7 @@ mod tests {
|
|||
}],
|
||||
commitments: Vec::new(),
|
||||
pressures: Vec::new(),
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: false,
|
||||
material: None,
|
||||
|
|
@ -10241,6 +10305,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
|
|||
],
|
||||
commitments: Vec::new(),
|
||||
pressures: Vec::new(),
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: false,
|
||||
material: None,
|
||||
|
|
@ -10264,6 +10329,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
|
|||
knowledge: Vec::new(),
|
||||
commitments: Vec::new(),
|
||||
pressures: Vec::new(),
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: false,
|
||||
material: None,
|
||||
|
|
@ -10390,6 +10456,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
|
|||
knowledge: Vec::new(),
|
||||
commitments: Vec::new(),
|
||||
pressures: Vec::new(),
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: false,
|
||||
material: None,
|
||||
|
|
@ -10416,6 +10483,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
|
|||
knowledge: Vec::new(),
|
||||
commitments: Vec::new(),
|
||||
pressures: Vec::new(),
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: false,
|
||||
material: None,
|
||||
|
|
@ -10868,6 +10936,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
|
|||
knowledge: Vec::new(),
|
||||
commitments,
|
||||
pressures,
|
||||
opinions: Vec::new(),
|
||||
dependencies: Vec::new(),
|
||||
qualified: true,
|
||||
material: None,
|
||||
|
|
@ -22306,3 +22375,81 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
|
|||
task.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod regard_projection_tests {
|
||||
use super::*;
|
||||
use crate::attitude::{AttitudeBasisRef, AttitudeTowardRef, TraitName};
|
||||
use crate::tests::{auth_principal, creation, opportunity_for, operations, owner, speech_world, submit_owner};
|
||||
use crate::{ComponentOp, Ref, WorldKernel};
|
||||
|
||||
/// The listener holds the speaker (the player, here) in hostility for a
|
||||
/// deed. The kernel derived it once; the Persona's own view, the
|
||||
/// storyteller's view of who stands with the player, and the table all
|
||||
/// carry that same reading and its cause.
|
||||
#[test]
|
||||
fn a_wronged_persona_and_the_narrator_are_handed_the_committed_regard() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut kernel = WorldKernel::create(
|
||||
directory.path().join("world.cc"),
|
||||
creation(CommandId::new(), "Regard"),
|
||||
&auth_principal(owner()),
|
||||
)
|
||||
.unwrap()
|
||||
.0;
|
||||
let (speech, active) = speech_world(&mut kernel);
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&active,
|
||||
operations(vec![
|
||||
ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(speech.listener),
|
||||
toward: Ref::Existing(speech.speaker),
|
||||
delta: -60,
|
||||
decay: None,
|
||||
},
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(speech.bystander),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||
delta: -50,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
},
|
||||
]),
|
||||
);
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let select = |subject| {
|
||||
let subject_snapshot = snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|candidate| candidate.id == subject)
|
||||
.unwrap()
|
||||
.clone();
|
||||
SelectedDecision {
|
||||
opportunity: opportunity_for(&snapshot, subject),
|
||||
snapshot: snapshot.clone(),
|
||||
subject: subject_snapshot,
|
||||
granted: Vec::new(),
|
||||
}
|
||||
};
|
||||
|
||||
// The wronged Persona sees how it holds the player, and why.
|
||||
let persona = select(speech.listener).projector_context().unwrap();
|
||||
assert!(persona.contains("\"you_regard_them_with\": \"hostility\""), "{persona}");
|
||||
assert!(persona.contains("\"strength\": -60"), "{persona}");
|
||||
assert!(persona.contains("a grievance (-60)"), "{persona}");
|
||||
|
||||
// A subject nobody wronged is handed no regard, and the prejudiced one
|
||||
// has none yet: nobody has told it anyone is an outlander.
|
||||
for quiet in [speech.speaker, speech.bystander] {
|
||||
let context = select(quiet).projector_context().unwrap();
|
||||
assert!(context.contains("\"regard\": []"), "{context}");
|
||||
}
|
||||
|
||||
// The narrator, over the player's slice, is told who regards the
|
||||
// player how, from the same derived opinion.
|
||||
let narrator = select(speech.speaker).narrator_context().unwrap();
|
||||
assert!(narrator.contains("\"regards_the_player_with\": \"hostility\""), "{narrator}");
|
||||
assert!(narrator.contains("a grievance (-60)"), "{narrator}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -733,6 +733,55 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
|
|||
));
|
||||
}
|
||||
}
|
||||
// Attitude: a holder and its target are canonical subjects, a delta is
|
||||
// nonzero and bounded, a stamp is not from the future, and a rumour rests
|
||||
// on a fact that exists. A trait row names a canonical subject, a civic
|
||||
// trait name, and at least one real fact.
|
||||
for (holder, held) in &state.attitudes {
|
||||
let modifier_is_canonical = |key: &super::AttitudeKey, modifier: &super::AttitudeModifier| {
|
||||
let toward_is_canonical = match &key.toward {
|
||||
super::AttitudeToward::Subject(target) => {
|
||||
state.subjects.contains_key(target) && target != holder
|
||||
}
|
||||
super::AttitudeToward::Trait(name) => super::patch::is_civic_name(&name.0),
|
||||
};
|
||||
let cause_is_canonical = match &key.cause {
|
||||
super::AttitudeCause::Rumour { fact } => {
|
||||
state.facts.contains_key(fact)
|
||||
&& matches!(key.toward, super::AttitudeToward::Subject(_))
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
toward_is_canonical
|
||||
&& cause_is_canonical
|
||||
&& crate::attitude::is_valid_delta(modifier.delta)
|
||||
&& crate::attitude::is_valid_decay(modifier.decay)
|
||||
&& modifier.since <= state.now
|
||||
};
|
||||
if !state.subjects.contains_key(holder)
|
||||
|| held.is_empty()
|
||||
|| !held.iter().all(|(key, modifier)| modifier_is_canonical(key, modifier))
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"an attitude row does not name a canonical holder, target, cause, and bounded delta"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
for (subject_id, carried) in &state.traits {
|
||||
if !state.subjects.contains_key(subject_id)
|
||||
|| carried.is_empty()
|
||||
|| carried.iter().any(|(name, evidence)| {
|
||||
!super::patch::is_civic_name(&name.0)
|
||||
|| evidence.is_empty()
|
||||
|| !evidence.iter().all(|fact| state.facts.contains_key(fact))
|
||||
})
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"a trait row does not name a canonical subject, trait, and fact".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if state
|
||||
.last_opportunity_at
|
||||
.iter()
|
||||
|
|
@ -2990,4 +3039,118 @@ mod custody_tests {
|
|||
"the chain digest answered for the authority check: {detail}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Attitude replays exactly: a restart rebuilds the same modifiers, traits
|
||||
/// and digest from the commits, and a row nobody's command wrote, whether
|
||||
/// edited, planted, or re-sealed under a digest that agrees with it, stops
|
||||
/// the history from recovering.
|
||||
#[test]
|
||||
fn attitude_replays_exactly_and_a_forged_row_fails_replay() {
|
||||
use crate::attitude::{AttitudeBasisRef, AttitudeCause, AttitudeKey, AttitudeToward, AttitudeTowardRef, TraitName};
|
||||
use crate::tests::{auth_principal, creation, operations, owner, speech_world, submit_owner};
|
||||
use crate::{ComponentOp, Ref};
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
let (mut kernel, _) =
|
||||
WorldKernel::create(&path, creation(CommandId::new(), "Attitude"), &auth_principal(owner()))
|
||||
.unwrap();
|
||||
let (speech, _) = speech_world(&mut kernel);
|
||||
let before = kernel.snapshot().unwrap();
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&before,
|
||||
operations(vec![
|
||||
ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(speech.listener),
|
||||
toward: Ref::Existing(speech.speaker),
|
||||
delta: -30,
|
||||
decay: None,
|
||||
},
|
||||
ComponentOp::DeclareTrait {
|
||||
subject: Ref::Existing(speech.speaker),
|
||||
name: TraitName("outlander".into()),
|
||||
fact: Ref::Existing(speech.flood),
|
||||
},
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(speech.listener),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||
delta: -10,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
},
|
||||
]),
|
||||
);
|
||||
assert!(!kernel.state.attitudes.is_empty() && !kernel.state.traits.is_empty());
|
||||
|
||||
let rows = |state: &WorldState| -> Vec<CultCacheEnvelope> {
|
||||
let mut rows: Vec<CultCacheEnvelope> = kernel
|
||||
.journal
|
||||
.commits
|
||||
.values()
|
||||
.map(|commit| {
|
||||
envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap()
|
||||
})
|
||||
.collect();
|
||||
rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap());
|
||||
rows
|
||||
};
|
||||
let (_, recovered, _) = recover(rows(&kernel.state), None).expect("the honest history recovers");
|
||||
assert_eq!(recovered, kernel.state);
|
||||
assert_eq!(recovered.state_digest, kernel.state.state_digest);
|
||||
|
||||
let planted = AttitudeKey {
|
||||
toward: AttitudeToward::Subject(speech.listener),
|
||||
cause: AttitudeCause::Prejudice,
|
||||
};
|
||||
let forgeries: Vec<(&str, Box<dyn Fn(&mut WorldState)>)> = vec![
|
||||
(
|
||||
"a grievance edited",
|
||||
Box::new(|state| {
|
||||
let held = state.attitudes.get_mut(&speech.listener).unwrap();
|
||||
held.values_mut().next().unwrap().delta = -90;
|
||||
}),
|
||||
),
|
||||
(
|
||||
"an attitude planted",
|
||||
Box::new(move |state| {
|
||||
state.attitudes.entry(speech.speaker).or_default().insert(
|
||||
planted.clone(),
|
||||
crate::AttitudeModifier {
|
||||
delta: -50,
|
||||
since: state.now,
|
||||
decay: None,
|
||||
},
|
||||
);
|
||||
}),
|
||||
),
|
||||
(
|
||||
"a grievance erased",
|
||||
Box::new(|state| {
|
||||
state.attitudes.clear();
|
||||
}),
|
||||
),
|
||||
(
|
||||
"a trait erased",
|
||||
Box::new(|state| {
|
||||
state.traits.clear();
|
||||
}),
|
||||
),
|
||||
];
|
||||
for (name, forge) in forgeries {
|
||||
let mut forged = kernel.state.clone();
|
||||
forge(&mut forged);
|
||||
assert!(
|
||||
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
|
||||
"{name}: a forged attitude row replayed"
|
||||
);
|
||||
// Re-sealed under a digest that agrees with the forgery.
|
||||
forged.state_digest = crate::state_digest(&forged).unwrap();
|
||||
assert!(
|
||||
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
|
||||
"{name}: a re-sealed forged attitude row replayed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@
|
|||
|
||||
mod action;
|
||||
mod aetheria;
|
||||
mod attitude;
|
||||
mod clock;
|
||||
mod consumer;
|
||||
mod controllers;
|
||||
|
|
@ -77,6 +78,9 @@ mod vault;
|
|||
mod verse;
|
||||
|
||||
pub(crate) use action::ActionMismatch;
|
||||
pub(crate) use attitude::{
|
||||
AttitudeCause, AttitudeKey, AttitudeModifier, AttitudeToward, TraitName,
|
||||
};
|
||||
pub(crate) use clock::Motion;
|
||||
pub use clock::{FictionalMinutes, TickMinutes};
|
||||
pub use consumer::{
|
||||
|
|
@ -931,6 +935,19 @@ struct WorldState {
|
|||
/// Pressure *on* each subject, keyed target-major then source. Never empty
|
||||
/// for a present key; no stored zero magnitude.
|
||||
pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>,
|
||||
/// How each subject regards others: sourced modifiers, never a stored
|
||||
/// opinion (`attitude::opinion` derives it). Never empty for a present key;
|
||||
/// no stored zero delta. Outside every scope digest: attitude constrains no
|
||||
/// precondition. Absent from a world that has none, so such a world's state
|
||||
/// and digests are what they were before attitude existed.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
attitudes: BTreeMap<SubjectId, BTreeMap<AttitudeKey, AttitudeModifier>>,
|
||||
/// The facts the world declares as evidence that a subject carries a trait:
|
||||
/// what a prejudice reads, since a trait modifier applies to a subject only
|
||||
/// while its holder knows one of these. Never empty for a present key.
|
||||
/// Absent when empty, for the same reason as `attitudes`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
traits: BTreeMap<SubjectId, BTreeMap<TraitName, BTreeSet<EntityId>>>,
|
||||
/// When each subject was last given a decision opportunity it consumed.
|
||||
/// Absence means never. The debt term of the attention order and nothing
|
||||
/// else.
|
||||
|
|
@ -1094,6 +1111,11 @@ pub struct SubjectSnapshot {
|
|||
/// subject's state, and the actor already sees the commitment that produced
|
||||
/// it.
|
||||
pub(crate) pressures: Vec<PressureSnapshot>,
|
||||
/// How this subject regards each subject it has an opinion of, derived by
|
||||
/// `attitude::opinion` at snapshot time: never stored, so there is one
|
||||
/// answer for the Dungeon Master's table, a Persona's own view, and the
|
||||
/// narrator. View-only, covered by no digest of its own.
|
||||
pub(crate) opinions: Vec<OpinionSnapshot>,
|
||||
/// This subject's own dependencies, lowered from `components.dependencies`
|
||||
/// (private to this module) so the play table's omniscient view can print
|
||||
/// what a `release` may name without reaching into `ScopeComponents`
|
||||
|
|
@ -1133,6 +1155,17 @@ pub(crate) struct PressureSnapshot {
|
|||
pub(crate) magnitude: PressureMagnitude,
|
||||
}
|
||||
|
||||
/// One subject's derived regard for another, with its strongest causes. A trait
|
||||
/// prejudice appears only once the holder knows the subject carries the trait.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct OpinionSnapshot {
|
||||
pub(crate) toward: SubjectId,
|
||||
/// Clamped to `-MAX_ATTITUDE..=MAX_ATTITUDE`.
|
||||
pub(crate) total: i32,
|
||||
/// At most `OPINION_CAUSES_SHOWN`, strongest first.
|
||||
pub(crate) causes: Vec<attitude::OpinionCause>,
|
||||
}
|
||||
|
||||
/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a
|
||||
/// receipt is non-fictional provenance and never enters a subject-facing
|
||||
/// surface, so a subject learns *that* a fact is canonical and never which
|
||||
|
|
@ -2109,6 +2142,8 @@ impl WorldState {
|
|||
commitments: BTreeMap::new(),
|
||||
persona_material: BTreeMap::new(),
|
||||
pressures: BTreeMap::new(),
|
||||
attitudes: BTreeMap::new(),
|
||||
traits: BTreeMap::new(),
|
||||
last_opportunity_at: BTreeMap::new(),
|
||||
now: FictionalMinutes::default(),
|
||||
scale_intent: WorldScaleIntent::default(),
|
||||
|
|
@ -3307,6 +3342,50 @@ fn apply_operation(
|
|||
}
|
||||
set_pressure(state, *target, *source, 0);
|
||||
}
|
||||
ResolvedOp::AdjustAttitude {
|
||||
holder,
|
||||
key,
|
||||
delta,
|
||||
decay,
|
||||
} => {
|
||||
let regards_live = match &key.toward {
|
||||
AttitudeToward::Subject(target) => state.subjects.contains_key(target),
|
||||
AttitudeToward::Trait(name) => patch::is_civic_name(&name.0),
|
||||
};
|
||||
let rests_on_known = match &key.cause {
|
||||
AttitudeCause::Rumour { fact } => state.facts.contains_key(fact),
|
||||
_ => true,
|
||||
};
|
||||
if !state.subjects.contains_key(holder)
|
||||
|| !regards_live
|
||||
|| !rests_on_known
|
||||
|| !attitude::is_valid_delta(*delta)
|
||||
|| !attitude::is_valid_decay(*decay)
|
||||
|| key.toward == AttitudeToward::Subject(*holder)
|
||||
{
|
||||
return Err(unknown());
|
||||
}
|
||||
attitude::adjust(state, *holder, key.clone(), *delta, *decay);
|
||||
}
|
||||
ResolvedOp::DeclareTrait {
|
||||
subject,
|
||||
name,
|
||||
fact,
|
||||
} => {
|
||||
if !state.subjects.contains_key(subject)
|
||||
|| !state.facts.contains_key(fact)
|
||||
|| !patch::is_civic_name(&name.0)
|
||||
{
|
||||
return Err(unknown());
|
||||
}
|
||||
state
|
||||
.traits
|
||||
.entry(*subject)
|
||||
.or_default()
|
||||
.entry(name.clone())
|
||||
.or_default()
|
||||
.insert(*fact);
|
||||
}
|
||||
ResolvedOp::Retire { subject } => {
|
||||
let scope = DecisionScope {
|
||||
subject_id: *subject,
|
||||
|
|
@ -4251,6 +4330,17 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
|||
magnitude: *magnitude,
|
||||
})
|
||||
.collect(),
|
||||
opinions: attitude::opinions_held(state, *subject_id)
|
||||
.into_iter()
|
||||
.map(|(toward, mut held)| {
|
||||
held.causes.truncate(attitude::OPINION_CAUSES_SHOWN);
|
||||
OpinionSnapshot {
|
||||
toward,
|
||||
total: held.total,
|
||||
causes: held.causes,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
qualified: qualifies(state, *subject_id),
|
||||
last_acted_at: last_acted_at.get(subject_id).copied(),
|
||||
})
|
||||
|
|
@ -5354,6 +5444,16 @@ fn operation_ground(
|
|||
}
|
||||
(subjects, places(named), routes)
|
||||
}
|
||||
// An attitude is the holder's own state about another subject, so both
|
||||
// are ground; a trait names none.
|
||||
ResolvedOp::AdjustAttitude { holder, key, .. } => {
|
||||
let mut subjects = vec![*holder];
|
||||
if let AttitudeToward::Subject(target) = &key.toward {
|
||||
subjects.push(*target);
|
||||
}
|
||||
(subjects, Vec::new(), Vec::new())
|
||||
}
|
||||
ResolvedOp::DeclareTrait { subject, .. } => (vec![*subject], Vec::new(), Vec::new()),
|
||||
// Confinement never reaches these through the ordinary ground check:
|
||||
// `confine_to_ground` refuses `Retire`, `GrantAffordance`, and
|
||||
// `RevokeAffordance` unconditionally for every confined author before
|
||||
|
|
@ -13207,6 +13307,8 @@ mod clock_tests {
|
|||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
mod attitude_tests;
|
||||
|
||||
/// The canonical IDs of the clock fixture: a hall containing a yard, a
|
||||
/// dead end reached by exactly one route, three subjects, a resource, and
|
||||
/// one commitment of each kind.
|
||||
|
|
|
|||
|
|
@ -11,6 +11,10 @@
|
|||
//! Resolution accumulates the complete mismatch set first and allocates only
|
||||
//! after that set is empty, so a rejected patch never mints an ID.
|
||||
|
||||
use super::attitude::{
|
||||
self, AttitudeBasisRef, AttitudeCause, AttitudeKey, AttitudeToward, AttitudeTowardRef, MAX_ATTITUDE,
|
||||
TraitName,
|
||||
};
|
||||
use super::clock::{FictionalMinutes, TickMinutes};
|
||||
use super::tool_schema;
|
||||
use super::grammar::GrammarRefusal;
|
||||
|
|
@ -777,6 +781,16 @@ pub(crate) enum ComponentOpKind {
|
|||
by: PressureMagnitude,
|
||||
},
|
||||
ResolvePressure,
|
||||
/// The holder is the slot's one referent and the regarded subject is the
|
||||
/// acting subject, so a proposer cannot make a third party hate someone else.
|
||||
/// The delta and the fade are fixed on the variant, like `AdvancePressure`'s
|
||||
/// `by`: a world authoring `insult`, `threaten`, or `gift` sets how far it
|
||||
/// moves regard, within `MAX_ATTITUDE`, and a proposer's hand never does.
|
||||
/// The cause is the invoking command, derived at lowering.
|
||||
AdjustAttitude {
|
||||
delta: i16,
|
||||
decay: Option<TickMinutes>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The referent shape of one operation: the single source of both the
|
||||
|
|
@ -821,7 +835,10 @@ impl ComponentOpKind {
|
|||
// referent to bind, so the action lane authors `Routine` and
|
||||
// `Obligation` and the patch lane authors goals.
|
||||
Self::CreateCommitment { .. } => vec![subject(), subject()],
|
||||
Self::AdvancePressure { .. } | Self::ReducePressure { .. } | Self::ResolvePressure => {
|
||||
Self::AdvancePressure { .. }
|
||||
| Self::ReducePressure { .. }
|
||||
| Self::ResolvePressure
|
||||
| Self::AdjustAttitude { .. } => {
|
||||
vec![subject()]
|
||||
}
|
||||
}
|
||||
|
|
@ -1311,6 +1328,38 @@ pub(crate) enum ComponentOp {
|
|||
source: PressureSourceRef,
|
||||
target: Ref<SubjectId>,
|
||||
},
|
||||
/// A deed changed how `holder` regards `toward`: a negative delta is a
|
||||
/// grievance, a positive one a favor, either named for this command. Adds
|
||||
/// to the modifier this command already wrote, saturating at
|
||||
/// `MAX_ATTITUDE`; `decay` is the span over which the term fades, or
|
||||
/// `None` for a grudge that does not.
|
||||
AdjustAttitude {
|
||||
holder: Ref<SubjectId>,
|
||||
toward: Ref<SubjectId>,
|
||||
delta: i16,
|
||||
decay: Option<TickMinutes>,
|
||||
},
|
||||
/// A regard the world holds without a deed behind it: prejudice toward a
|
||||
/// trait or a person, or an opinion resting on a rumour the holder must
|
||||
/// still believe. This is the dislike a player cannot account for. A
|
||||
/// rumour can only regard a subject, because belief in it is what makes it
|
||||
/// apply to anyone.
|
||||
DeclareAttitude {
|
||||
holder: Ref<SubjectId>,
|
||||
toward: AttitudeTowardRef,
|
||||
delta: i16,
|
||||
basis: AttitudeBasisRef,
|
||||
decay: Option<TickMinutes>,
|
||||
},
|
||||
/// The world's statement that `subject` carries `name`, evidenced by `fact`:
|
||||
/// a species, a faction, a look, a rumour about them. A holder's prejudice
|
||||
/// against the trait applies to the subject only while the holder knows
|
||||
/// that fact.
|
||||
DeclareTrait {
|
||||
subject: Ref<SubjectId>,
|
||||
name: TraitName,
|
||||
fact: Ref<EntityId>,
|
||||
},
|
||||
/// Ends a subject's turn for good: no opportunity, no position, no
|
||||
/// audience, its history kept. Only the owner and `Play` may write it.
|
||||
Retire {
|
||||
|
|
@ -1755,6 +1804,12 @@ pub enum Mismatch {
|
|||
/// A lens weight set with no nonzero weight, at genesis or in
|
||||
/// `SetLensWeights`. A single zero weight is admitted and never draws.
|
||||
LensWeightsNeverDraw,
|
||||
/// An attitude write whose delta is zero or beyond the bound, that regards
|
||||
/// its own holder, or whose rumour names a trait; or a trait name that is
|
||||
/// not `[a-z][a-z0-9_]{0,47}`.
|
||||
InvalidAttitude {
|
||||
site: Site,
|
||||
},
|
||||
/// A jurisdictional author wrote outside its jurisdiction. The owner is
|
||||
/// unconfined and never sees this.
|
||||
OutsideJurisdiction {
|
||||
|
|
@ -2090,6 +2145,19 @@ pub(crate) enum ResolvedOp {
|
|||
source: PressureSource,
|
||||
target: SubjectId,
|
||||
},
|
||||
/// Adds `delta` to the modifier at `key`, saturating, and restamps it.
|
||||
/// Deeds and declarations are the same write at different keys.
|
||||
AdjustAttitude {
|
||||
holder: SubjectId,
|
||||
key: AttitudeKey,
|
||||
delta: i16,
|
||||
decay: Option<TickMinutes>,
|
||||
},
|
||||
DeclareTrait {
|
||||
subject: SubjectId,
|
||||
name: TraitName,
|
||||
fact: EntityId,
|
||||
},
|
||||
Retire {
|
||||
subject: SubjectId,
|
||||
},
|
||||
|
|
@ -2505,7 +2573,7 @@ pub(super) const ACTOR_ROLE: &str = "actor";
|
|||
/// Authority kinds, office names, and grievance kinds share the affordance
|
||||
/// alphabet: world-declared, kernel-opaque, and safe to surface in a generated
|
||||
/// tool description.
|
||||
pub(super) fn is_civic_name(value: &str) -> bool {
|
||||
pub(crate) fn is_civic_name(value: &str) -> bool {
|
||||
is_tool_name(value, 48)
|
||||
}
|
||||
|
||||
|
|
@ -2773,6 +2841,11 @@ fn validate_affordance(
|
|||
{
|
||||
mismatches.push(Mismatch::InvalidCivicName { site: site() });
|
||||
}
|
||||
if let ComponentOpKind::AdjustAttitude { delta, decay } = &slot.op_kind
|
||||
&& (!attitude::is_valid_delta(*delta) || !attitude::is_valid_decay(*decay))
|
||||
{
|
||||
mismatches.push(Mismatch::InvalidAttitude { site: site() });
|
||||
}
|
||||
if slot.roles.len() != arity.len() {
|
||||
mismatches.push(Mismatch::SlotRoleArity {
|
||||
handle: handle.clone(),
|
||||
|
|
@ -3991,6 +4064,130 @@ pub(super) fn resolve_patch(
|
|||
});
|
||||
}
|
||||
}
|
||||
// Attitude writes add to a modifier and saturate, so none can be a
|
||||
// no-op the resolver must predict: the only state they consult is
|
||||
// referents and shape, which is all that is checked here.
|
||||
ComponentOp::AdjustAttitude {
|
||||
holder,
|
||||
toward,
|
||||
delta,
|
||||
decay,
|
||||
} => {
|
||||
let holder_key = resolve_subject(
|
||||
Site::Operation(position),
|
||||
holder,
|
||||
&index,
|
||||
&state.subjects,
|
||||
&mut mismatches,
|
||||
);
|
||||
let toward_key = resolve_subject(
|
||||
Site::Operation(position),
|
||||
toward,
|
||||
&index,
|
||||
&state.subjects,
|
||||
&mut mismatches,
|
||||
);
|
||||
let (Some(holder_key), Some(toward_key)) = (holder_key, toward_key) else {
|
||||
continue;
|
||||
};
|
||||
if !attitude::is_valid_delta(*delta)
|
||||
|| !attitude::is_valid_decay(*decay)
|
||||
|| holder_key == toward_key
|
||||
{
|
||||
mismatches.push(Mismatch::InvalidAttitude {
|
||||
site: Site::Operation(position),
|
||||
});
|
||||
} else if retired.contains(&holder_key) {
|
||||
mismatches.push(Mismatch::RetiredSubjectActed {
|
||||
operation: position,
|
||||
});
|
||||
}
|
||||
}
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder,
|
||||
toward,
|
||||
delta,
|
||||
basis,
|
||||
decay,
|
||||
} => {
|
||||
let holder_key = resolve_subject(
|
||||
Site::Operation(position),
|
||||
holder,
|
||||
&index,
|
||||
&state.subjects,
|
||||
&mut mismatches,
|
||||
);
|
||||
let toward_key = match toward {
|
||||
AttitudeTowardRef::Subject(reference) => resolve_subject(
|
||||
Site::Operation(position),
|
||||
reference,
|
||||
&index,
|
||||
&state.subjects,
|
||||
&mut mismatches,
|
||||
)
|
||||
.map(Some),
|
||||
AttitudeTowardRef::Trait(_) => Some(None),
|
||||
};
|
||||
let basis_resolved = match basis {
|
||||
AttitudeBasisRef::Rumour { fact } => resolve_entity(
|
||||
Site::Operation(position),
|
||||
EntityKind::Fact,
|
||||
fact,
|
||||
&index,
|
||||
&state.entities,
|
||||
&mut mismatches,
|
||||
)
|
||||
.map(|_| ()),
|
||||
AttitudeBasisRef::Prejudice => Some(()),
|
||||
};
|
||||
let (Some(holder_key), Some(toward_key), Some(())) =
|
||||
(holder_key, toward_key, basis_resolved)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let names_bad_trait = matches!(
|
||||
toward,
|
||||
AttitudeTowardRef::Trait(name) if !is_civic_name(&name.0)
|
||||
);
|
||||
let rumour_of_a_trait = matches!(toward, AttitudeTowardRef::Trait(_))
|
||||
&& matches!(basis, AttitudeBasisRef::Rumour { .. });
|
||||
if !attitude::is_valid_delta(*delta)
|
||||
|| !attitude::is_valid_decay(*decay)
|
||||
|| names_bad_trait
|
||||
|| rumour_of_a_trait
|
||||
|| toward_key.as_ref() == Some(&holder_key)
|
||||
{
|
||||
mismatches.push(Mismatch::InvalidAttitude {
|
||||
site: Site::Operation(position),
|
||||
});
|
||||
} else if retired.contains(&holder_key) {
|
||||
mismatches.push(Mismatch::RetiredSubjectActed {
|
||||
operation: position,
|
||||
});
|
||||
}
|
||||
}
|
||||
ComponentOp::DeclareTrait { subject, name, fact } => {
|
||||
let subject_key = resolve_subject(
|
||||
Site::Operation(position),
|
||||
subject,
|
||||
&index,
|
||||
&state.subjects,
|
||||
&mut mismatches,
|
||||
);
|
||||
let fact_key = resolve_entity(
|
||||
Site::Operation(position),
|
||||
EntityKind::Fact,
|
||||
fact,
|
||||
&index,
|
||||
&state.entities,
|
||||
&mut mismatches,
|
||||
);
|
||||
if subject_key.is_some() && fact_key.is_some() && !is_civic_name(&name.0) {
|
||||
mismatches.push(Mismatch::InvalidAttitude {
|
||||
site: Site::Operation(position),
|
||||
});
|
||||
}
|
||||
}
|
||||
ComponentOp::Relocate { subject, via } => {
|
||||
let subject_key = resolve_subject(
|
||||
Site::Operation(position),
|
||||
|
|
@ -5638,6 +5835,50 @@ pub(super) fn resolve_patch(
|
|||
source: pressure_source_of(source),
|
||||
target: subject_id_of(&key_of(target)),
|
||||
},
|
||||
ComponentOp::AdjustAttitude {
|
||||
holder,
|
||||
toward,
|
||||
delta,
|
||||
decay,
|
||||
} => ResolvedOp::AdjustAttitude {
|
||||
holder: subject_id_of(&key_of(holder)),
|
||||
key: AttitudeKey {
|
||||
toward: AttitudeToward::Subject(subject_id_of(&key_of(toward))),
|
||||
cause: attitude::deed_cause(*delta, command_id),
|
||||
},
|
||||
delta: *delta,
|
||||
decay: *decay,
|
||||
},
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder,
|
||||
toward,
|
||||
delta,
|
||||
basis,
|
||||
decay,
|
||||
} => ResolvedOp::AdjustAttitude {
|
||||
holder: subject_id_of(&key_of(holder)),
|
||||
key: AttitudeKey {
|
||||
toward: match toward {
|
||||
AttitudeTowardRef::Subject(reference) => {
|
||||
AttitudeToward::Subject(subject_id_of(&key_of(reference)))
|
||||
}
|
||||
AttitudeTowardRef::Trait(name) => AttitudeToward::Trait(name.clone()),
|
||||
},
|
||||
cause: match basis {
|
||||
AttitudeBasisRef::Prejudice => AttitudeCause::Prejudice,
|
||||
AttitudeBasisRef::Rumour { fact } => AttitudeCause::Rumour {
|
||||
fact: entity_id_of(&key_of(fact)),
|
||||
},
|
||||
},
|
||||
},
|
||||
delta: *delta,
|
||||
decay: *decay,
|
||||
},
|
||||
ComponentOp::DeclareTrait { subject, name, fact } => ResolvedOp::DeclareTrait {
|
||||
subject: subject_id_of(&key_of(subject)),
|
||||
name: name.clone(),
|
||||
fact: entity_id_of(&key_of(fact)),
|
||||
},
|
||||
ComponentOp::Retire { subject } => ResolvedOp::Retire {
|
||||
subject: subject_id_of(&key_of(subject)),
|
||||
},
|
||||
|
|
@ -6114,6 +6355,8 @@ pub(crate) enum PatchFieldKind {
|
|||
Quantity,
|
||||
Cost,
|
||||
Magnitude,
|
||||
/// A signed regard, `-MAX_ATTITUDE..=MAX_ATTITUDE`; zero is refused at resolve.
|
||||
Attitude,
|
||||
Minutes,
|
||||
OptionalPeriod,
|
||||
Evidence,
|
||||
|
|
@ -6143,6 +6386,8 @@ pub(crate) enum CompositeShape {
|
|||
AudienceRef,
|
||||
AuthoredSource,
|
||||
PressureSourceRef,
|
||||
AttitudeToward,
|
||||
AttitudeBasis,
|
||||
CommitmentKey,
|
||||
PreconditionRef,
|
||||
RoleSpec,
|
||||
|
|
@ -6692,6 +6937,51 @@ pub(crate) const PATCH_TOOLS: &[PatchTool] = &[
|
|||
variant: "resolve_pressure",
|
||||
},
|
||||
},
|
||||
PatchTool {
|
||||
name: "adjust_attitude",
|
||||
description: "Record that a deed changed how one subject regards another: a negative delta is a grievance (an insult, a threat, a betrayal, a wreck), a positive one a favor (a gift, a rescue). The regard is what the holder carries into every later meeting, so the holder acts on it. The delta is -100..100; repeated deeds are separate grievances that add up; the optional decay is the number of minutes over which the regard fades, and none is a grudge that stays.",
|
||||
fields: &[
|
||||
field("holder", PatchFieldKind::Reference("subject")),
|
||||
field("toward", PatchFieldKind::Reference("subject")),
|
||||
field("delta", PatchFieldKind::Attitude),
|
||||
field("decay", PatchFieldKind::OptionalPeriod),
|
||||
],
|
||||
shape: PatchToolShape::Operate {
|
||||
variant: "adjust_attitude",
|
||||
},
|
||||
},
|
||||
PatchTool {
|
||||
name: "declare_attitude",
|
||||
description: "Declare a regard that rests on no deed of the player's: prejudice toward a trait (the holder dislikes everyone it learns is an outlander) or toward one person for reasons nobody can name, or an opinion resting on a rumour the holder must still believe. Prejudice toward a trait applies only to subjects the holder knows carry it (see declare_trait). The delta is -100..100.",
|
||||
fields: &[
|
||||
field("holder", PatchFieldKind::Reference("subject")),
|
||||
field(
|
||||
"toward",
|
||||
PatchFieldKind::Composite(CompositeShape::AttitudeToward),
|
||||
),
|
||||
field("delta", PatchFieldKind::Attitude),
|
||||
field(
|
||||
"basis",
|
||||
PatchFieldKind::Composite(CompositeShape::AttitudeBasis),
|
||||
),
|
||||
field("decay", PatchFieldKind::OptionalPeriod),
|
||||
],
|
||||
shape: PatchToolShape::Operate {
|
||||
variant: "declare_attitude",
|
||||
},
|
||||
},
|
||||
PatchTool {
|
||||
name: "declare_trait",
|
||||
description: "Declare that a subject carries a trait (a species, a faction, a look, a rumour about them), evidenced by one fact. A holder's prejudice against the trait reaches the subject only while the holder knows that fact; one who never learned it is untouched.",
|
||||
fields: &[
|
||||
field("subject", PatchFieldKind::Reference("subject")),
|
||||
field("name", PatchFieldKind::Name("the trait's name")),
|
||||
field("fact", PatchFieldKind::Reference("fact")),
|
||||
],
|
||||
shape: PatchToolShape::Operate {
|
||||
variant: "declare_trait",
|
||||
},
|
||||
},
|
||||
PatchTool {
|
||||
name: "retire",
|
||||
description: "Retire a subject for good: no opportunity, no position, no audience, its history kept. Only the owner and the play table may retire.",
|
||||
|
|
@ -6790,6 +7080,10 @@ fn field_schema(kind: PatchFieldKind) -> Value {
|
|||
PatchFieldKind::Quantity => tool_schema::bounded_integer(1, u64::MAX),
|
||||
PatchFieldKind::Cost => tool_schema::bounded_integer(1, u64::from(MAX_ROUTE_COST)),
|
||||
PatchFieldKind::Magnitude => tool_schema::bounded_integer(1, u64::from(u32::MAX)),
|
||||
PatchFieldKind::Attitude => tool_schema::signed_integer(
|
||||
-i64::from(MAX_ATTITUDE),
|
||||
i64::from(MAX_ATTITUDE),
|
||||
),
|
||||
PatchFieldKind::Minutes => tool_schema::described(
|
||||
tool_schema::bounded_integer(0, u64::MAX),
|
||||
"a reading of the world clock in fictional minutes; the prompt states the current reading, and a due must be later than it",
|
||||
|
|
@ -6921,6 +7215,27 @@ fn composite_schema(shape: CompositeShape) -> Value {
|
|||
("subject", Some(subject_ref_schema())),
|
||||
],
|
||||
),
|
||||
CompositeShape::AttitudeToward => tool_schema::variant_content(
|
||||
"toward",
|
||||
"of",
|
||||
vec![
|
||||
("subject", Some(subject_ref_schema())),
|
||||
(
|
||||
"trait",
|
||||
Some(tool_schema::canonical_string("the trait's name")),
|
||||
),
|
||||
],
|
||||
),
|
||||
CompositeShape::AttitudeBasis => tool_schema::variant(
|
||||
"basis",
|
||||
vec![
|
||||
("prejudice", vec![]),
|
||||
(
|
||||
"rumour",
|
||||
vec![("fact".to_owned(), tool_schema::reference("fact"))],
|
||||
),
|
||||
],
|
||||
),
|
||||
CompositeShape::CommitmentKey => tool_schema::object(vec![
|
||||
(
|
||||
"command".to_owned(),
|
||||
|
|
@ -7229,6 +7544,25 @@ fn component_op_kind_schema() -> Value {
|
|||
)],
|
||||
),
|
||||
("resolve_pressure", vec![]),
|
||||
(
|
||||
"adjust_attitude",
|
||||
vec![
|
||||
(
|
||||
"delta".to_owned(),
|
||||
tool_schema::signed_integer(
|
||||
-i64::from(MAX_ATTITUDE),
|
||||
i64::from(MAX_ATTITUDE),
|
||||
),
|
||||
),
|
||||
(
|
||||
"decay".to_owned(),
|
||||
tool_schema::nullable(tool_schema::bounded_integer(
|
||||
1,
|
||||
u64::from(MAX_ROUTE_COST),
|
||||
)),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
|
@ -7248,6 +7582,7 @@ pub(super) fn field_example(kind: PatchFieldKind) -> Value {
|
|||
PatchFieldKind::Statement => json!("The lower hinge flooded."),
|
||||
PatchFieldKind::Quantity | PatchFieldKind::Minutes => json!(7),
|
||||
PatchFieldKind::Cost | PatchFieldKind::Magnitude => json!(3),
|
||||
PatchFieldKind::Attitude => json!(-30),
|
||||
PatchFieldKind::OptionalPeriod => Value::Null,
|
||||
PatchFieldKind::Evidence => json!("vault:example/1"),
|
||||
PatchFieldKind::Flag => json!(false),
|
||||
|
|
@ -7559,6 +7894,9 @@ mod catalog_tests {
|
|||
ComponentOp::AdvancePressure { .. } => "advance_pressure",
|
||||
ComponentOp::ReducePressure { .. } => "reduce_pressure",
|
||||
ComponentOp::ResolvePressure { .. } => "resolve_pressure",
|
||||
ComponentOp::AdjustAttitude { .. } => "adjust_attitude",
|
||||
ComponentOp::DeclareAttitude { .. } => "declare_attitude",
|
||||
ComponentOp::DeclareTrait { .. } => "declare_trait",
|
||||
ComponentOp::Retire { .. } => "retire",
|
||||
ComponentOp::GrantAffordance { .. } => "grant_affordance",
|
||||
ComponentOp::RevokeAffordance { .. } => "revoke_affordance",
|
||||
|
|
|
|||
|
|
@ -1558,6 +1558,42 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
|
|||
out.push_str(" none");
|
||||
}
|
||||
|
||||
// Derived by the kernel from sourced modifiers; the one reading the
|
||||
// Persona's own view and the narrator also draw from. A prejudice toward a
|
||||
// trait shows only once its holder knows the subject carries it.
|
||||
out.push_str("\n Regard (how each subject holds another, with what it rests on):");
|
||||
let mut any_regard = false;
|
||||
for subject in &snapshot.subjects {
|
||||
for held in &subject.opinions {
|
||||
any_regard = true;
|
||||
let toward = label_for_any_id(snapshot, &id_text(held.toward))
|
||||
.unwrap_or_else(|| format!("[{}]", id_text(held.toward)));
|
||||
out.push_str(&format!(
|
||||
" {} [{}] regards {} with {} ({:+}): {};",
|
||||
subject.label,
|
||||
id_text(subject.id),
|
||||
toward,
|
||||
crate::attitude::regard_word(held.total),
|
||||
held.total,
|
||||
joined(
|
||||
held.causes
|
||||
.iter()
|
||||
.map(|cause| crate::attitude::describe_cause(cause, |fact| {
|
||||
snapshot
|
||||
.facts
|
||||
.iter()
|
||||
.find(|entry| entry.id == fact)
|
||||
.map(|entry| entry.statement.as_str().to_owned())
|
||||
}))
|
||||
.collect()
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
if !any_regard {
|
||||
out.push_str(" none");
|
||||
}
|
||||
|
||||
out.push_str("\n Persona material:");
|
||||
let mut any_material = false;
|
||||
for subject in &snapshot.subjects {
|
||||
|
|
|
|||
|
|
@ -47,6 +47,11 @@ pub(super) fn bounded_integer(min: u64, max: u64) -> Value {
|
|||
json!({"type": "integer", "minimum": min, "maximum": max})
|
||||
}
|
||||
|
||||
/// An integer that may be negative, for a regard that can fall as well as rise.
|
||||
pub(super) fn signed_integer(min: i64, max: i64) -> Value {
|
||||
json!({"type": "integer", "minimum": min, "maximum": max})
|
||||
}
|
||||
|
||||
/// The same schema with the text the model reads beside it. Meaning that lives
|
||||
/// only in a prompt paragraph is lost by the time the model fills the field.
|
||||
pub(super) fn described(mut schema: Value, description: &str) -> Value {
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
Loading…
Reference in a new issue