Merge ghostlight-verse/dungeon-attitude-state: regard as sourced modifiers with derived opinion, trait-gated prejudice, AdjustAttitude/DeclareAttitude/DeclareTrait, opinion in DM, Persona and narrator views (cut-dungeon-attitude-state r1, report h1; mutation pass pending)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 03:53:27 +01:00
commit 06b9520b4d
13 changed files with 1684 additions and 20 deletions

View file

@ -130,6 +130,9 @@ const PLAY_TOOLS: &[&str] = &[
"discharge_commitment",
"advance_pressure",
"reduce_pressure",
"adjust_attitude",
"declare_attitude",
"declare_trait",
"open_route",
"close_route",
"declare_place",
@ -182,6 +185,9 @@ are not furniture. When the player speaks to someone, give that person their own
one `react` call. A person's turn comes back as prose that is only a draft: it is in the world, and so \
heard by the player, only once you commit what they said and did through their own `<handle>__speak` \
tool, each `text` an exact quote from their prose. Commit every answer before you end the turn.\n\
- A deed that changes how someone regards another is state: record it with `adjust_attitude`, so the regard is \
carried into every later meeting. A regard held with no deed behind it is `declare_attitude`, and the trait it turns \
on is `declare_trait`.\n\
- Call `end_turn` when the round's consequences are settled.";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -11378,6 +11384,9 @@ pub(crate) mod tests {
"discharge_commitment",
"advance_pressure",
"reduce_pressure",
"adjust_attitude",
"declare_attitude",
"declare_trait",
"open_route",
"close_route",
"declare_place",
@ -11391,7 +11400,7 @@ pub(crate) mod tests {
"revoke_affordance",
];
assert_eq!(PLAY_TOOLS, EXPECTED);
assert_eq!(PLAY_TOOLS.len(), 24);
assert_eq!(PLAY_TOOLS.len(), 27);
assert!(!PLAY_TOOLS.contains(&"communicate"));
}

View file

@ -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,
}
}

View 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})"),
},
}
}

View 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 hatred (-70)"), "{line}");
assert!(line.contains("(-70)"), "{line}");
assert!(line.contains("a grievance (-30)"), "{line}");
assert!(line.contains("prejudice toward the outlander (-40)"), "{line}");
}

View file

@ -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}");
}
}

View file

