From 59db826aa24c46856b59c490b08b374c3b529a8c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 22 Sep 2026 04:41:29 +0200 Subject: [PATCH] feat: add persistent conflict model --- lib_efo/src/adjudication.rs | 47 ++++-- lib_efo/src/conflict.rs | 278 ++++++++++++++++++++++++++++++++ lib_efo/src/epoch/epoch_info.rs | 6 + lib_efo/src/lib.rs | 1 + lib_efo/src/workspace.rs | 4 + lib_efo/tests/conflict.rs | 140 ++++++++++++++++ 6 files changed, 462 insertions(+), 14 deletions(-) create mode 100644 lib_efo/src/conflict.rs create mode 100644 lib_efo/tests/conflict.rs diff --git a/lib_efo/src/adjudication.rs b/lib_efo/src/adjudication.rs index ec6f00d..eeda3b5 100644 --- a/lib_efo/src/adjudication.rs +++ b/lib_efo/src/adjudication.rs @@ -584,23 +584,33 @@ pub fn apply_to_world( limit: config.max_records, }); } - world.find_entity_strict(report.source, Some(EntityType::Event))?; + let source_is_event = world + .find_entity_strict(report.source, Some(EntityType::Event)) + .is_ok(); + if !source_is_event && !world.conflicts.contains_key(&report.source) { + return Err(AdjudicationError::Invalid(format!( + "source @{} is neither an event nor a conflict", + report.source + ))); + } let mut updated = world.clone(); let target = updated.find_entity_strict_as_mut(report.target, Some(target_type))?; apply_to_target(report, target)?; updated.adjudications.insert(report.id, report.clone()); - updated.event_adjudications.insert( - report.source, - EventAdjudicationState { - potency_basis_points: report.source_potency_after, - destroyed: report.disposition == AdjudicationDisposition::Destroyed, - last_record: report.id, - }, - ); - if report.disposition == AdjudicationDisposition::Destroyed - && let Some(diffusion) = updated.diffusions.get_mut(&report.source) - { - diffusion.expired = true; + if source_is_event { + updated.event_adjudications.insert( + report.source, + EventAdjudicationState { + potency_basis_points: report.source_potency_after, + destroyed: report.disposition == AdjudicationDisposition::Destroyed, + last_record: report.id, + }, + ); + if report.disposition == AdjudicationDisposition::Destroyed + && let Some(diffusion) = updated.diffusions.get_mut(&report.source) + { + diffusion.expired = true; + } } Ok(updated) } @@ -630,7 +640,16 @@ pub fn validate_adjudications(world: &EpochInfo) -> Result<(), AdjudicationError report.id ))); } - world.find_entity_strict(report.source, Some(EntityType::Event))?; + if world + .find_entity_strict(report.source, Some(EntityType::Event)) + .is_err() + && !world.conflicts.contains_key(&report.source) + { + return Err(AdjudicationError::Invalid(format!( + "record @{} refers to missing source @{}", + report.id, report.source + ))); + } world.find_entity_strict(report.target, None)?; let unique = report .changes diff --git a/lib_efo/src/conflict.rs b/lib_efo/src/conflict.rs new file mode 100644 index 0000000..67acb73 --- /dev/null +++ b/lib_efo/src/conflict.rs @@ -0,0 +1,278 @@ +//! Persistent, multi-side fight and war state. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::{epoch::EpochInfo, stats::EntityType}; + +/// Stable ruleset used by this release. +pub const DEFAULT_CONFLICT_RULESET: &str = "epoch-forge/conflict-gm-1"; + +/// Whether a conflict is a bounded fight or persistent war. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "snake_case")] +pub enum ConflictKind { + /// Normally completes after its first adjudicated round. + Fight, + /// Continues until one side remains, a stalemate is declared, or it is ended. + War, +} + +/// Conflict lifecycle state. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum ConflictStatus { + /// Created but not advanced. + Planned, + /// At least one war round has completed and multiple sides remain. + Active, + /// No winner was produced. + Stalemate, + /// One named side remains. + Won { + /// Winning side label. + side: String, + }, + /// Explicitly ended by the game master. + Ended { + /// Human explanation. + reason: String, + }, +} + +impl ConflictStatus { + /// Whether another round may be adjudicated. + pub fn can_advance(&self) -> bool { + matches!(self, Self::Planned | Self::Active) + } +} + +/// Stable participant reference; normal entities are never owned or deleted. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ParticipantRef { + /// Stored entity collection. + pub entity_type: EntityType, + /// Stable entity identity. + pub id: Uuid, + /// User-defined coalition label. + pub side: String, + /// Relative commitment for future rulesets. + pub committed_weight: u32, + /// Whether an adjudication removed this participant from the conflict. + #[serde(default)] + pub removed: bool, +} + +/// One immutable-in-spirit conflict round audit entry. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ConflictRound { + /// Monotonic one-based round number. + pub number: u64, + /// Adjudication record IDs produced for participants. + pub records: Vec, +} + +/// Persisted generic conflict. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ConflictState { + /// Stable identity. + pub id: Uuid, + /// Human name. + pub name: String, + /// Fight or war behavior. + pub kind: ConflictKind, + /// Participants in deterministic UUID order. + pub participants: Vec, + /// Number of applied rounds. + pub round: u64, + /// Current lifecycle state. + pub status: ConflictStatus, + /// Versioned resolution policy. + pub ruleset_id: String, + /// Applied round history keyed by number. + #[serde(default)] + pub rounds: BTreeMap, +} + +/// Invalid conflict input or transition. +#[derive(Debug, thiserror::Error)] +pub enum ConflictError { + /// Semantic invariant failed. + #[error("invalid conflict: {0}")] + Invalid(String), + /// Requested conflict does not exist. + #[error("conflict `{0}` was not found; run `efo conflict list`")] + Missing(String), +} + +/// Validate and create a planned conflict. +pub fn create_conflict( + world: &EpochInfo, + id: Uuid, + name: String, + kind: ConflictKind, + mut participants: Vec, +) -> Result { + participants.sort_unstable_by_key(|participant| participant.id); + let conflict = ConflictState { + id, + name, + kind, + participants, + round: 0, + status: ConflictStatus::Planned, + ruleset_id: DEFAULT_CONFLICT_RULESET.into(), + rounds: BTreeMap::new(), + }; + validate_conflict(world, &conflict)?; + Ok(conflict) +} + +/// Validate every persisted conflict and cross-reference. +pub fn validate_conflicts(world: &EpochInfo) -> Result<(), ConflictError> { + for (key, conflict) in &world.conflicts { + if key != &conflict.id { + return Err(ConflictError::Invalid(format!( + "map key @{key} does not match conflict @{}", + conflict.id + ))); + } + validate_conflict(world, conflict)?; + } + Ok(()) +} + +/// Resolve a conflict by exact ID or unambiguous case-insensitive name prefix. +pub fn find_conflict<'a>( + world: &'a EpochInfo, + selector: &str, +) -> Result<&'a ConflictState, ConflictError> { + let matches = world + .conflicts + .values() + .filter(|conflict| { + selector + .strip_prefix('@') + .is_some_and(|id| conflict.id.to_string().starts_with(id)) + || conflict + .name + .to_lowercase() + .starts_with(&selector.to_lowercase()) + }) + .collect::>(); + match matches.as_slice() { + [conflict] => Ok(conflict), + [] => Err(ConflictError::Missing(selector.into())), + _ => Err(ConflictError::Invalid(format!( + "selector `{selector}` is ambiguous; use @UUID" + ))), + } +} + +/// Record a round and derive its deterministic lifecycle result. +pub fn finish_round( + conflict: &mut ConflictState, + records: Vec, + removed: &HashSet, +) -> Result<(), ConflictError> { + if !conflict.status.can_advance() { + return Err(ConflictError::Invalid(format!( + "{} is already finished", + conflict.name + ))); + } + let number = conflict.round.saturating_add(1); + if conflict.rounds.contains_key(&number) { + return Err(ConflictError::Invalid(format!( + "round {number} is already recorded" + ))); + } + for participant in &mut conflict.participants { + participant.removed |= removed.contains(&participant.id); + } + let remaining = conflict + .participants + .iter() + .filter(|participant| !participant.removed) + .map(|participant| participant.side.clone()) + .collect::>(); + conflict.round = number; + conflict + .rounds + .insert(number, ConflictRound { number, records }); + conflict.status = match remaining.len() { + 0 => ConflictStatus::Stalemate, + 1 => ConflictStatus::Won { + side: remaining.into_iter().next().unwrap_or_default(), + }, + _ if conflict.kind == ConflictKind::Fight => ConflictStatus::Stalemate, + _ => ConflictStatus::Active, + }; + Ok(()) +} + +/// Validate one conflict independently of map identity. +fn validate_conflict(world: &EpochInfo, conflict: &ConflictState) -> Result<(), ConflictError> { + if conflict.name.trim().is_empty() { + return Err(ConflictError::Invalid("name cannot be empty".into())); + } + if conflict.ruleset_id != DEFAULT_CONFLICT_RULESET { + return Err(ConflictError::Invalid(format!( + "unsupported ruleset `{}`", + conflict.ruleset_id + ))); + } + if conflict.participants.len() < 2 { + return Err(ConflictError::Invalid( + "at least two participants are required".into(), + )); + } + let mut ids = HashSet::new(); + let mut sides = BTreeSet::new(); + for participant in &conflict.participants { + if participant.entity_type == EntityType::Player { + return Err(ConflictError::Invalid( + "player is not a stored entity type".into(), + )); + } + if !ids.insert(participant.id) + || participant.side.trim().is_empty() + || participant.committed_weight == 0 + { + return Err(ConflictError::Invalid( + "participants must have unique IDs, non-empty sides, and positive weights".into(), + )); + } + world + .find_entity_strict(participant.id, Some(participant.entity_type)) + .map_err(|error| ConflictError::Invalid(error.to_string()))?; + if !participant.removed { + sides.insert(participant.side.as_str()); + } + } + if conflict.round == 0 && sides.len() < 2 { + return Err(ConflictError::Invalid( + "at least two active sides are required".into(), + )); + } + if conflict.rounds.len() != usize::try_from(conflict.round).unwrap_or(usize::MAX) + || conflict.rounds.keys().copied().ne(1..=conflict.round) + { + return Err(ConflictError::Invalid( + "round history is not contiguous".into(), + )); + } + if conflict + .rounds + .values() + .flat_map(|round| &round.records) + .any(|record| !world.adjudications.contains_key(record)) + { + return Err(ConflictError::Invalid( + "round refers to a missing adjudication record".into(), + )); + } + Ok(()) +} diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index 7654f4d..b9e15b5 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -14,6 +14,7 @@ use uuid::Uuid; use crate::{ adjudication::{AdjudicationReport, EventAdjudicationState}, + conflict::ConflictState, entity::{Entity, EntityIdentifier}, epoch::{ EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList, @@ -105,6 +106,10 @@ pub struct EpochInfo { #[serde(default)] #[table(skip)] pub event_adjudications: BTreeMap, + /// Persistent fights and wars keyed by stable conflict UUID. + #[serde(default)] + #[table(skip)] + pub conflicts: BTreeMap, } impl Prettiable for EpochInfo {} @@ -129,6 +134,7 @@ impl Default for EpochInfo { diffusions: BTreeMap::new(), adjudications: BTreeMap::new(), event_adjudications: BTreeMap::new(), + conflicts: BTreeMap::new(), } } } diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index ed89ff2..6d7ead6 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -15,6 +15,7 @@ use crate::epoch::EpochInfo; #[allow(unused_assignments)] pub mod error; pub mod adjudication; +pub mod conflict; pub mod diff; pub mod entity; pub mod epoch; diff --git a/lib_efo/src/workspace.rs b/lib_efo/src/workspace.rs index ba52596..2124f27 100644 --- a/lib_efo/src/workspace.rs +++ b/lib_efo/src/workspace.rs @@ -12,6 +12,7 @@ use uuid::Uuid; use crate::{ adjudication::validate_adjudications, + conflict::validate_conflicts, entity::EntityIdentifier, epoch::{EntityIndex, EpochInfo}, repository_format::{FormatError, RepositoryManifest, RepositorySnapshot, decode_manifest}, @@ -824,6 +825,7 @@ fn copy_world_metadata(source: &EpochInfo, destination: &mut EpochInfo) { destination.summary = source.summary.clone(); destination.adjudications = source.adjudications.clone(); destination.event_adjudications = source.event_adjudications.clone(); + destination.conflicts = source.conflicts.clone(); } /// Validate stable identity, collection type, and relationship targets. @@ -834,6 +836,8 @@ fn validate_world(label: &str, world: &EpochInfo) -> Result<(), WorkspaceError> .map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?; validate_adjudications(world) .map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?; + validate_conflicts(world) + .map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?; let index = EntityIndex::build(world); if !index.duplicate_ids().is_empty() { return Err(WorkspaceError::Inconsistent(format!( diff --git a/lib_efo/tests/conflict.rs b/lib_efo/tests/conflict.rs new file mode 100644 index 0000000..5c0b203 --- /dev/null +++ b/lib_efo/tests/conflict.rs @@ -0,0 +1,140 @@ +use std::collections::HashSet; + +use lib_efo::{ + conflict::{ + ConflictKind, ConflictStatus, ParticipantRef, create_conflict, finish_round, + validate_conflicts, + }, + entity::Entity, + epoch::EpochInfo, + stats::EntityType, +}; +use uuid::Uuid; + +fn entity(id: u128, kind: EntityType, name: &str) -> Entity { + let mut entity = Entity::default(); + entity.id = Uuid::from_u128(id); + entity.entity_type = kind; + entity.name = name.into(); + entity +} + +fn world() -> EpochInfo { + let mut world = EpochInfo::default(); + world.towns.push(entity(1, EntityType::Town, "Haven")); + world + .organizations + .push(entity(2, EntityType::Organization, "Guild")); + world + .characters + .push(entity(3, EntityType::Character, "Aria")); + world +} + +fn participant(id: u128, kind: EntityType, side: &str) -> ParticipantRef { + ParticipantRef { + entity_type: kind, + id: Uuid::from_u128(id), + side: side.into(), + committed_weight: 1, + removed: false, + } +} + +#[test] +fn mixed_two_and_three_side_conflicts_validate_independently_of_insertion_order() { + let world = world(); + let a = create_conflict( + &world, + Uuid::from_u128(20), + "The Crossing".into(), + ConflictKind::War, + vec![ + participant(3, EntityType::Character, "third"), + participant(1, EntityType::Town, "red"), + participant(2, EntityType::Organization, "blue"), + ], + ) + .expect("valid conflict"); + let b = create_conflict( + &world, + Uuid::from_u128(20), + "The Crossing".into(), + ConflictKind::War, + vec![ + participant(2, EntityType::Organization, "blue"), + participant(1, EntityType::Town, "red"), + participant(3, EntityType::Character, "third"), + ], + ) + .expect("valid reordered conflict"); + assert_eq!(a, b); +} + +#[test] +fn fights_stalemate_and_wars_continue_or_select_the_remaining_side() { + let world = world(); + let participants = vec![ + participant(1, EntityType::Town, "red"), + participant(2, EntityType::Organization, "blue"), + ]; + let mut fight = create_conflict( + &world, + Uuid::from_u128(20), + "Fight".into(), + ConflictKind::Fight, + participants.clone(), + ) + .expect("fight"); + finish_round(&mut fight, Vec::new(), &HashSet::new()).expect("round"); + assert_eq!(fight.status, ConflictStatus::Stalemate); + + let mut war = create_conflict( + &world, + Uuid::from_u128(21), + "War".into(), + ConflictKind::War, + participants, + ) + .expect("war"); + finish_round(&mut war, Vec::new(), &HashSet::new()).expect("round"); + assert_eq!(war.status, ConflictStatus::Active); + finish_round(&mut war, Vec::new(), &HashSet::from([Uuid::from_u128(2)])) + .expect("decisive round"); + assert_eq!(war.status, ConflictStatus::Won { side: "red".into() }); +} + +#[test] +fn malformed_participants_and_cross_references_are_rejected() { + let mut world = world(); + let duplicate = vec![ + participant(1, EntityType::Town, "red"), + participant(1, EntityType::Town, "blue"), + ]; + assert!( + create_conflict( + &world, + Uuid::from_u128(20), + "Bad".into(), + ConflictKind::Fight, + duplicate + ) + .is_err() + ); + + let conflict = create_conflict( + &world, + Uuid::from_u128(20), + "Valid".into(), + ConflictKind::Fight, + vec![ + participant(1, EntityType::Town, "red"), + participant(2, EntityType::Organization, "blue"), + ], + ) + .expect("valid"); + world.conflicts.insert(conflict.id, conflict); + validate_conflicts(&world).expect("valid world conflicts"); + world.organizations.clear(); + assert!(validate_conflicts(&world).is_err()); +}