From 0e9999fa18d9cb8a6566494cd0497c8538cb5d18 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 22 Sep 2026 02:28:46 +0200 Subject: [PATCH] feat: add deterministic influx rules --- AGENTS-TASKS.md | 4 +- docs/issue-audit.md | 2 +- docs/resolution-conflict-design.md | 6 +- docs/simulation-worldgen-design.md | 12 +- lib_efo/assets/simulation/README.md | 18 + lib_efo/assets/simulation/default.json | 32 ++ lib_efo/src/influx.rs | 543 +++++++++++++++++++++++++ lib_efo/src/lib.rs | 1 + lib_efo/tests/influx.rs | 272 +++++++++++++ scripts/package-simulation-config.sh | 24 ++ 10 files changed, 903 insertions(+), 11 deletions(-) create mode 100644 lib_efo/assets/simulation/README.md create mode 100644 lib_efo/assets/simulation/default.json create mode 100644 lib_efo/src/influx.rs create mode 100644 lib_efo/tests/influx.rs create mode 100755 scripts/package-simulation-config.sh diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index 7a2afff..c51a39d 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -226,9 +226,9 @@ and [`docs/presentation-design.md`](docs/presentation-design.md). - [x] Approve the shared prework contract in `docs/resolution-conflict-design.md`. -- [ ] Add a separately versioned, embedded `SimulationConfig` with strict +- [x] Add a separately versioned, embedded `SimulationConfig` with strict validation, external replacement, safety limits, and release packaging. -- [ ] Implement all six stable `InfluxLevel` values, configured pressure bands, +- [x] Implement all six stable `InfluxLevel` values, configured pressure bands, deterministic target sub-seeds, resistance, attenuation, and typed reports. - [ ] Persist idempotent, stale-state-checked resolution records with workspace and historical `fsck` validation. diff --git a/docs/issue-audit.md b/docs/issue-audit.md index 265c5fb..1ae33c8 100644 --- a/docs/issue-audit.md +++ b/docs/issue-audit.md @@ -18,7 +18,7 @@ absent. | [#12 Add fight/war](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/12) | Not implemented. The implementation-ready design uses generic multi-side conflict records and reuses deterministic influx resolution. | Deliver after the influx engine and diffusion integration; see `resolution-conflict-design.md`. | | [#11 Epoch Diffing](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/11) | Addressed: epoch and layer comparisons share a deterministic, serializable typed diff with changed-field details and importance classification. | Extend the type rather than parsing terminal output when structured formats arrive. | | [#10 Display functions](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/10) | Partially addressed: unified `show`, entity detail, and diff rendering are buffered. Most commands and several legacy library helpers still print directly; saving/structured output is absent. | Implement the renderer/sink migration and acceptance inventory in `presentation-design.md`. | -| [#9 Adding influx](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9) | Not implemented. All six levels, deterministic rolls, avoidance/destruction, attenuation, configuration, records, CLI, and tests now have an approved prework contract. | Implement slices 1–3 of `resolution-conflict-design.md`. | +| [#9 Adding influx](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9) | Foundation implemented: versioned embedded/override rules, all six levels, deterministic target-isolated rolls, weighted pressure/resistance, four outcomes, attenuation, and serializable typed reports. Persistence and CLI remain open. | Persist idempotent resolution records, then implement preview/apply/show/clear. | | [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Partially addressed: deterministic road/direct town frontiers, affected sets, expiry, previewed ticks, and reversible application exist. Influx-aware outcomes, protected-town avoidance, and character targeting remain. | Integrate the shared resolution engine using the explicit #8 acceptance gates in `resolution-conflict-design.md`. | | [#6 HashMap/HashSet](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/6) | Addressed without format churn: `EntityIndex` provides ephemeral UUID/name hash indexes and duplicate-ID detection over the stable vector representation. Repository validation uses the index and hash lookup for relationships. | Rebuild indexes after mutation; never persist them. | diff --git a/docs/resolution-conflict-design.md b/docs/resolution-conflict-design.md index bd11a1b..272b357 100644 --- a/docs/resolution-conflict-design.md +++ b/docs/resolution-conflict-design.md @@ -276,8 +276,9 @@ upgrade path under issue #17. ## Delivery slices -1. Add and validate `SimulationConfig`, `InfluxLevel`, typed reports, and - deterministic sub-seeding; no commands or mutation. +1. **Complete:** add and validate `SimulationConfig`, `InfluxLevel`, typed + reports, deterministic sub-seeding, and reproducible release packaging; no + commands or mutation. 2. Add pure influx preview/resolution tests for every outcome and level. 3. Persist idempotent resolution records and expose preview/apply/show/clear. 4. Integrate resolution into diffusion towns, then resident/positioned @@ -287,4 +288,3 @@ upgrade path under issue #17. 7. Run default and portable gates, corruption fixtures, help snapshots, and release builds; update the live tracker only after each issue's acceptance gates pass. - diff --git a/docs/simulation-worldgen-design.md b/docs/simulation-worldgen-design.md index 9d0d85a..b481f25 100644 --- a/docs/simulation-worldgen-design.md +++ b/docs/simulation-worldgen-design.md @@ -100,11 +100,13 @@ can follow that mechanism once the Jenkins credential ID used by the release job is known. Routine CI must validate/package the config but must not publish or run release-only badge tooling. -The repository provides `scripts/package-worldgen-config.sh VERSION` and an -explicit `scripts/upload-worldgen-config.sh TAG ZIP`. The upload helper requires -`GITEA_TOKEN`; Jenkins should bind its existing release credential to that -environment variable only inside a tag-release stage. It is never invoked by -the routine Jenkinsfile. +The repository provides `scripts/package-worldgen-config.sh VERSION` and +`scripts/package-simulation-config.sh VERSION`; both create reproducible +archives from embedded defaults. The explicit +`scripts/upload-worldgen-config.sh TAG ZIP` helper can upload either archive. +It requires `GITEA_TOKEN`; Jenkins should bind its existing release credential +to that environment variable only inside a tag-release stage. It is never +invoked by the routine Jenkinsfile. ## Safety and test gates diff --git a/lib_efo/assets/simulation/README.md b/lib_efo/assets/simulation/README.md new file mode 100644 index 0000000..9e442de --- /dev/null +++ b/lib_efo/assets/simulation/README.md @@ -0,0 +1,18 @@ +# Epoch Forge simulation configuration + +`default.json` is the complete configuration embedded in the corresponding +Epoch Forge release. Pass an edited complete replacement to future simulation +commands with `--config PATH`; unknown fields and invalid ranges are rejected. + +The schema version is independent from the repository and application +versions. It defines: + +- the six canonical influx pressure bands; +- source-pressure, target-resistance, and proposed-effect stat weights in basis + points (`10000` means one whole unit per stat unit); +- the deterministic roll interval; +- strictly ordered destroyed, avoided, dampened, and affected thresholds; +- dampened attenuation and defensive allocation limits. + +Keep `ruleset_id` stable while semantics remain identical. Change it whenever +an edited configuration should not be mistaken for the embedded ruleset. diff --git a/lib_efo/assets/simulation/default.json b/lib_efo/assets/simulation/default.json new file mode 100644 index 0000000..f8f31c0 --- /dev/null +++ b/lib_efo/assets/simulation/default.json @@ -0,0 +1,32 @@ +{ + "schema_version": { "major": 1, "minor": 0 }, + "ruleset_id": "epoch-forge/default-1", + "levels": [ + { "level": "apocalypse", "min": -120, "max": -91 }, + { "level": "worsen", "min": -90, "max": -56 }, + { "level": "bad", "min": -55, "max": -21 }, + { "level": "mid", "min": -20, "max": 34 }, + { "level": "good", "min": 35, "max": 79 }, + { "level": "excellent", "min": 80, "max": 120 } + ], + "source_weights": [ + { "stat": "threat", "basis_points": 2500 }, + { "stat": "strength", "basis_points": 2500 } + ], + "resistance_weights": [ + { "stat": "fortification", "basis_points": 2500 }, + { "stat": "health", "basis_points": 2500 } + ], + "effects": [ + { "stat": "health", "basis_points": 5000 }, + { "stat": "happiness", "basis_points": 2500 } + ], + "roll": { "min": -10, "max": 10 }, + "thresholds": { + "destroyed_max": -80, + "avoided_max": -30, + "dampened_max": 20, + "dampened_basis_points": 5000 + }, + "limits": { "max_targets": 10000, "max_records": 100000 } +} diff --git a/lib_efo/src/influx.rs b/lib_efo/src/influx.rs new file mode 100644 index 0000000..b9945d5 --- /dev/null +++ b/lib_efo/src/influx.rs @@ -0,0 +1,543 @@ +//! Versioned, deterministic influx resolution shared by events and conflicts. + +use std::{collections::BTreeSet, fs, path::Path}; + +use rand::{Rng, SeedableRng, rngs::StdRng}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::{ + entity::Entity, + repository_format::FormatVersion, + stats::{ListStats, OverallStats}, +}; + +/// Configuration schema understood by this build. +pub const CURRENT_SIMULATION_CONFIG_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 }; +/// Offline-safe canonical simulation rules. +pub const DEFAULT_SIMULATION_CONFIG_JSON: &str = include_str!("../assets/simulation/default.json"); + +/// Compatibility vocabulary for event intensity and polarity. +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + clap::ValueEnum, +)] +#[serde(rename_all = "snake_case")] +pub enum InfluxLevel { + /// Exceptional beneficial pressure. + Excellent, + /// Beneficial pressure. + Good, + /// Weak or mixed pressure. + #[value(alias = "medium")] + Mid, + /// Harmful pressure. + Bad, + /// Strongly harmful or escalating pressure. + #[value(alias = "worse")] + Worsen, + /// Extreme harmful pressure. + Apocalypse, +} + +/// Supported persisted statistic names for configurable rules. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StatName { + /// Population count or modifier. + Population, + /// Population growth rate. + GrowthRate, + /// Crime. + Crime, + /// Happiness. + Happiness, + /// Food. + Food, + /// Industry. + Industry, + /// Science. + Science, + /// Trade. + Trade, + /// Army. + Army, + /// Strength. + Strength, + /// Fortification. + Fortification, + /// Threat. + Threat, + /// Bureaucracy. + Bureaucracy, + /// Transportation. + Transportation, + /// Sprawl. + Sprawl, + /// Health. + Health, +} + +impl StatName { + /// Convert to the existing statistics selector. + fn list_stat(self) -> ListStats { + match self { + Self::Population => ListStats::Population, + Self::GrowthRate => ListStats::Growthrate, + Self::Crime => ListStats::Crime, + Self::Happiness => ListStats::Happiness, + Self::Food => ListStats::Food, + Self::Industry => ListStats::Industry, + Self::Science => ListStats::Science, + Self::Trade => ListStats::Trade, + Self::Army => ListStats::Army, + Self::Strength => ListStats::Strength, + Self::Fortification => ListStats::Fortification, + Self::Threat => ListStats::Threat, + Self::Bureaucracy => ListStats::Bureaucracy, + Self::Transportation => ListStats::Transportation, + Self::Sprawl => ListStats::Sprawl, + Self::Health => ListStats::Health, + } + } +} + +/// Inclusive pressure range for one influx level. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct InfluxBand { + /// Level configured by this row. + pub level: InfluxLevel, + /// Inclusive minimum pressure. + pub min: isize, + /// Inclusive maximum pressure. + pub max: isize, +} + +/// Weighted statistic contribution in basis points. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StatWeight { + /// Statistic to read. + pub stat: StatName, + /// Multiplier where 10,000 is one whole unit per stat unit. + pub basis_points: isize, +} + +/// Deterministic bounded-roll configuration. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RollRange { + /// Inclusive minimum roll. + pub min: isize, + /// Inclusive maximum roll. + pub max: isize, +} + +/// Ordered outcome thresholds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OutcomeThresholds { + /// Largest margin that exhausts the source. + pub destroyed_max: isize, + /// Largest margin that the target completely avoids. + pub avoided_max: isize, + /// Largest margin that produces a dampened effect. + pub dampened_max: isize, + /// Dampened effect multiplier in basis points. + pub dampened_basis_points: isize, +} + +/// Allocation limits enforced before resolution. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SimulationLimits { + /// Largest accepted target set. + pub max_targets: usize, + /// Largest accepted persisted record collection. + pub max_records: usize, +} + +/// Complete versioned deterministic simulation rules. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SimulationConfig { + /// Independent configuration schema version. + pub schema_version: FormatVersion, + /// Stable identifier recorded in reports. + pub ruleset_id: String, + /// Exactly one pressure band per influx level. + pub levels: Vec, + /// Source statistics added to pressure. + pub source_weights: Vec, + /// Target statistics added to resistance. + pub resistance_weights: Vec, + /// Proposed target changes derived from resolved pressure. + pub effects: Vec, + /// Bounded random contribution. + pub roll: RollRange, + /// Outcome decision thresholds. + pub thresholds: OutcomeThresholds, + /// Defensive allocation limits. + pub limits: SimulationLimits, +} + +/// Configuration or resolution failure. +#[derive(Debug, thiserror::Error)] +pub enum InfluxError { + /// Reading an external configuration failed. + #[error("cannot read simulation config `{path}`: {source}")] + Io { + /// Affected path. + path: std::path::PathBuf, + /// Filesystem error. + #[source] + source: std::io::Error, + }, + /// JSON did not match the configuration schema. + #[error("invalid simulation config `{path}`: {source}")] + Json { + /// Embedded label or external path. + path: std::path::PathBuf, + /// Decode error. + #[source] + source: serde_json::Error, + }, + /// Semantic validation rejected otherwise valid JSON. + #[error("invalid simulation configuration: {0}")] + Invalid(String), +} + +impl SimulationConfig { + /// Load and validate the embedded offline rules. + pub fn embedded() -> Result { + Self::decode( + DEFAULT_SIMULATION_CONFIG_JSON.as_bytes(), + Path::new(""), + ) + } + + /// Load and validate a complete external replacement. + pub fn load(path: &Path) -> Result { + let bytes = fs::read(path).map_err(|source| InfluxError::Io { + path: path.to_owned(), + source, + })?; + Self::decode(&bytes, path) + } + + /// Decode bytes with source-aware diagnostics. + pub fn decode(bytes: &[u8], path: &Path) -> Result { + let config: Self = serde_json::from_slice(bytes).map_err(|source| InfluxError::Json { + path: path.to_owned(), + source, + })?; + config.validate()?; + Ok(config) + } + + /// Validate schema, ranges, thresholds, weights, and allocation limits. + pub fn validate(&self) -> Result<(), InfluxError> { + if self.schema_version != CURRENT_SIMULATION_CONFIG_VERSION { + return Err(InfluxError::Invalid(format!( + "schema {} is unsupported; expected {}", + self.schema_version, CURRENT_SIMULATION_CONFIG_VERSION + ))); + } + if self.ruleset_id.trim().is_empty() || self.ruleset_id.len() > 128 { + return Err(InfluxError::Invalid( + "ruleset_id must contain 1..=128 characters".into(), + )); + } + let expected = [ + InfluxLevel::Excellent, + InfluxLevel::Good, + InfluxLevel::Mid, + InfluxLevel::Bad, + InfluxLevel::Worsen, + InfluxLevel::Apocalypse, + ]; + let found = self + .levels + .iter() + .map(|band| band.level) + .collect::>(); + if found != BTreeSet::from(expected) || self.levels.len() != expected.len() { + return Err(InfluxError::Invalid( + "levels must contain each influx level exactly once".into(), + )); + } + for band in &self.levels { + if band.min > band.max || band.min < -120 || band.max > 120 { + return Err(InfluxError::Invalid(format!( + "{:?} pressure must be ordered within -120..=120", + band.level + ))); + } + } + let mut ordered = self.levels.clone(); + ordered.sort_unstable_by_key(|band| band.min); + if ordered.windows(2).any(|pair| pair[0].max >= pair[1].min) { + return Err(InfluxError::Invalid( + "influx pressure bands must not overlap".into(), + )); + } + for (label, weights) in [ + ("source_weights", &self.source_weights), + ("resistance_weights", &self.resistance_weights), + ("effects", &self.effects), + ] { + if weights.len() > 64 + || weights + .iter() + .any(|weight| weight.basis_points.unsigned_abs() > 10_000) + { + return Err(InfluxError::Invalid(format!( + "{label} must contain at most 64 weights within -10000..=10000 basis points" + ))); + } + let unique = weights + .iter() + .map(|weight| weight.stat) + .collect::>(); + if unique.len() != weights.len() { + return Err(InfluxError::Invalid(format!( + "{label} contains a duplicate statistic" + ))); + } + } + if self.roll.min > self.roll.max || self.roll.min < -120 || self.roll.max > 120 { + return Err(InfluxError::Invalid( + "roll must be ordered within -120..=120".into(), + )); + } + let thresholds = self.thresholds; + if !(thresholds.destroyed_max < thresholds.avoided_max + && thresholds.avoided_max < thresholds.dampened_max) + || !(0..=10_000).contains(&thresholds.dampened_basis_points) + { + return Err(InfluxError::Invalid( + "outcome thresholds must be strictly ordered and attenuation within 0..=10000" + .into(), + )); + } + if self.limits.max_targets == 0 + || self.limits.max_targets > 1_000_000 + || self.limits.max_records == 0 + || self.limits.max_records > 10_000_000 + { + return Err(InfluxError::Invalid( + "simulation limits are zero or exceed hard safety limits".into(), + )); + } + Ok(()) + } + + /// Find the pressure band for one level after validation. + fn band(&self, level: InfluxLevel) -> InfluxBand { + self.levels + .iter() + .find(|band| band.level == level) + .copied() + .unwrap_or(InfluxBand { + level, + min: 0, + max: 0, + }) + } +} + +/// Repeat behavior requested by a resolution caller. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RepeatPolicy { + /// Refuse a duplicate persisted source/target/tick record. + Once, + /// Permit a new explicitly identified resolution. + Allow, +} + +/// Stable inputs for one influx resolution. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InfluxSpec { + /// Configured severity/polarity. + pub level: InfluxLevel, + /// User-visible deterministic seed. + pub seed: u64, + /// Event or conflict source UUID. + pub source: Uuid, + /// Ruleset expected by the caller. + pub ruleset_id: String, + /// Duplicate application policy. + pub repeat_policy: RepeatPolicy, +} + +/// Resolution classification. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ResolutionOutcome { + /// Full configured effect. + Affected, + /// Reduced configured effect. + Dampened, + /// Target completely resisted the effect. + Avoided, + /// Resistance exhausted the source. + Destroyed, +} + +/// One typed projected statistic delta. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProposedChange { + /// Statistic to modify. + pub stat: StatName, + /// Signed delta before target-domain clamping. + pub delta: isize, +} + +/// Pure deterministic explanation and proposed effects for one target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolutionReport { + /// Stable deterministic record identity. + pub id: Uuid, + /// Source identity. + pub source: Uuid, + /// Target identity. + pub target: Uuid, + /// Simulation tick or conflict round. + pub tick_or_round: u64, + /// User-visible root seed. + pub seed: u64, + /// Pressure selected from the influx band. + pub base_pressure: isize, + /// Weighted source-stat contribution. + pub source_contribution: isize, + /// Weighted target resistance. + pub resistance: isize, + /// Deterministic bounded roll. + pub roll: isize, + /// Final pressure minus resistance. + pub margin: isize, + /// Classified result. + pub outcome: ResolutionOutcome, + /// Applied effect multiplier in basis points. + pub attenuation_basis_points: isize, + /// Typed proposed target changes. + pub proposed_changes: Vec, + /// Ruleset used for this report. + pub ruleset_id: String, +} + +/// Resolve one target without mutating either entity or repository state. +pub fn resolve( + config: &SimulationConfig, + spec: &InfluxSpec, + source: &Entity, + target: &Entity, + tick_or_round: u64, +) -> Result { + config.validate()?; + if spec.source != source.id { + return Err(InfluxError::Invalid( + "influx source UUID does not match the supplied entity".into(), + )); + } + if spec.ruleset_id != config.ruleset_id { + return Err(InfluxError::Invalid(format!( + "requested ruleset `{}` does not match `{}`", + spec.ruleset_id, config.ruleset_id + ))); + } + let sub_seed = resolution_seed(spec.seed, source.id, target.id, tick_or_round); + let mut rng = StdRng::seed_from_u64(sub_seed); + let band = config.band(spec.level); + let base_pressure = rng.random_range(band.min as i64..=band.max as i64) as isize; + let source_contribution = weighted(source.get_stats(), &config.source_weights); + let resistance = weighted(target.get_stats(), &config.resistance_weights); + let roll = rng.random_range(config.roll.min as i64..=config.roll.max as i64) as isize; + let margin = base_pressure + .saturating_add(source_contribution) + .saturating_add(roll) + .saturating_sub(resistance); + let (outcome, attenuation_basis_points) = if margin <= config.thresholds.destroyed_max { + (ResolutionOutcome::Destroyed, 0) + } else if margin <= config.thresholds.avoided_max { + (ResolutionOutcome::Avoided, 0) + } else if margin <= config.thresholds.dampened_max { + ( + ResolutionOutcome::Dampened, + config.thresholds.dampened_basis_points, + ) + } else { + (ResolutionOutcome::Affected, 10_000) + }; + let proposed_changes = config + .effects + .iter() + .map(|effect| ProposedChange { + stat: effect.stat, + delta: scale( + scale(base_pressure, effect.basis_points), + attenuation_basis_points, + ), + }) + .filter(|change| change.delta != 0) + .collect(); + Ok(ResolutionReport { + id: resolution_id(sub_seed, source.id, target.id), + source: source.id, + target: target.id, + tick_or_round, + seed: spec.seed, + base_pressure, + source_contribution, + resistance, + roll, + margin, + outcome, + attenuation_basis_points, + proposed_changes, + ruleset_id: config.ruleset_id.clone(), + }) +} + +/// Sum weighted implemented statistics with saturating arithmetic. +fn weighted(stats: &OverallStats, weights: &[StatWeight]) -> isize { + weights.iter().fold(0_isize, |total, weight| { + total.saturating_add(scale( + **stats.get_field(&weight.stat.list_stat()), + weight.basis_points, + )) + }) +} + +/// Apply a basis-point multiplier with saturating multiplication. +fn scale(value: isize, basis_points: isize) -> isize { + value.saturating_mul(basis_points) / 10_000 +} + +/// Derive an iteration-independent seed from stable resolution inputs. +fn resolution_seed(seed: u64, source: Uuid, target: Uuid, tick_or_round: u64) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325_u64 ^ seed ^ tick_or_round.rotate_left(17); + for byte in source.as_bytes().iter().chain(target.as_bytes()) { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash +} + +/// Produce a stable UUID without consuming external randomness. +fn resolution_id(seed: u64, source: Uuid, target: Uuid) -> Uuid { + let high = resolution_seed(seed, source, target, 0); + let low = resolution_seed(seed.rotate_left(29), target, source, 1); + Uuid::from_u128((u128::from(high) << 64) | u128::from(low)) +} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 7df0920..9f81ee4 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -17,6 +17,7 @@ pub mod error; pub mod diff; pub mod entity; pub mod epoch; +pub mod influx; pub mod naming; pub mod output; pub mod repository_format; diff --git a/lib_efo/tests/influx.rs b/lib_efo/tests/influx.rs new file mode 100644 index 0000000..9f8888b --- /dev/null +++ b/lib_efo/tests/influx.rs @@ -0,0 +1,272 @@ +use std::{fs, path::Path}; + +use lib_efo::{ + entity::Entity, + influx::{ + InfluxLevel, InfluxSpec, OutcomeThresholds, RepeatPolicy, ResolutionOutcome, + SimulationConfig, StatName, StatWeight, resolve, + }, + stats::{EntityType, ListStats, Modification, StatPair}, +}; +use uuid::Uuid; + +fn entity(id: u128, kind: EntityType, stats: &[(ListStats, isize)]) -> Entity { + let mut entity = Entity::default(); + entity.id = Uuid::from_u128(id); + entity.name = format!("entity-{id}"); + entity.entity_type = kind; + for (stat, value) in stats { + entity.change_stat_strict( + StatPair { + stat: *stat, + value: (*value).into(), + }, + Modification::Replace, + ); + } + entity.update_metastats(); + entity +} + +fn spec(config: &SimulationConfig, level: InfluxLevel, seed: u64) -> InfluxSpec { + InfluxSpec { + level, + seed, + source: Uuid::from_u128(1), + ruleset_id: config.ruleset_id.clone(), + repeat_policy: RepeatPolicy::Once, + } +} + +#[test] +fn embedded_config_covers_every_level_and_external_files_are_complete_replacements() { + let config = SimulationConfig::embedded().expect("embedded config"); + for level in [ + InfluxLevel::Excellent, + InfluxLevel::Good, + InfluxLevel::Mid, + InfluxLevel::Bad, + InfluxLevel::Worsen, + InfluxLevel::Apocalypse, + ] { + assert_eq!( + config + .levels + .iter() + .filter(|band| band.level == level) + .count(), + 1 + ); + } + + let directory = tempfile::tempdir().expect("tempdir"); + let path = directory.path().join("simulation.json"); + fs::write(&path, serde_json::to_vec_pretty(&config).expect("encode")).expect("write"); + assert_eq!(SimulationConfig::load(&path).expect("external"), config); + assert!(SimulationConfig::load(Path::new("/definitely/missing/config.json")).is_err()); +} + +#[test] +fn semantic_validation_rejects_every_unsafe_configuration_family() { + let config = SimulationConfig::embedded().expect("config"); + let mut invalid = config.clone(); + invalid.levels.pop(); + assert!(invalid.validate().is_err()); + + let mut invalid = config.clone(); + invalid.levels[0].max = invalid.levels[1].min; + assert!(invalid.validate().is_err()); + + let mut invalid = config.clone(); + invalid.roll.min = 5; + invalid.roll.max = -5; + assert!(invalid.validate().is_err()); + + let mut invalid = config.clone(); + invalid.thresholds.avoided_max = invalid.thresholds.destroyed_max; + assert!(invalid.validate().is_err()); + + let mut invalid = config.clone(); + invalid.source_weights[0].basis_points = isize::MIN; + assert!(invalid.validate().is_err()); + + let mut invalid = config.clone(); + invalid.source_weights.push(invalid.source_weights[0]); + assert!(invalid.validate().is_err()); + + let mut invalid = config; + invalid.limits.max_targets = 0; + assert!(invalid.validate().is_err()); +} + +#[test] +fn reports_are_serializable_and_mismatched_inputs_fail_before_resolution() { + let config = SimulationConfig::embedded().expect("config"); + let source = entity(1, EntityType::Event, &[]); + let target = entity(2, EntityType::Town, &[]); + let report = resolve( + &config, + &spec(&config, InfluxLevel::Good, 12), + &source, + &target, + 4, + ) + .expect("report"); + let encoded = serde_json::to_vec(&report).expect("serialize"); + let decoded: lib_efo::influx::ResolutionReport = + serde_json::from_slice(&encoded).expect("deserialize"); + assert_eq!(decoded, report); + + let mut wrong_source = spec(&config, InfluxLevel::Good, 12); + wrong_source.source = Uuid::from_u128(99); + assert!(resolve(&config, &wrong_source, &source, &target, 4).is_err()); + let mut wrong_rules = spec(&config, InfluxLevel::Good, 12); + wrong_rules.ruleset_id = "unknown".into(); + assert!(resolve(&config, &wrong_rules, &source, &target, 4).is_err()); +} + +#[test] +fn every_level_stays_inside_its_pressure_band_and_replays_exactly() { + let config = SimulationConfig::embedded().expect("config"); + let source = entity(1, EntityType::Event, &[]); + let target = entity(2, EntityType::Town, &[]); + for band in &config.levels { + for seed in 0..128 { + let first = resolve( + &config, + &spec(&config, band.level, seed), + &source, + &target, + 7, + ) + .expect("resolution"); + let replay = resolve( + &config, + &spec(&config, band.level, seed), + &source, + &target, + 7, + ) + .expect("replay"); + assert_eq!(first, replay); + assert!((band.min..=band.max).contains(&first.base_pressure)); + } + } +} + +#[test] +fn stable_target_subseeds_are_independent_of_resolution_order() { + let config = SimulationConfig::embedded().expect("config"); + let source = entity(1, EntityType::Event, &[(ListStats::Threat, 40)]); + let targets = [ + entity(2, EntityType::Town, &[(ListStats::Health, 10)]), + entity(3, EntityType::Town, &[(ListStats::Health, 80)]), + ]; + let forward = targets + .iter() + .map(|target| { + resolve( + &config, + &spec(&config, InfluxLevel::Bad, 42), + &source, + target, + 3, + ) + .expect("forward") + }) + .collect::>(); + let reverse = targets + .iter() + .rev() + .map(|target| { + resolve( + &config, + &spec(&config, InfluxLevel::Bad, 42), + &source, + target, + 3, + ) + .expect("reverse") + }) + .collect::>(); + assert_eq!(forward[0], reverse[1]); + assert_eq!(forward[1], reverse[0]); + assert_ne!(forward[0].id, forward[1].id); +} + +#[test] +fn thresholds_produce_all_four_outcomes_and_typed_effects() { + let base = SimulationConfig::embedded().expect("config"); + let source = entity(1, EntityType::Event, &[]); + let target = entity(2, EntityType::Town, &[]); + for (expected, attenuation) in [ + (ResolutionOutcome::Destroyed, 0), + (ResolutionOutcome::Avoided, 0), + (ResolutionOutcome::Dampened, 5_000), + (ResolutionOutcome::Affected, 10_000), + ] { + let mut config = base.clone(); + config.roll.min = 0; + config.roll.max = 0; + config.source_weights.clear(); + config.resistance_weights.clear(); + config.effects = vec![StatWeight { + stat: StatName::Health, + basis_points: 10_000, + }]; + let pressure = resolve( + &config, + &spec(&config, InfluxLevel::Mid, 9), + &source, + &target, + 0, + ) + .expect("pressure") + .base_pressure; + config.thresholds = match expected { + ResolutionOutcome::Destroyed => OutcomeThresholds { + destroyed_max: pressure, + avoided_max: pressure + 1, + dampened_max: pressure + 2, + dampened_basis_points: 5_000, + }, + ResolutionOutcome::Avoided => OutcomeThresholds { + destroyed_max: pressure - 1, + avoided_max: pressure, + dampened_max: pressure + 1, + dampened_basis_points: 5_000, + }, + ResolutionOutcome::Dampened => OutcomeThresholds { + destroyed_max: pressure - 2, + avoided_max: pressure - 1, + dampened_max: pressure, + dampened_basis_points: 5_000, + }, + ResolutionOutcome::Affected => OutcomeThresholds { + destroyed_max: pressure - 3, + avoided_max: pressure - 2, + dampened_max: pressure - 1, + dampened_basis_points: 5_000, + }, + }; + let report = resolve( + &config, + &spec(&config, InfluxLevel::Mid, 9), + &source, + &target, + 0, + ) + .expect("outcome"); + assert_eq!(report.outcome, expected); + assert_eq!(report.attenuation_basis_points, attenuation); + if attenuation == 0 { + assert!(report.proposed_changes.is_empty()); + } else { + assert_eq!(report.proposed_changes[0].stat, StatName::Health); + assert_eq!( + report.proposed_changes[0].delta, + pressure * attenuation / 10_000 + ); + } + } +} diff --git a/scripts/package-simulation-config.sh b/scripts/package-simulation-config.sh new file mode 100755 index 0000000..8ce5092 --- /dev/null +++ b/scripts/package-simulation-config.sh @@ -0,0 +1,24 @@ +#!/bin/sh +set -eu + +version="${1:-0.1.0}" +output="${2:-epoch-forge-simulation-config-v${version}.zip}" +case "$output" in + /*) ;; + *) output="$PWD/$output" ;; +esac + +if ! command -v zip >/dev/null 2>&1; then + echo "error: zip is required to package simulation configuration" >&2 + exit 1 +fi + +package_dir="$(mktemp -d)" +trap 'rm -rf "$package_dir"' EXIT HUP INT TERM +cp lib_efo/assets/simulation/default.json "$package_dir/default.json" +cp lib_efo/assets/simulation/README.md "$package_dir/README.md" +touch -t 200001010000 "$package_dir/default.json" "$package_dir/README.md" +(cd "$package_dir" && sha256sum default.json README.md > SHA256SUMS) +touch -t 200001010000 "$package_dir/SHA256SUMS" +(cd "$package_dir" && zip -X "$output" default.json README.md SHA256SUMS) +echo "Created $output"