@ -1763,7 +1763,7 @@ const SEED_NAMESPACE: &str = "ghostlight.command.seed.v1";
/// seeded out of goals alone therefore activates with nothing for the Active
/// elaborator to answer, so this instruction requires an obligation, not a
/// goal alone, from every subject it authors.
const SEED_INSTRUCTIONS: &str = "Use only the supplied tools to author living structure inside your jurisdiction. A subject counts only when it has a controller, at least one affordance grant, and holds a goal commitment. A goal alone is not enough structure: every person and institution you author must also hold at least one obligation commitment with a counterparty, because a goal carries no counterparty and derives no boundary for the world's Active elaborator to answer. Author the shortfall you were given in as few responses as you can, making several tool calls per response, and finish with submit_patch as your last call; a session that ends without it keeps only what was authored. Recording a gap changes nothing. Every promise carries a statement of what is promised; both parties will read it. Give every person material with set_persona_material: how they speak, what they hold to, what they remember, and how they read each subject they are bound to. A person with no material has no rendered inner life and will say nothing.";
const SEED_INSTRUCTIONS: &str = "Use only the supplied tools to author living structure inside your jurisdiction. A subject counts only when it has a controller, at least one affordance grant, and holds a goal commitment. A goal alone is not enough structure: every person and institution you author must also hold at least one obligation commitment with a counterparty, because a goal carries no counterparty and derives no boundary for the world's Active elaborator to answer. Author the shortfall you were given in as few responses as you can, making several tool calls per response, and finish with submit_patch as your last call; a session that ends without it keeps only what was authored. Recording a gap changes nothing. Every promise carries a statement of what is promised; both parties will read it. Give every person material with set_persona_material: how they speak, what they hold to, what they remember, and how they read each subject they are bound to. A person with no material has no rendered inner life and will say nothing. People hold regards of their own: where a person or an institution distrusts a kind of person (a species, a faction, a look, a rumoured sin), declare the trait on those who carry it with declare_trait, evidenced by a fact, and the prejudice with declare_attitude; it reaches only those who come to know the trait.";
/// The row a session answers, plus the ancestry it was built against. There is
/// no `PatchAnswer` here: a seed answers nothing, and giving this session an
@ -2432,7 +2432,7 @@ fn build_seed_prompt(
}
prompt.push_str(&render_clock(snapshot));
prompt.push_str(
"\nA subject qualifies only when it has a controller, at least one affordance grant, and holds a goal commitment. Declare people, institutions, and populations who want something; give each a controller, grants, a position, and a goal. Give them the rest of a life: routines and obligations that recur, counterparties, channels they speak on and who controls them, authority and the offices that lend it, holdings and the dependencies those holdings serve, routes between the places they move through. A goal that nobody can hold the subject to is allowed and expected; the world's elaborator answers that gap later, so do not write it into a promise.\nEvery promise states what is promised, in the promisor's own words. Every person carries material (set_persona_material): a voice, two or three values, a few memories, and a read of each counterparty, all distinct from every other person's; without it the person has no inner life to speak from.\nYou may not declare a human-controlled subject: only the world's first person is human, and that was genesis.\n\n",
"\nA subject qualifies only when it has a controller, at least one affordance grant, and holds a goal commitment. Declare people, institutions, and populations who want something; give each a controller, grants, a position, and a goal. Give them the rest of a life: routines and obligations that recur, counterparties, channels they speak on and who controls them, authority and the offices that lend it, holdings and the dependencies those holdings serve, routes between the places they move through. A goal that nobody can hold the subject to is allowed and expected; the world's elaborator answers that gap later, so do not write it into a promise.\nEvery promise states what is promised, in the promisor's own words. Every person carries material (set_persona_material): a voice, two or three values, a few memories, and a read of each counterparty, all distinct from every other person's; without it the person has no inner life to speak from.\nPeople also carry regards no deed explains: a prejudice against a kind of person (declare_trait on those who carry it, evidenced by a fact; declare_attitude for the prejudice) reaches only those who come to know the trait.\nYou may not declare a human-controlled subject: only the world's first person is human, and that was genesis.\n\n",
);
prompt.push_str(&super::table::render_world_structure(snapshot));
prompt.push('\n');

View file

@ -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"
);
}
}
}

View file

@ -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.

View file

