Merge ghostlight-verse/dungeon-consequences: attack/threaten/accuse verbs, witnessing as Seen knowledge, the DM's Open grievances view, revenge obligations (cut-dungeon-consequences r1, report h1; the watch does not yet come, Gestalt seam recorded)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 05:04:04 +01:00
commit 3e95b48d09
6 changed files with 693 additions and 0 deletions

View file

@ -348,6 +348,28 @@ async fn finish(
key: Uuid,
world_id: ghostlight::WorldId,
) -> Result<(), BeginError> {
// The deeds a table is made of are declared before the world opens, and
// granted to every person the draft holds, the player included. A resumed
// Begin finds them declared and goes on.
let draft = current(host)
.await
.map_err(|error| from_mailbox("verbs", error))?
.ok_or_else(|| stopped("verbs", "the world could not be read"))?;
if !draft.affordances.iter().any(|entry| entry.entry.kind.0 == "attack") {
let batch = crate::verbs::install(&draft).map_err(|error| stopped("verbs", error))?;
host.world
.submit_principal(
PrincipalCommandIntent {
id: derived_step_id(key, "verbs")?,
world_id,
expected_revision: draft.revision,
body: CommandBody::AdmitPatch { answers: None, patch: batch.patch },
},
principal,
)
.await
.map_err(|error| from_mailbox("verbs", error))?;
}
for (name, body) in [
("approve", CommandBody::ApproveDraft),
("activate", CommandBody::ActivateWorld),
@ -1052,6 +1074,7 @@ pub(crate) mod tests {
let world = host.world.snapshot().await.unwrap();
assert_eq!(world.phase, WorldPhase::Active);
assert!(world.scale_deficit.is_empty(), "an unseeded Begin states no targets");
assert!(world.affordances.iter().any(|entry| entry.entry.kind.0 == "attack"), "the verbs are declared at Begin");
assert_eq!(rig.status(&begun.timeline).await, None);
let catalog = rig.catalog.lock().await;
assert_eq!(catalog.owned_timeline("alice", &begun.timeline).unwrap().1.snapshot_id, None);

View file

@ -19,6 +19,7 @@ mod test_support;
mod timelines;
mod turn_log;
mod vaults;
mod verbs;
use anyhow::bail;
use std::path::PathBuf;

View file

@ -188,6 +188,11 @@ tool, each `text` an exact quote from their prose. Commit every answer before yo
- 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\
- A deed is state the room holds: when the player acts on someone, commit it through the player's own `attack`, \
`threaten` or `accuse` tool with a `display` quote, so everyone present has seen it. The table \
view lists the open grievances the world has not answered. An office, a victim's kin and the witnesses answer \
through their own people: give them their turns, and rule pressure (`advance_pressure`, from whoever would lean) or \
a sworn reckoning (`create_commitment`, the victim's kin with the doer as counterparty) where you judge the world would.\n\
- Call `end_turn` when the round's consequences are settled.";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]

View file

@ -0,0 +1,398 @@
//! The Dungeon's verbs: the affordance catalog every world Begin makes
//! declares, and the grant of it to every person.
//!
//! A fresh world knows only Speak. A deed the player may attempt but the world
//! cannot lower is a gap, so the Dungeon declares the deeds a table is made of:
//! attack, threaten and accuse. Each lowers to kernel effects the
//! kernel alone writes: regard in the target (`AdjustAttitude`), pressure
//! (`AdvancePressure`). The effects name no consequence
//! beyond the deed. Nothing here refuses a verb on grounds of niceness: a
//! sword is drawn when the preconditions hold (the target is in the room), and
//! what the world does about it is state the table reads, not a rule.
//!
//! A deed carries its witnesses through the kernel's own display lowering: the
//! table commits it with a `display` quote, which becomes a claim the whole room
//! holds as `Seen`. Who saw it is therefore kernel state, and the Open
//! grievances block of the table view is derived from it.
//!
//! What answers a deed is the table's judgement, not a rule here. The table
//! sees who was wronged, who saw it, which forums cover the doer and whether
//! anyone presses or has sworn a reckoning, and gives the office, the kin and
//! the witnesses their own turns, ruling pressure (`advance_pressure`) or a
//! sworn reckoning (`create_commitment`, an obligation with the doer as
//! counterparty: the kernel refuses a goal that has one) where it judges the
//! world would.
//!
//! Seams, recorded rather than patched:
//! - An institution that must react off-screen, with no person of it in the
//! room, is the Gestalt hierarchy's turn (`cut-gestalt-*`, not built). No
//! scheduler stands in for it here.
//! - Verbs are granted to the people a Begin holds. A person an Active
//! elaborator authors later holds only what its author grants by id.
//! - Steal, give, trade, seduce, persuade, flee, hide and move are not
//! declared: a seeded world holds no custody to transfer, and the others
//! lower to speech or to nothing the table cannot already rule.
use ghostlight::{DecodedBatch, SubjectKind, WorldSnapshot, decode_authoring_calls};
use serde_json::{Value, json};
/// The deed kinds this catalog declares, in the order declared.
pub(crate) const VERBS: [&str; 3] = ["attack", "threaten", "accuse"];
fn subject_role() -> Value {
json!({"namespace": "subject", "kind": null})
}
fn adjust(delta: i16) -> Value {
json!({"op_kind": {"op": "adjust_attitude", "delta": delta, "decay": null}, "roles": ["target"], "bounds": {"bound": "none"}})
}
fn colocated_target() -> Value {
json!({"precondition": "can_reach", "subject": "target", "via": "colocated"})
}
/// The declarations, as the authoring calls the Dungeon Master would make.
fn declarations() -> Vec<(&'static str, Value)> {
vec![
(
"declare_affordance",
// Three grades of harm, weighted so a blow usually lands. The
// regard the target holds of the actor falls by the grade; what the
// wound or death means is the table's ruling.
json!({
"handle": "attack",
"kind": "attack",
"roles": [{"role": "target", "kind": subject_role()}],
"preconditions": [colocated_target()],
"effect_slots": [adjust(-35), adjust(-70), adjust(-100)],
"outcome_bands": [
{"weight": 3, "effects": [0]},
{"weight": 3, "effects": [1]},
{"weight": 2, "effects": [2]},
],
"carries_speech": false,
}),
),
(
"declare_affordance",
json!({
"handle": "threaten",
"kind": "threaten",
"roles": [{"role": "target", "kind": subject_role()}],
"preconditions": [colocated_target()],
"effect_slots": [
{"op_kind": {"op": "advance_pressure", "by": 20}, "roles": ["target"], "bounds": {"bound": "none"}},
adjust(-25),
],
"outcome_bands": [{"weight": 1, "effects": [0, 1]}],
"carries_speech": false,
}),
),
(
"declare_affordance",
// A grievance carried to someone who can lean on the accused:
// pressure on the target from the accuser, who must hold the
// charge as something believed. An office answers through its own
// people using this same verb.
json!({
"handle": "accuse",
"kind": "accuse",
"roles": [
{"role": "target", "kind": subject_role()},
{"role": "charge", "kind": {"namespace": "entity", "kind": "fact"}},
],
"preconditions": [{"precondition": "knows", "fact": "charge", "at_least": "believed"}],
"effect_slots": [
{"op_kind": {"op": "advance_pressure", "by": 25}, "roles": ["target"], "bounds": {"bound": "none"}},
],
"outcome_bands": [{"weight": 1, "effects": [0]}],
"carries_speech": false,
}),
),
]
}
/// The one patch that declares the catalog and grants it to every person the
/// world holds. A world that already carries a verb is a replay of this step
/// and is not asked again by the caller.
pub(crate) fn install(world: &WorldSnapshot) -> Result<DecodedBatch, String> {
let mut calls: Vec<(String, String)> = declarations()
.into_iter()
.map(|(name, arguments)| (name.to_owned(), arguments.to_string()))
.collect();
for subject in world
.subjects
.iter()
.filter(|subject| subject.kind == SubjectKind::Person && !subject.retired)
{
for verb in VERBS {
calls.push((
"grant_affordance".to_owned(),
json!({
"subject": {"ref": "existing", "value": subject.id},
"affordance": {"ref": "draft", "value": verb},
})
.to_string(),
));
}
}
let borrowed: Vec<(&str, &str)> = calls.iter().map(|(name, arguments)| (name.as_str(), arguments.as_str())).collect();
decode_authoring_calls(&borrowed)
}
#[cfg(test)]
mod tests {
use super::*;
use ghostlight::{
CommandBody, CommandId, CreateWorldIntent, Lens, LensWeights, PlayPort, PrincipalCommandIntent,
SubjectId, VerifiedPrincipalEvidence, WorldMailbox, decode_actor_call, table_view,
};
use std::collections::BTreeMap;
struct Scenario {
_directory: tempfile::TempDir,
world: WorldMailbox,
principal: VerifiedPrincipalEvidence,
}
fn text(id: SubjectId) -> String {
serde_json::to_value(id).unwrap().as_str().unwrap().to_owned()
}
fn existing(id: impl serde::Serialize) -> Value {
json!({"ref": "existing", "value": id})
}
async fn snapshot(scene: &Scenario) -> ghostlight::WorldSnapshot {
scene.world.snapshot().await.unwrap()
}
fn who(snapshot: &ghostlight::WorldSnapshot, label: &str) -> SubjectId {
snapshot.subjects.iter().find(|subject| subject.label == label).expect("a subject by that label").id
}
async fn submit(scene: &Scenario, body: CommandBody) {
let snapshot = snapshot(scene).await;
scene
.world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
body,
},
&scene.principal,
)
.await
.unwrap();
}
fn batch(calls: &[(&str, Value)]) -> ghostlight::WorldPatch {
let owned: Vec<(&str, String)> = calls.iter().map(|(name, arguments)| (*name, arguments.to_string())).collect();
let borrowed: Vec<(&str, &str)> = owned.iter().map(|(name, arguments)| (*name, arguments.as_str())).collect();
decode_authoring_calls(&borrowed).expect("the calls decode").patch
}
/// The table's own ruling, through the one door the Dungeon Master holds.
async fn rule(scene: &Scenario, calls: &[(&str, Value)]) {
PlayPort::new(scene.world.clone()).submit_patch(CommandId::new(), batch(calls)).await.unwrap();
}
/// A tavern with Dorra, her kin Brannoch and a witness, Grix; the Hold's
/// watch stands at the gate with Hilda. The player, Korr, is in the tavern.
/// Dorra counts Korr a friend, so nothing about the room is hostile.
async fn consequence_world() -> Scenario {
let directory = tempfile::tempdir().unwrap();
let (world, _owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
let principal = VerifiedPrincipalEvidence::new("consequence-scenario", chrono::Utc::now() + chrono::Duration::hours(4));
let receipt = world
.create(
CreateWorldIntent {
id: CommandId::new(),
title: "Consequence Scenario".into(),
brief: "A tavern, a gate and a watch.".into(),
human_subject_label: "Korr".into(),
narrative_persona_label: None,
operational_agent_label: None,
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
era: None,
},
&principal,
)
.await
.unwrap();
let scene = Scenario { _directory: directory, world, principal };
let start = snapshot(&scene).await;
let commons = start.places.iter().find(|place| place.label == "The Commons").unwrap().id;
let speak = start.affordances.iter().find(|entry| entry.entry.kind.0 == "speak").unwrap().id;
let subject = |handle: &str, label: &str, kind: &str, position: Value| {
(
"declare_subject",
json!({
"handle": handle,
"label": label,
"kind": kind,
"controller": {"type": "narrative_persona"},
"affordances": [existing(speak)],
"position": position,
}),
)
};
let patch = batch(&[
("declare_place", json!({"handle": "gate", "label": "The Gate", "container": null})),
(
"declare_route",
json!({"handle": "road", "label": "The Road", "from": existing(commons), "to": {"ref": "draft", "value": "gate"}, "access": {"access": "public"}, "cost": 1}),
),
subject("dorra", "Dorra Ironkettle", "person", existing(commons)),
subject("brann", "Brannoch Deepvein", "person", existing(commons)),
subject("grix", "Grix Sparkfinger", "person", existing(commons)),
subject("hilda", "Hilda Gatewright", "person", json!({"ref": "draft", "value": "gate"})),
subject("watch", "The Deepgate Watch", "institution", json!({"ref": "draft", "value": "gate"})),
]);
submit(&scene, CommandBody::AdmitPatch { answers: None, patch }).await;
let drafted = snapshot(&scene).await;
let (dorra, korr) = (who(&drafted, "Dorra Ironkettle"), who(&drafted, "Korr"));
submit(
&scene,
CommandBody::AdmitPatch {
answers: None,
patch: batch(&[(
"declare_attitude",
json!({"holder": existing(dorra), "toward": {"toward": "subject", "of": existing(korr)}, "delta": 80, "basis": {"basis": "prejudice"}, "decay": null}),
)]),
},
)
.await;
let drafted = snapshot(&scene).await;
submit(&scene, CommandBody::AdmitPatch { answers: None, patch: install(&drafted).unwrap().patch }).await;
submit(&scene, CommandBody::ApproveDraft).await;
submit(&scene, CommandBody::ActivateWorld).await;
let _ = receipt;
scene
}
async fn attack(scene: &Scenario, victim: &str, display: &str) -> Result<(), ghostlight::MailboxError> {
let now = snapshot(scene).await;
let (korr, victim) = (who(&now, "Korr"), who(&now, victim));
let arguments = json!({"target": text(victim), "display": display}).to_string();
let (opportunity, invocation) = decode_actor_call(&now, korr, "", "attack", &arguments).expect("the player may attack");
scene
.world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: now.world_id,
expected_revision: now.revision,
body: CommandBody::ExerciseDecision { opportunity, invocation },
},
&scene.principal,
)
.await
.map(|_| ())
}
const DEED: &str = "Korr buries his axe in Dorra.";
fn open_grievances(view: &str) -> String {
view.split("Open grievances").nth(1).unwrap().split("\n Persona material").next().unwrap().to_owned()
}
fn between<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` not in view")) + from.len();
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
&text[start..end]
}
#[tokio::test]
async fn nothing_forbids_the_sword_and_the_room_sees_it() {
let scene = consequence_world().await;
// Dorra is the player's friend, and the attack is admitted all the same.
attack(&scene, "Dorra Ironkettle", DEED).await.expect("an attack on a friend is admitted");
let view = table_view(&snapshot(&scene).await);
let grievances = open_grievances(&view);
let seen = between(&grievances, "acts seen by:", "forums covering");
for witness in ["Grix Sparkfinger", "Brannoch Deepvein", "Dorra Ironkettle"] {
assert!(seen.contains(witness), "{witness} stands in the room and saw it: {seen}");
}
assert!(!seen.contains("Hilda"), "the gate is out of earshot and out of sight: {seen}");
assert!(grievances.contains("Korr"), "{grievances}");
assert!(grievances.contains("nothing has answered it yet"), "{grievances}");
let subjects = between(&view, "Subjects:", "
Affordances");
let watch = between(subjects, "The Deepgate Watch [", "holdings");
assert!(watch.contains("institution") && !watch.contains("attack"), "an institution is granted no sword: {watch}");
let player = between(subjects, "Korr [", "holdings");
for verb in VERBS {
assert!(player.contains(verb), "the player holds {verb}: {player}");
}
}
#[tokio::test]
async fn an_unseen_world_has_no_open_grievance() {
let scene = consequence_world().await;
assert!(open_grievances(&table_view(&snapshot(&scene).await)).trim().ends_with("none"));
}
#[tokio::test]
async fn word_spreads_law_presses_and_kin_swear() {
let scene = consequence_world().await;
attack(&scene, "Dorra Ironkettle", DEED).await.unwrap();
let now = snapshot(&scene).await;
let view = table_view(&now);
let (korr, grix, hilda, brann) =
(who(&now, "Korr"), who(&now, "Grix Sparkfinger"), who(&now, "Hilda Gatewright"), who(&now, "Brannoch Deepvein"));
let quoted = format!("\"{DEED}\" [");
let deed = between(&view, &quoted, "]").to_owned();
let road = between(&view, "The Road [", "]").to_owned();
assert!(!between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard has not heard");
// The witness walks to the gate and tells the guard.
rule(&scene, &[("relocate", json!({"subject": existing(grix), "via": existing(road)}))]).await;
rule(&scene, &[("communicate", json!({"speaker": existing(grix), "fact": existing(&deed), "to": "colocated"}))]).await;
let view = table_view(&snapshot(&scene).await);
assert!(between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard was told");
// Believing it, the guard regards the killer worse than a stranger.
rule(
&scene,
&[(
"declare_attitude",
json!({"holder": existing(hilda), "toward": {"toward": "subject", "of": existing(korr)}, "delta": -60, "basis": {"basis": "rumour", "fact": existing(&deed)}, "decay": null}),
)],
)
.await;
let view = table_view(&snapshot(&scene).await);
assert!(between(&view, "Regard (", "Persona material").contains("Hilda Gatewright ["), "{view}");
// The law leans on the player, and the grievance is no longer unanswered.
assert!(open_grievances(&view).contains("nothing has answered it yet"));
rule(&scene, &[("advance_pressure", json!({"source": {"from": "subject", "of": existing(hilda)}, "target": existing(korr), "by": 30}))]).await;
let pressed = open_grievances(&table_view(&snapshot(&scene).await));
assert!(between(&pressed, "pressed by:", "reckonings").contains("Hilda Gatewright"), "{pressed}");
assert!(!pressed.contains("nothing has answered it yet"), "{pressed}");
// The victim's kin swear a reckoning with the player as counterparty.
rule(
&scene,
&[(
"create_commitment",
json!({"subject": existing(brann), "counterparty": existing(korr), "kind": "obligation", "due": 600, "period": null, "checks": [], "statement": "Make Korr answer for Dorra."}),
)],
)
.await;
let sworn = open_grievances(&table_view(&snapshot(&scene).await));
assert!(between(&sworn, "reckonings sworn against them:", "answered").contains("Brannoch Deepvein"), "{sworn}");
}
#[test]
fn no_verb_text_refuses_violence() {
let lower = serde_json::to_string(&declarations()).unwrap().to_lowercase();
assert!(!lower.contains("not allowed to attack"));
assert!(lower.find("refuse").is_none_or(|at| !lower[at..].contains("violence")));
assert_eq!(declarations().len(), VERBS.len());
}
}

View file

@ -498,3 +498,173 @@ fn the_derived_opinion_and_its_causes_reach_the_tables_view() {
assert!(line.contains("a grievance (-30)"), "{line}");
assert!(line.contains("prejudice toward the outlander (-40)"), "{line}");
}
/// An act the room saw: the same invocation as `exercise`, with the actor's own
/// words for what everyone present watched.
fn exercise_displaying(
kernel: &mut WorldKernel,
actor: SubjectId,
affordance: AffordanceId,
bindings: Vec<RoleBinding>,
display: &str,
) -> Result<SubmitReceipt, KernelError> {
let snapshot = kernel.snapshot().unwrap();
let opportunity = opportunity_for(&snapshot, actor);
let caller = CallerId::Controller(opportunity.controller_id);
kernel.submit(
command(
&snapshot,
CommandId::new(),
caller.clone(),
CommandBody::ExerciseDecision {
opportunity,
invocation: DecisionInvocation {
affordance,
bindings,
proposed: vec![ProposedEffect {
slot: 0,
magnitude: Magnitude::None,
}],
speech: None,
display: Some(Statement::new(display).unwrap()),
},
},
),
&AuthenticatedCaller::fixture(caller),
)
}
use crate::clock::FictionalMinutes;
use crate::patch::{CommitmentKind, PressureMagnitude};
const BLOW: &str = "The farmer strikes the reeve.";
/// The view's Open grievances block, alone.
fn open_grievances(kernel: &WorldKernel) -> String {
let view = crate::table_view(&kernel.snapshot().unwrap());
view.split("Open grievances")
.nth(1)
.expect("the view always carries the block")
.split("\n Persona material")
.next()
.unwrap()
.to_owned()
}
fn segment<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` missing in {text}")) + from.len();
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
&text[start..end]
}
fn strike(kernel: &mut WorldKernel, clockwork: &Clockwork, delta: i16) {
grant_insult(kernel, clockwork.farmer, delta, None);
let insult = insult_id(kernel);
exercise_displaying(
kernel,
clockwork.farmer,
insult,
vec![binding("target", Target::Subject(clockwork.reeve))],
BLOW,
)
.expect("the blow commits");
}
#[test]
fn a_deed_the_room_saw_is_an_open_grievance_until_something_answers_it() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Open grievances");
assert!(open_grievances(&kernel).trim().ends_with("none"));
strike(&mut kernel, &clockwork, -30);
let block = open_grievances(&kernel);
assert_eq!(block.matches("; acts seen by:").count(), 1, "one doer, no other: {block}");
assert!(block.contains("The Yard Farmer"), "{block}");
assert!(segment(&block, "wronged", ";").contains("The Yard Reeve"), "{block}");
let seen = segment(&block, "acts seen by:", "forums covering");
assert!(seen.contains("The Yard Reeve") && seen.contains(BLOW), "{seen}");
assert!(!seen.contains("The Yard Farmer"), "the doer is not their own witness: {seen}");
assert!(segment(&block, "forums covering them:", ";").contains("none"), "{block}");
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
assert!(segment(&block, "reckonings sworn against them:", ";").contains("none"), "{block}");
assert!(block.contains("nothing has answered it yet"), "{block}");
// Someone leans on the doer: answered, and the pressure is named with its weight.
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::AdvancePressure {
source: PressureSourceRef::Subject(Ref::Existing(clockwork.reeve)),
target: Ref::Existing(clockwork.farmer),
by: PressureMagnitude(30),
}],
evidence: Vec::new(),
},
)
.unwrap();
let block = open_grievances(&kernel);
let pressed = segment(&block, "pressed by:", ";");
assert!(pressed.contains("The Yard Reeve") && pressed.contains("(30)"), "{pressed}");
assert!(block.contains("answered so far") && !block.contains("nothing has answered"), "{block}");
}
#[test]
fn a_sworn_reckoning_answers_a_grievance_and_a_favour_opens_none() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Reckoning");
strike(&mut kernel, &clockwork, -30);
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::CreateCommitment {
subject: Ref::Existing(clockwork.reeve),
counterparty: Some(Ref::Existing(clockwork.farmer)),
kind: CommitmentKind::Obligation,
due: FictionalMinutes(600),
period: None,
checks: Vec::new(),
statement: Statement::new("Make the farmer answer for the blow.").unwrap(),
}],
evidence: Vec::new(),
},
)
.unwrap();
let block = open_grievances(&kernel);
let sworn = segment(&block, "reckonings sworn against them:", "answered");
assert!(sworn.contains("The Yard Reeve") && sworn.contains("Make the farmer answer"), "{sworn}");
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
assert!(block.contains("answered so far"), "{block}");
let directory = tempfile::tempdir().unwrap();
let (mut kindly, clockwork, _) = clock_kernel(directory.path(), "Favour");
strike(&mut kindly, &clockwork, 20);
assert!(open_grievances(&kindly).trim().ends_with("none"), "a favour is no grievance");
}
#[test]
fn a_dislike_nobody_earned_is_no_open_grievance() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Prejudice");
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::DeclareAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
delta: -40,
basis: AttitudeBasisRef::Prejudice,
decay: None,
}],
evidence: Vec::new(),
},
)
.unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -40);
assert!(
open_grievances(&kernel).trim().ends_with("none"),
"a feeling no deed explains wrongs no one"
);
}

