feat: add deterministic configured world generation
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-09-21 02:17:44 +02:00
parent 4a8af40dc6
commit 79ce7f84d3
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
15 changed files with 593 additions and 8 deletions

View File

@ -29,9 +29,11 @@ prototype reader, migration command, fixtures, and compatibility aliases are
removed. Future evolution uses explicit `1.x` major/minor versions. Default
and portable quality and release gates passed on 2026-09-21.
**Milestone 7 — deterministic worldgen foundation: planned.** The spatial,
**Milestone 7 — deterministic worldgen foundation: complete.** The spatial,
fuzzing, configuration, rendering, and release-asset contract is approved in
[`docs/simulation-worldgen-design.md`](docs/simulation-worldgen-design.md).
Embedded and override configuration, deterministic generation, safe CLI apply,
packaging, and default/portable release gates passed on 2026-09-21.
## Phase 0 — audit and guardrails
@ -160,15 +162,15 @@ fuzzing, configuration, rendering, and release-asset contract is approved in
- [x] Define cumulative event/settlement/region/world generation levels.
- [x] Choose embedded defaults plus explicit local `--config` overrides.
- [x] Define seeded reproducibility, preview/apply behavior, and restoration.
- [ ] Add a versioned `WorldGenConfig` with strict semantic validation.
- [ ] Move canonical defaults to `lib_efo/assets/worldgen/default.json` and
- [x] Add a versioned `WorldGenConfig` with strict semantic validation.
- [x] Move canonical defaults to `lib_efo/assets/worldgen/default.json` and
embed them in the library.
- [ ] Generate deterministic IDs, positions, names, events, and entity counts
- [x] Generate deterministic IDs, positions, names, events, and entity counts
from a caller-supplied seed without thread-local randomness.
- [ ] Add `efo gen world --level ... --seed ... [--config ...] [--apply]` with
- [x] Add `efo gen world --level ... --seed ... [--config ...] [--apply]` with
preview as the default and worktree-only application.
- [ ] Add seed-replay, invalid-config, invariant, and CLI reversal tests.
- [ ] Package the editable config and schema notes as a reproducible zip;
- [x] Add seed-replay, invalid-config, invariant, and CLI reversal tests.
- [x] Package the editable config and schema notes as a reproducible zip;
document the Gitea release upload endpoint without publishing in routine CI.
### Checkpoint 2 — roads, residency, and travel
@ -242,6 +244,8 @@ These require user approval and are not part of the current implementation:
- After pre-release format consolidation, all 88 default-feature tests, 84
portable-output tests, strict Clippy, and both release builds passed on
2026-09-21.
- The worldgen foundation raised coverage to 93 default-feature tests and 89
portable-output tests; strict Clippy and both release builds still pass.
- The milestone-only `rust_autobadges` run was attempted, but this installed
version misreported passing tests as failing and coverage as unavailable.
Its false generated badges were discarded; the prior badges were preserved.

1
Cargo.lock generated
View File