@ -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),
@ -7461,7 +7796,7 @@ mod catalog_tests {
.iter()
.filter(|entry| matches!(entry.shape, PatchToolShape::Operate { .. }))
.count();
assert_eq!((declarations, operations, PATCH_TOOLS.len()), (7, 34, 43));
assert_eq!((declarations, operations, PATCH_TOOLS.len()), (7, 37, 46));
// Every declaration variant the vocabulary owns is reachable, and the
// two payload-carrying entity kinds are not exposed as an `Entity`
@ -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",
@ -7616,7 +7954,7 @@ mod catalog_tests {
.count();
assert_eq!(
(declare_tools, operate_tools, PATCH_TOOLS.len()),
(7, 34, 43)
(7, 37, 46)
);
let declarations = every_declaration();
@ -7816,16 +8154,26 @@ mod catalog_tests {
let inner = schema.get("items").unwrap_or(&Value::Null);
items.iter().all(|item| admits(inner, item))
}),
Some("integer") => value.as_u64().is_some_and(|number| {
schema
.get("minimum")
.and_then(Value::as_u64)
.is_none_or(|minimum| number >= minimum)
&& schema
.get("maximum")
.and_then(Value::as_u64)
.is_none_or(|maximum| number <= maximum)
}),
Some("integer") => {
// Signed as well as unsigned: a regard may be negative, and
// `u64::MAX` ceilings still need to fit.
let wide = |number: &Value| {
number
.as_i64()
.map(i128::from)
.or_else(|| number.as_u64().map(i128::from))
};
wide(value).is_some_and(|number| {
schema
.get("minimum")
.and_then(wide)
.is_none_or(|minimum| number >= minimum)
&& schema
.get("maximum")
.and_then(wide)
.is_none_or(|maximum| number <= maximum)
})
}
Some("boolean") => value.is_boolean(),
Some("string") => value.is_string(),
Some("null") => value.is_null(),

View file

@ -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 {

View file

@ -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 {

View file

@ -442,6 +442,8 @@ which noun a component is; it cares what it constrains.
| `Channel` | channel: reach set, controller (latency arrives with the clock, pass 7) | how facts travel; who can be silenced |
| `Commitment` | subject → counterparty: kind (`Routine`, `Obligation`, `Goal`), due, period, statement | obligation with a clock; autonomous motion |
| `Pressure` | source → target: magnitude | the causal boundary trigger |
| `Attitude` | holder → subject or trait: signed delta, cause, since, decay | how one subject regards another; sourced modifiers, never a stored opinion |
| `Trait` | subject → trait name: the facts that evidence it | what a prejudice may reach, once the holder knows one of them |
| `PersonaMaterial` | subject: values, voice, memories, reads | lived meaning; never authority |
A `Fact` carries a `standing` (`FactStanding`, three variants): `Canonical`
@ -451,6 +453,23 @@ belief. Deception is a subject asserting a claim while holding a contradicting
canonical fact; misread is a listener acquiring a claim the speaker did not
intend. Both are ordinary typed states, not narrator judgments.
Attitude is a sum of sourced terms, in the manner of Crusader Kings opinion
modifiers. A modifier points at a subject or at a trait, carries a delta in
`-100..=100`, a cause (`Prejudice`, `Grievance` or `Favor` named for the command
that did the deed, or a `Rumour` over a fact), the clock at its last write, and an
optional fade. `attitude::opinion(holder, subject)` derives the regard on demand:
the direct modifiers, plus each trait modifier whose trait the subject carries
*and* whose evidencing fact the holder knows at `Believed` or better, summed and
clamped. A prejudice against outlanders does nothing to a stranger the holder
has not learned is one. `Trait` rows are declared by the world, never inferred.
The regard is projected to every reader from that one derivation: each subject's
snapshot, the table view the Dungeon Master reads, the Persona's own view, and
the narrator's account of who stands with the player. Only the reducer writes it,
through `AdjustAttitude` (a deed, or an affordance effect, whose regarded party is
fixed to the actor), `DeclareAttitude` (prejudice or rumour, authored without a
deed) and `DeclareTrait`. The three are additive on the state: a world with no
attitude serializes as it did before, so the state schema tag did not move.
Civic order is the `Authority` + `Selection` + `Redress` + `Custody` subgraph.
It is not a prose manifest and needs no civic verdict. `Dependency` is the
crisis transmitter: it is what makes a failed pump in one realm a political
@ -460,7 +479,7 @@ problem in another without anyone deciding that it should be.
This is the closed operation set. Every mutation the kernel applies is one of
these, and every model-facing tool is a projection of one of these. The type is
`ComponentOp` in `crates/ghostlight/src/patch.rs`: 34 variants, named here by
`ComponentOp` in `crates/ghostlight/src/patch.rs`: 37 variants, named here by
the component they act on. Declarations are the six `Declaration` variants.
```text
@ -478,6 +497,7 @@ Knowledge AcquireKnowledge, Communicate, Witness, Forget
Channel SetReach, SetController
Commitment CreateCommitment, DischargeCommitment
Pressure AdvancePressure, ReducePressure, ResolvePressure
Attitude AdjustAttitude, DeclareAttitude, DeclareTrait
PersonaMaterial SetPersonaMaterial
Retirement Retire
Affordance GrantAffordance, RevokeAffordance

File diff suppressed because one or more lines are too long