View file

@ -983,6 +983,100 @@ fn render_dependency_target(snapshot: &WorldSnapshot, target: &DependencyTarget)
}
}
/// The wrongs the world holds against a subject and what has answered them,
/// read off state and stored nowhere: whom the doer wronged (a grievance in the
/// victim's regard), who saw the doer's acts (`Seen` knowledge), which forums
/// cover the doer, who presses the doer, and who has sworn a reckoning with the
/// doer as counterparty. A grievance nothing answers is named as unanswered:
/// the table's own judgement sends the watch, so what it needs is to see that
/// no one has been sent.
fn render_open_grievances(snapshot: &WorldSnapshot) -> String {
use crate::attitude::AttitudeCause;
use crate::patch::KnowledgeSource;
let name = |id: SubjectId| {
label_for_any_id(snapshot, &id_text(id)).unwrap_or_else(|| format!("[{}]", id_text(id)))
};
let mut out = String::from("\n Open grievances (derived: who was wronged, who saw it, what answers it):");
let mut any = false;
for doer in &snapshot.subjects {
let wronged: Vec<String> = snapshot
.subjects
.iter()
.flat_map(|holder| {
holder
.opinions
.iter()
.filter(|held| held.toward == doer.id)
.filter(|held| {
held.causes
.iter()
.any(|cause| matches!(cause.cause, AttitudeCause::Grievance { .. }) && cause.delta < 0)
})
.map(|held| format!("{} ({:+})", name(holder.id), held.total))
})
.collect();
if wronged.is_empty() {
continue;
}
any = true;
let mut seen_by = Vec::new();
let mut acts = std::collections::BTreeSet::new();
for witness in snapshot.subjects.iter().filter(|witness| witness.id != doer.id) {
for row in &witness.knowledge {
if row.source == (KnowledgeSource::Seen { by: doer.id }) {
seen_by.push(name(witness.id));
acts.insert(format!("\"{}\"", row.statement.as_str()));
}
}
}
seen_by.sort();
seen_by.dedup();
let pressing: Vec<String> = doer
.pressures
.iter()
.filter_map(|pressure| match pressure.source {
PressureSource::Subject(id) => Some(format!("{} ({})", name(id), pressure.magnitude.0)),
_ => None,
})
.collect();
let reckonings: Vec<String> = snapshot
.subjects
.iter()
.flat_map(|holder| {
holder
.commitments
.iter()
.filter(|commitment| commitment.counterparty == Some(doer.id))
.map(move |commitment| format!("{}: \"{}\"", name(holder.id), commitment.statement.as_str()))
})
.collect();
let answered = !pressing.is_empty() || !reckonings.is_empty();
out.push_str(&format!(
" {} wronged {}; acts seen by: {}{}; forums covering them: {}; pressed by: {}; reckonings sworn against them: {}; {}",
name(doer.id),
joined_sorted(wronged),
if seen_by.is_empty() { "no one".to_owned() } else { joined_sorted(seen_by) },
if acts.is_empty() { String::new() } else { format!(" ({})", joined_sorted(acts.into_iter().collect())) },
if doer.redress.is_empty() {
"none".to_owned()
} else {
joined_sorted(doer.redress.iter().map(|forum| render_forum(snapshot, forum)).collect())
},
if pressing.is_empty() { "no one".to_owned() } else { joined_sorted(pressing) },
if reckonings.is_empty() { "none".to_owned() } else { joined_sorted(reckonings) },
if answered {
"answered so far."
} else {
"nothing has answered it yet: no office presses them and no kin or ally has sworn anything. The office, the kin and the witnesses answer through their own people: dispatch them, or rule it with advance_pressure and create_commitment."
},
));
}
if !any {
out.push_str(" none");
}
out
}
/// A pressure source, in the same shape `advance_pressure`/`reduce_pressure`'s
/// `PressureSourceRef` composite takes: a commitment names the promisor
/// subject id and the commitment key; a dependency names its target; a
@ -1594,6 +1688,8 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
out.push_str(" none");
}
out.push_str(&render_open_grievances(snapshot));
out.push_str("\n Persona material:");
let mut any_material = false;
for subject in &snapshot.subjects {