@ -398,6 +398,7 @@ dependencies = [
"lib_efo",
"log",
"miette",
"rand",
"serde",
"serde_json",
"thiserror",

View File

@ -73,7 +73,7 @@ Run `efo --help`, `efo <command> --help`, or see the
| Repository | Initialise format 1.0; inspect; lock and recover transactional writes | Future 1.x migration tooling; discovery from child directories; integrity repair |
| Timeline | Commit, advance, switch, log, tag, summarise, diff, restore, revert, and backed-up future pruning | Branching and merging |
| Entities | Add, edit, list, inspect, diff, and delete six built-in types | Custom types and custom fields; bulk operations |
| Generation | Generate character, town, event, calamity, blocker, and exotic names | Deterministic seed controls and template packs |
| Generation | Generate names and deterministic seeded events, settlements, regions, or worlds from embedded/override configuration | Roads, diffusion, and setting template packs |
| Interfaces | Complete CLI; read-only `efo-tui` repository browser | TUI write workflows; GUI/web (out of scope) |
`efo show all` gives a world overview; per-type commands such as

View File

@ -24,3 +24,4 @@ log = {workspace = true}
derive_more = {workspace = true}
colored = {workspace = true}
uuid = {workspace = true}
rand = "0.9.2"

View File

@ -61,6 +61,8 @@
//!
//! *All sub-commands simply output the generated data; they do not alter any files or state.*
use std::path::PathBuf;
use clap::{Args, Subcommand};
use lib_efo::{Displayable, error::EpochError, naming::NAMING};
@ -82,6 +84,25 @@ pub enum GenCmd {
Calamity(Qty),
/// Blocker
Blocker(Qty),
/// Generate a deterministic world from embedded or external configuration.
World(WorldArgs),
}
/// Deterministic world-generation options.
#[derive(Args, Debug)]
pub struct WorldArgs {
/// Amount of state to generate.
#[arg(long, value_enum, default_value_t = lib_efo::worldgen::GenerationLevel::World)]
level: lib_efo::worldgen::GenerationLevel,
/// Reproducible random seed; generated and printed when omitted.
#[arg(long)]
seed: Option<u64>,
/// JSON configuration override; embedded defaults are used when omitted.
#[arg(long, value_name = "PATH")]
config: Option<PathBuf>,
/// Replace the repository worktree; preview is the default.
#[arg(long)]
apply: bool,
}
#[derive(Args, Debug)]
@ -125,10 +146,41 @@ pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> {
GenCmd::Exotic(args) => handle_exotic(args)?,
GenCmd::Calamity(args) => handle_calamity(args)?,
GenCmd::Blocker(args) => handle_blocker(args)?,
GenCmd::World(args) => handle_world(args)?,
}
Ok(())
}
/// Preview or apply a deterministic generated world.
fn handle_world(args: &WorldArgs) -> Result<(), AppError> {
let config = args.config.as_deref().map_or_else(
lib_efo::worldgen::WorldGenConfig::embedded,
lib_efo::worldgen::WorldGenConfig::load,
)?;
let seed = args.seed.unwrap_or_else(rand::random);
let mut world = lib_efo::worldgen::generate(&config, seed, args.level);
println!("World generation preview · {:?} · seed {seed}", args.level);
println!("├─ Characters {}", world.characters.len());
println!("├─ Towns {}", world.towns.len());
println!("├─ Events {}", world.events.len());
println!("├─ Calamities {}", world.calamities.len());
println!("├─ Organisations {}", world.organizations.len());
println!("└─ Blockers {}", world.blockers.len());
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to replace the worktree.");
return Ok(());
}
let mut workspace = lib_efo::workspace::Workspace::open(std::path::Path::new("."))?;
world.epoch_id = workspace.worktree.world.epoch_id;
world.parent_epoch = workspace.worktree.world.parent_epoch;
world.commit_message = workspace.worktree.world.commit_message.clone();
workspace.worktree.world = world;
workspace.save_worktree("generate world")?;
println!("✓ Replaced the worktree with generated state using seed {seed}.");
println!(" Undo: efo restore --worktree --all");
Ok(())
}
/// Print a calamity name
fn handle_calamity(args: &Qty) -> Result<(), EpochError> {
for _ in 0..args.number {

View File

@ -10,6 +10,7 @@ use lib_efo::{
repository_format::FormatError,
transaction::TransactionError,
workspace::WorkspaceError,
worldgen::WorldGenError,
};
use miette::Diagnostic;
use thiserror::Error;
@ -48,6 +49,10 @@ pub enum AppError {
/// Repository manifest format detection failed.
#[error("Repository format error: {0}")]
Format(#[from] FormatError),
/// World-generation configuration or validation failed.
#[error("World generation stopped: {0}")]
WorldGen(#[from] WorldGenError),
// /// Anything else we didn't anticipate.
// #[error("Unknown error: {0}")]
// Other(String),

View File

@ -420,3 +420,69 @@ fn malformed_config_and_snapshot_are_diagnostics_not_panics() {
assert!(stderr(&bad_snapshot).contains("invalid repository state"));
assert!(!stderr(&bad_snapshot).contains("panicked"));
}
#[test]
fn seeded_world_generation_previews_applies_and_restores() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
let preview = efo(
&repo,
&["gen", "world", "--level", "settlement", "--seed", "42"],
);
assert_success(&preview);
let preview_text = stdout(&preview);
assert!(preview_text.contains("seed 42"));
assert!(preview_text.contains("Towns 1"));
assert!(preview_text.contains("Nothing changed"));
assert!(
snapshot(&repo, 0)["towns"]
.as_array()
.expect("towns")
.is_empty()
);
let applied = efo(
&repo,
&[
"gen",
"world",
"--level",
"settlement",
"--seed",
"42",
"--apply",
],
);
assert_success(&applied);
let first = snapshot(&repo, 0);
assert_eq!(first["towns"].as_array().expect("towns").len(), 1);
assert!(
!first["characters"]
.as_array()
.expect("characters")
.is_empty()
);
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
assert!(
snapshot(&repo, 0)["towns"]
.as_array()
.expect("towns")
.is_empty()
);
assert_success(&efo(
&repo,
&[
"gen",
"world",
"--level",
"settlement",
"--seed",
"42",
"--apply",
],
));
assert_eq!(snapshot(&repo, 0), first);
}

View File

@ -76,6 +76,12 @@ collection. Use `<noun> show IDENTIFIER` for full details of one entity.
`efo gen character|town|event|exotic|calamity|blocker` prints generated content
without creating or changing repository files.
`efo gen world --level event|settlement|region|world --seed N` previews a
deterministic generated world using embedded configuration. `--config PATH`
selects an editable JSON override. `--apply` explicitly replaces only the
worktree; undo it with `efo restore --worktree --all`, or stage and commit it
through the ordinary workflow.
Output is human-readable Unicode, with Nerd Font icons enabled by default. A
portable build replaces those icons with textual/standard-Unicode labels; use
`cargo install --path bin_efo --no-default-features`. Stable JSON output is

View File

@ -96,6 +96,12 @@ 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.
## Safety and test gates
- Property tests generate many seeds and validate IDs, links, bounds, roads,

View File

@ -0,0 +1,12 @@
# Epoch Forge worldgen configuration 1.0
`default.json` is embedded in `lib_efo` and is the offline default used by
`efo gen world`. Copy it, edit it, and pass the copy with `--config PATH`.
The schema version is independent from repository and application versions.
This release accepts exactly schema 1.0. Counts are inclusive and capped at
10,000 per entity kind; canvas dimensions are capped at 100,000 per axis.
Every kind with a non-zero maximum needs at least one name.
Given the same application build, exact configuration, generation level, and
seed, generation is deterministic. Preserve those four inputs with bug reports.

View File

@ -0,0 +1,20 @@
{
"schema_version": { "major": 1, "minor": 0 },
"canvas": { "width": 1920, "height": 1080 },
"counts": {
"characters": { "min": 18, "max": 32 },
"towns": { "min": 5, "max": 9 },
"events": { "min": 3, "max": 8 },
"calamities": { "min": 0, "max": 2 },
"organisations": { "min": 2, "max": 5 },
"blockers": { "min": 1, "max": 4 }
},
"names": {
"characters": ["Aria", "Bryn", "Cora", "Dain", "Elian", "Fara"],
"towns": ["Durn", "Highmere", "Oakwatch", "Rill", "Stoneford"],
"events": ["Market Day", "Heavy Rains", "Pilgrim Arrival", "Strange Lights"],
"calamities": ["The Blight", "Ashfall", "Great Flood"],
"organisations": ["Iron Council", "River Guild", "Lantern Compact"],
"blockers": ["North Wall", "Broken Bridge", "Rockslide"]
}
}

View File

@ -23,6 +23,7 @@ pub mod stats;
pub mod transaction;
pub mod utils;
pub mod workspace;
pub mod worldgen;
// use std::io::Result as IoResult;

356
lib_efo/src/worldgen.rs Normal file
View File

@ -0,0 +1,356 @@
//! Deterministic, configuration-driven world generation.
use std::{fs, path::Path};
use rand::{Rng, SeedableRng, rngs::StdRng, seq::IndexedRandom};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
entity::Entity,
epoch::EpochInfo,
repository_format::FormatVersion,
stats::{EntityType, Position},
};
/// Schema understood by this build for world-generation configuration.
pub const CURRENT_CONFIG_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 };
/// Embedded, offline-safe default configuration.
pub const DEFAULT_CONFIG_JSON: &str = include_str!("../assets/worldgen/default.json");
/// Amount of state to generate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum GenerationLevel {
/// One positioned event.
Event,
/// One town with residents and a local event.
Settlement,
/// A medium subset of the configured world.
Region,
/// A complete configured world.
World,
}
/// Inclusive entity-count range.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CountRange {
/// Smallest generated count.
pub min: usize,
/// Largest generated count.
pub max: usize,
}
/// Output canvas and coordinate bounds.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanvasConfig {
/// Width in pixels/world units.
pub width: u32,
/// Height in pixels/world units.
pub height: u32,
}
/// Configured ranges for every persisted entity collection.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EntityCounts {
/// Character count.
pub characters: CountRange,
/// Town count.
pub towns: CountRange,
/// Event count.
pub events: CountRange,
/// Calamity count.
pub calamities: CountRange,
/// Organisation count.
pub organisations: CountRange,
/// Blocker count.
pub blockers: CountRange,
}
/// Name pools used by deterministic generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamePools {
/// Character names.
pub characters: Vec<String>,
/// Town names.
pub towns: Vec<String>,
/// Event names.
pub events: Vec<String>,
/// Calamity names.
pub calamities: Vec<String>,
/// Organisation names.
pub organisations: Vec<String>,
/// Blocker names.
pub blockers: Vec<String>,
}
/// Complete versioned input for the generator.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorldGenConfig {
/// Configuration schema, independent from repository format.
pub schema_version: FormatVersion,
/// Spatial bounds.
pub canvas: CanvasConfig,
/// Full-world collection ranges.
pub counts: EntityCounts,
/// User-editable naming pools.
pub names: NamePools,
}
/// Configuration and generation failures.
#[derive(Debug, thiserror::Error)]
pub enum WorldGenError {
/// Reading an external configuration failed.
#[error("cannot read worldgen config `{path}`: {source}")]
Io {
/// Affected file.
path: std::path::PathBuf,
/// Filesystem failure.
#[source]
source: std::io::Error,
},
/// JSON did not match the schema.
#[error("invalid worldgen config `{path}`: {source}")]
Json {
/// Embedded label or external file.
path: std::path::PathBuf,
/// Decode failure.
#[source]
source: serde_json::Error,
},
/// Semantic validation rejected otherwise valid JSON.
#[error("invalid worldgen configuration: {0}")]
Invalid(String),
}
impl WorldGenConfig {
/// Load and validate the embedded defaults.
pub fn embedded() -> Result<Self, WorldGenError> {
Self::decode(
DEFAULT_CONFIG_JSON.as_bytes(),
Path::new("<embedded worldgen config>"),
)
}
/// Load and validate an external override.
pub fn load(path: &Path) -> Result<Self, WorldGenError> {
let bytes = fs::read(path).map_err(|source| WorldGenError::Io {
path: path.to_owned(),
source,
})?;
Self::decode(&bytes, path)
}
/// Decode and validate bytes while retaining their diagnostic source.
fn decode(bytes: &[u8], path: &Path) -> Result<Self, WorldGenError> {
let config: Self = serde_json::from_slice(bytes).map_err(|source| WorldGenError::Json {
path: path.to_owned(),
source,
})?;
config.validate()?;
Ok(config)
}
/// Validate limits before allocation or generation.
pub fn validate(&self) -> Result<(), WorldGenError> {
if self.schema_version != CURRENT_CONFIG_VERSION {
return Err(WorldGenError::Invalid(format!(
"schema {} is unsupported; expected {}",
self.schema_version, CURRENT_CONFIG_VERSION
)));
}
if self.canvas.width == 0
|| self.canvas.height == 0
|| self.canvas.width > 100_000
|| self.canvas.height > 100_000
{
return Err(WorldGenError::Invalid(
"canvas dimensions must each be between 1 and 100000".into(),
));
}
let entries = [
("characters", self.counts.characters, &self.names.characters),
("towns", self.counts.towns, &self.names.towns),
("events", self.counts.events, &self.names.events),
("calamities", self.counts.calamities, &self.names.calamities),
(
"organisations",
self.counts.organisations,
&self.names.organisations,
),
("blockers", self.counts.blockers, &self.names.blockers),
];
for (label, range, names) in entries {
if range.min > range.max || range.max > 10_000 {
return Err(WorldGenError::Invalid(format!(
"{label} count must be ordered and no greater than 10000"
)));
}
if range.max > 0 && names.is_empty() {
return Err(WorldGenError::Invalid(format!(
"{label} names cannot be empty when entities may be generated"
)));
}
}
Ok(())
}
}
/// Generate a deterministic complete snapshot from a validated configuration.
pub fn generate(config: &WorldGenConfig, seed: u64, level: GenerationLevel) -> EpochInfo {
let mut rng = StdRng::seed_from_u64(seed);
let mut world = EpochInfo {
rng_seed: seed,
..EpochInfo::default()
};
let counts = selected_counts(config, level, &mut rng);
world.characters = entities(
&config.names.characters,
counts[0],
EntityType::Character,
config,
&mut rng,
);
world.towns = entities(
&config.names.towns,
counts[1],
EntityType::Town,
config,
&mut rng,
);
world.events = entities(
&config.names.events,
counts[2],
EntityType::Event,
config,
&mut rng,
);
world.calamities = entities(
&config.names.calamities,
counts[3],
EntityType::Calamity,
config,
&mut rng,
);
world.organizations = entities(
&config.names.organisations,
counts[4],
EntityType::Organization,
config,
&mut rng,
);
world.blockers = entities(
&config.names.blockers,
counts[5],
EntityType::Blocker,
config,
&mut rng,
);
world
}
/// Resolve configured ranges into concrete counts for one generation level.
fn selected_counts(
config: &WorldGenConfig,
level: GenerationLevel,
rng: &mut StdRng,
) -> [usize; 6] {
match level {
GenerationLevel::Event => [0, 0, 1, 0, 0, 0],
GenerationLevel::Settlement => [rng.random_range(3..=6), 1, 1, 0, 0, 0],
GenerationLevel::Region => [
pick(config.counts.characters, rng).div_ceil(2),
pick(config.counts.towns, rng).max(1).div_ceil(2),
pick(config.counts.events, rng).max(1).div_ceil(2),
pick(config.counts.calamities, rng).div_ceil(2),
pick(config.counts.organisations, rng).div_ceil(2),
pick(config.counts.blockers, rng).div_ceil(2),
],
GenerationLevel::World => [
pick(config.counts.characters, rng),
pick(config.counts.towns, rng),
pick(config.counts.events, rng),
pick(config.counts.calamities, rng),
pick(config.counts.organisations, rng),
pick(config.counts.blockers, rng),
],
}
}
/// Pick an inclusive count reproducibly.
fn pick(range: CountRange, rng: &mut StdRng) -> usize {
rng.random_range(range.min..=range.max)
}
/// Build one positioned entity collection from a name pool.
fn entities(
names: &[String],
count: usize,
kind: EntityType,
config: &WorldGenConfig,
rng: &mut StdRng,
) -> Vec<Entity> {
(0..count)
.map(|index| {
let base = names
.choose(rng)
.cloned()
.unwrap_or_else(|| "Unnamed".to_owned());
let mut entity = Entity::default();
entity.name = format!("{base} {}", index + 1);
entity.id = Uuid::from_u128(rng.random());
entity.entity_type = kind;
entity.modify_position(Position::from((
rng.random_range(0..config.canvas.width) as isize,
rng.random_range(0..config.canvas.height) as isize,
)));
entity
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_config_is_valid() {
WorldGenConfig::embedded().expect("valid embedded config");
}
#[test]
fn the_same_seed_replays_exactly() {
let config = WorldGenConfig::embedded().expect("config");
let first = generate(&config, 42, GenerationLevel::World);
let second = generate(&config, 42, GenerationLevel::World);
assert_eq!(
serde_json::to_value(first).expect("first"),
serde_json::to_value(second).expect("second")
);
}
#[test]
fn levels_are_cumulative_in_scope() {
let config = WorldGenConfig::embedded().expect("config");
let event = generate(&config, 7, GenerationLevel::Event);
assert_eq!(event.events.len(), 1);
assert!(event.towns.is_empty());
let settlement = generate(&config, 7, GenerationLevel::Settlement);
assert_eq!(settlement.towns.len(), 1);
assert!(!settlement.characters.is_empty());
}
#[test]
fn invalid_ranges_and_empty_pools_are_rejected() {
let mut config = WorldGenConfig::embedded().expect("config");
config.counts.towns = CountRange { min: 3, max: 2 };
assert!(config.validate().is_err());
config.counts.towns = CountRange { min: 1, max: 2 };
config.names.towns.clear();
assert!(config.validate().is_err());
}
}

View File

@ -0,0 +1,22 @@
#!/bin/sh
set -eu
version="${1:-0.1.0}"
output="${2:-epoch-forge-worldgen-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 worldgen configuration" >&2
exit 1
fi
package_dir="$(mktemp -d)"
trap 'rm -rf "$package_dir"' EXIT HUP INT TERM
cp lib_efo/assets/worldgen/default.json "$package_dir/default.json"
cp lib_efo/assets/worldgen/README.md "$package_dir/README.md"
touch -t 200001010000 "$package_dir/default.json" "$package_dir/README.md"
(cd "$package_dir" && zip -X "$output" default.json README.md)
echo "Created $output"

View File

@ -0,0 +1,33 @@
#!/bin/sh
set -eu
tag="${1:?usage: upload-worldgen-config.sh TAG ZIP}"
asset="${2:?usage: upload-worldgen-config.sh TAG ZIP}"
base_url="${GITEA_URL:-https://proxy.dandaedre.com/gitea}"
repository="${GITEA_REPOSITORY:-idle-org/epoch_forge}"
if [ -z "${GITEA_TOKEN:-}" ]; then
echo "error: GITEA_TOKEN is required" >&2
exit 1
fi
if [ ! -f "$asset" ]; then
echo "error: asset does not exist: $asset" >&2
exit 1
fi
release_json="$(curl --fail --silent --show-error \
--header "Authorization: token $GITEA_TOKEN" \
"$base_url/api/v1/repos/$repository/releases/tags/$tag")"
release_id="$(printf '%s' "$release_json" | sed -n 's/^[[:space:]]*{"id":\([0-9][0-9]*\),.*/\1/p' | head -n 1)"
if [ -z "$release_id" ]; then
echo "error: could not determine release ID for tag $tag" >&2
exit 1
fi
curl --fail --silent --show-error \
--request POST \
--header "Authorization: token $GITEA_TOKEN" \
--form "attachment=@$asset" \
"$base_url/api/v1/repos/$repository/releases/$release_id/assets?name=$(basename "$asset")"
echo
echo "Uploaded $(basename "$asset") to release $tag"