This commit is contained in:
Dandaedre 2025-11-30 18:19:20 +01:00
parent 8043e6bd56
commit a7c6e849cd
19 changed files with 274 additions and 274 deletions

10
LICENSE
View File

@ -6,10 +6,10 @@ treat the Software as is, without restriction, subject to the following
condition:
• The Software may not be used, directly or indirectly, for training,
fine‑tuning, or otherwise feeding into any artificial‑intelligence
fine-tuning, or otherwise feeding into any artificial-intelligence
model or system. This includes, but is not limited to, usage as a
training dataset for machine‑learning or deep‑learning models,
model‑optimization, reinforcement‑learning, or any AI‑based analytics
training dataset for machine-learning or deep-learning models,
model-optimization, reinforcement-learning, or any AI-based analytics
pipeline.
• The Software may not be “scraped,” extracted, or otherwise harvested
@ -24,8 +24,8 @@ condition:
All other rights granted under the MIT license remain in force, namely:
• The Software may be used for any non‑AI purpose, including commercial
or non‑commercial use, modification, distribution, private or public
• The Software may be used for any non-AI purpose, including commercial
or non-commercial use, modification, distribution, private or public
deployment, and so on.
• The Software is provided “as is,” without warranty of any kind,

View File

@ -1,9 +1,9 @@
# 📦 Epoch Forge (`epoch_forge`)
> **A Rust‑powered CLI for managing fantasy organisations across time.**
> *Think of it as a living, breathing world‑state engine that lets you “rewind”, “fast‑forward”, and **alter** the history of guilds, towns, wars, and characters.*
> **A Rust-powered CLI for managing fantasy organisations across time.**
> *Think of it as a living, breathing world-state engine that lets you “rewind”, “fast-forward”, and **alter** the history of guilds, towns, wars, and characters.*
> 🚀 *Fast, type‑safe, and fully testable.*
> 🚀 *Fast, type-safe, and fully testable.*
## ✨ Quick start
@ -40,19 +40,19 @@ cat world.json
| Feature | What it gives you | Where it lives |
|---------|------------------|----------------|
| **Epoch management** | Switch, advance, or rewind the timeline | `core::epoch` |
| **Event handling** | Add/remove world‑shaping events (storms, festivals, wars) | `core::event` |
| **Event handling** | Add/remove world-shaping events (storms, festivals, wars) | `core::event` |
| **Organisation CRUD** | Guilds, factions, corporations | `core::org` |
| **Character CRUD** | Heroes, villains, NPCs | `core::character` |
| **Town CRUD** | Villages, cities, trade hubs | `core::town` |
| **Link network** | Alliances, wars, roads, trade routes | `core::link` |
| **Persistence** | JSON/YAML stores, pluggable back‑ends | `core::storage` |
| **CLI** | `efo` binary with sub‑commands | `efo` crate |
| **Persistence** | JSON/YAML stores, pluggable back-ends | `core::storage` |
| **CLI** | `efo` binary with sub-commands | `efo` crate |
| **Tests** | Unit & integration coverage | `tests/` |
### 📃 Quick reference table
| Sub‑command | Usage | What it changes |
| Sub-command | Usage | What it changes |
|-------------|-------|-----------------|
| `epoch` | `efo epoch --init`<br>`efo epoch --advance N`<br>`efo epoch --target ID` | Creates a world; moves time forward or back. |
| `event` | `efo event add ...`<br>`efo event remove ...` | Adds or removes an event. |

View File

@ -1,10 +1,10 @@
//! # `commands` module
//!
//! This module is the entry point for all CLI sub‑commands of the `efo` binary.
//! Each sub‑command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its
//! own file inside this directory and is re‑exported here so that the main
//! This module is the entry point for all CLI sub-commands of the `efo` binary.
//! Each sub-command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its
//! own file inside this directory and is re-exported here so that the main
//! `efo::main.rs` can simply `use commands::*;` and dispatch based on the
//! clap‑parsed enum.
//! clap-parsed enum.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]

View File

@ -1,6 +1,6 @@
//! # `epoch` sub‑command
//! # `epoch` sub-command
//!
//! Handles all epoch‑related logic – logging, switching, computing the
//! Handles all epoch-related logic - logging, switching, computing the
//! next epoch, and resetting future events.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
@ -16,12 +16,12 @@ use log::{debug, info};
pub mod cli_epoch;
/// **Public entry point used by `efo::main`** – dispatches to the real
/// **Public entry point used by `efo::main`** - dispatches to the real
/// handler that lives in `crate::world::EpochManager`.
///
/// # Arguments
/// * `cmd` – The command to execute. This is an enum that represents
/// one of the possible sub‑commands for the `epoch` feature.
/// * `cmd` - The command to execute. This is an enum that represents
/// one of the possible sub-commands for the `epoch` feature.
///
/// # Returns
/// * `Ok(())` on success.
@ -64,7 +64,7 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> {
/// supplied in `args.summary`. The epoch map in `main_epoch` is
/// modified in place.
///
/// This helper is internal to the `epoch` sub‑command and is not part
/// This helper is internal to the `epoch` sub-command and is not part
/// of the public API.
fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let epoch_id = main_epoch.epoch_id;
@ -82,9 +82,9 @@ fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Res
/// Show a diff between two epochs.
///
/// Currently unimplemented. The function is a placeholder until a
/// world‑level diff algorithm is available.
/// world-level diff algorithm is available.
///
/// This helper is internal to the `epoch` sub‑command and is not part
/// This helper is internal to the `epoch` sub-command and is not part
/// of the public API.
fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> {
let _ = args;
@ -99,7 +99,7 @@ fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> {
/// up to the supplied limit. The log is written by the
/// underlying `EpochConfig::log_elements` implementation.
///
/// This helper is internal to the `epoch` sub‑command.
/// This helper is internal to the `epoch` sub-command.
fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let limit = args.limit;
let start_id = &main_epoch.epoch_id;
@ -121,7 +121,7 @@ fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(),
/// in the configuration, and persists the change. It also prints a
/// success message via `display_success`.
///
/// This helper is internal to the `epoch` sub‑command.
/// This helper is internal to the `epoch` sub-command.
fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let target = main_epoch.get(&args.target)?;
main_epoch.try_load(&target)?;
@ -135,15 +135,15 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul
Ok(())
}
/// Handle the `next` sub‑command.
/// Handle the `next` sub-command.
///
/// Advances the epoch to the next scheduled event. If the current
/// configuration contains any epochs with an identifier larger than
/// the current one, an error is returned – otherwise the next epoch
/// the current one, an error is returned - otherwise the next epoch
/// is computed.
///
/// # Arguments
/// * `main_epoch` – mutable reference to the current `EpochConfig`
/// * `main_epoch` - mutable reference to the current `EpochConfig`
/// (the `cli_epoch::Next` argument is unused).
///
/// # Returns
@ -171,13 +171,13 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<(
}
}
/// Handle the `reset` sub‑command.
/// Handle the `reset` sub-command.
///
/// Deletes all epochs whose identifier is greater than the current one,
/// effectively rolling back to the present epoch.
///
/// # Arguments
/// * `main_epoch` – mutable reference to the current `EpochConfig`
/// * `main_epoch` - mutable reference to the current `EpochConfig`
/// (the `cli_epoch::Reset` argument is unused).
///
/// # Returns
@ -202,14 +202,14 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<
Ok(())
}
/// Handle the `tag` sub‑command.
/// Handle the `tag` sub-command.
///
/// Adds a tag to the current epoch. The tag must not already exist
/// elsewhere in the configuration; otherwise an error is returned.
///
/// # Arguments
/// * `args` – `cli_epoch::Tag` containing the tag to add.
/// * `main_epoch` – mutable reference to the current `EpochConfig`.
/// * `args` - `cli_epoch::Tag` containing the tag to add.
/// * `main_epoch` - mutable reference to the current `EpochConfig`.
///
/// # Returns
/// * `Ok(())` if the tag was successfully added.
@ -256,13 +256,13 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(
/// Perform a filesystem consistency check on the epoch data.
///
/// The function invokes the internal consistency‑check logic of
/// `EpochConfig`. It is intended for use from the `fsck` sub‑command
/// The function invokes the internal consistency-check logic of
/// `EpochConfig`. It is intended for use from the `fsck` sub-command
/// and does **not** modify the current epoch. Any problems that
/// are detected are reported through the returned `Result`; the
/// command may also print a diagnostic message to the user.
///
/// This helper is internal to the `epoch` sub‑command.
/// This helper is internal to the `epoch` sub-command.
fn handle_fsck(args: cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let _ = main_epoch;
let _ = args;

View File

@ -1,30 +1,30 @@
//! # `epoch` CLI module
//!
//! This module defines the command‑line interface for the `efo epoch`
//! sub‑command.
//! This module defines the command-line interface for the `efo epoch`
//! sub-command.
//!
//! ## Overview of commands
//!
//! * **`log`** – list epochs in a git‑log style.
//! * **`switch`** – switch to a specific epoch (by id, name or tag).
//! * **`next`** – compute the next epoch from the current one.
//! * **`reset`** – delete all future events after the current epoch.
//! * **`diff`** – show differences between two epochs.
//! * **`tag`** – add a tag to the current epoch.
//! * **`fsck`** – perform basic filesystem level maintenance.
//! * **`log`** - list epochs in a git-log style.
//! * **`switch`** - switch to a specific epoch (by id, name or tag).
//! * **`next`** - compute the next epoch from the current one.
//! * **`reset`** - delete all future events after the current epoch.
//! * **`diff`** - show differences between two epochs.
//! * **`tag`** - add a tag to the current epoch.
//! * **`fsck`** - perform basic filesystem level maintenance.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use clap::{Args, Subcommand};
use lib_efo::epoch::EpochIdentifier;
/// Top‑level sub‑command for the `efo epoch` command.
/// Top-level sub-command for the `efo epoch` command.
///
/// Each variant represents a distinct epoch operation that can be
/// invoked from the command line.
#[derive(Subcommand, Debug)]
pub enum EpochCmd {
/// List all epochs – a git‑log style view
/// List all epochs - a git-log style view
Log(Log),
/// Switch to an epoch (by numeric ID, name, or tag)
@ -49,10 +49,10 @@ pub enum EpochCmd {
Summary(Summary),
}
/// Displays a git‑log style list of epochs.
/// Displays a git-log style list of epochs.
///
/// # Arguments
/// * `limit` – (Optional) Limit the number of entries shown.
/// * `limit` - (Optional) Limit the number of entries shown.
/// Default: `50`.
#[derive(Args, Debug)]
pub struct Log {
@ -65,16 +65,16 @@ pub struct Log {
/// a name, or a tag.
///
/// # Arguments
/// * `target` – The epoch to switch to.
/// * `force` – If set, drops all pending work and forces the switch.
/// * `target` - The epoch to switch to.
/// * `force` - If set, drops all pending work and forces the switch.
#[derive(Args, Debug)]
pub struct Switch {
/// The epoch to switch to – can be an integer, a name, or a tag.
/// The epoch to switch to - can be an integer, a name, or a tag.
#[arg(required = true)]
pub target: EpochIdentifier,
/// Optional confirmation flag (if you ever want to force‑switch)
#[arg(long, short, help = "Force‑switch dropping all the pending work")]
/// Optional confirmation flag (if you ever want to force-switch)
#[arg(long, short, help = "Force-switch dropping all the pending work")]
pub force: bool,
}
@ -89,8 +89,8 @@ pub struct Reset;
/// Shows the differences between two epochs.
///
/// # Arguments
/// * `start` – The starting point to compute the differences.
/// * `end` – The end point to compute the differences; defaults to the
/// * `start` - The starting point to compute the differences.
/// * `end` - The end point to compute the differences; defaults to the
/// current epoch if omitted.
#[derive(Args, Debug)]
pub struct Diff {
@ -105,7 +105,7 @@ pub struct Diff {
/// Adds a tag to the current epoch.
///
/// # Arguments
/// * `tag` – The tag to tag the current epoch with.
/// * `tag` - The tag to tag the current epoch with.
#[derive(Args, Debug)]
pub struct Tag {
#[arg(required = true)]

View File

@ -1,13 +1,13 @@
//! # `init` module
//!
//! Provides the implementation of the `init` sub‑command for the
//! command‑line interface. The sub‑command creates an empty
//! Provides the implementation of the `init` sub-command for the
//! command-line interface. The sub-command creates an empty
//! repository, writes the default configuration (`.epoch`),
//! and sets up the first epoch (epoch 0).
//! and sets up the first epoch (epoch 0).
//!
//! The main public API consists of:
//!
//! * `InitCmd` – a struct containing the command‑line arguments.
//! * `InitCmd` - a struct containing the command-line arguments.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
@ -67,7 +67,7 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> {
Ok(())
}
/// Helper that creates the initial epoch (epoch 0).
/// Helper that creates the initial epoch (epoch 0).
///
/// This function is not part of the public API; it is kept internal
/// to `init`. It creates an empty `EpochInfo`, crea

View File

@ -1,7 +1,7 @@
//! General error type that the CLI propagates.
//!
//! `AppError` aggregates all error kinds that may surface during a command
//! execution: parsing, I/O, epoch logic, storage, and a catch‑all.
//! execution: parsing, I/O, epoch logic, storage, and a catch-all.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
@ -13,8 +13,8 @@ use thiserror::Error;
#[derive(Debug, Error, Diagnostic)]
#[allow(dead_code)]
pub enum AppError {
/// Generic “invalid command / missing flag” – emitted by clap.
#[error("Command‑line error: {0}")]
/// Generic “invalid command / missing flag” - emitted by clap.
#[error("Command-line error: {0}")]
// #[diagnostic(transparent)]
Clap(#[from] clap::Error),
@ -23,17 +23,17 @@ pub enum AppError {
// #[diagnostic(transparent)]
Io(#[from] std::io::Error),
/// Domain‑specific problems (see `EpochError`).
/// Domain-specific problems (see `EpochError`).
#[error("Epoch error:")]
#[diagnostic(transparent)]
Epoch(#[from] EpochError),
/// Storage‑layer (e.g. DB) errors.
/// Storage-layer (e.g. DB) errors.
#[error("Storage error: {0}")]
// #[diagnostic(transparent)]
Storage(#[from] StorageError),
/// Anything else we didn’t anticipate.
/// Anything else we didn't anticipate.
#[error("Unknown error: {0}")]
Other(String),
}

View File

@ -1,16 +1,16 @@
//! # `efo`
//!
//! The **command‑line interface** for `epoch_forge`. It exposes a single
//! binary `efo` that supports the following sub‑commands:
//! The **command-line interface** for `epoch_forge`. It exposes a single
//! binary `efo` that supports the following sub-commands:
//!
//! - `epoch` – switch / advance time
//! - `event` – add / remove events
//! - `org` – add / remove organisations
//! - `chr` – add / remove characters
//! - `town` – add / remove towns
//! - `link` – add / remove links (alliances, wars, roads, etc.)
//! - `epoch` - switch / advance time
//! - `event` - add / remove events
//! - `org` - add / remove organisations
//! - `chr` - add / remove characters
//! - `town` - add / remove towns
//! - `link` - add / remove links (alliances, wars, roads, etc.)
//!
//! Each sub‑command is implemented in its own module under `commands/`.
//! Each sub-command is implemented in its own module under `commands/`.
//! The `main.rs` file simply parses arguments with `clap` and dispatches
//! to the appropriate handler. The handlers share a common `World`
//! instance that they load from / persist to disk.
@ -32,13 +32,13 @@ mod commands;
mod error;
mod success;
/// The root command‑line parser for the `efo` binary.
/// The root command-line parser for the `efo` binary.
///
/// It uses `clap` to parse the top‑level sub‑commands (`init`, `epoch`, …)
/// It uses `clap` to parse the top-level sub-commands (`init`, `epoch`, …)
/// and stores them in the `command` field.
#[derive(Parser, Debug)]
#[command(name = "efo")]
#[command(about = "Epoch Forge – manage organisations over time")]
#[command(about = "Epoch Forge - manage organisations over time")]
struct Cli {
/// The level of verbosity
#[arg(short, long, action = ArgAction::Count, global = true)]
@ -49,9 +49,9 @@ struct Cli {
command: TopLevelCmd,
}
/// Enumeration of the top‑level sub‑commands that `efo` accepts.
/// Enumeration of the top-level sub-commands that `efo` accepts.
///
/// Each variant corresponds to a single sub‑command and holds its own
/// Each variant corresponds to a single sub-command and holds its own
/// argument structure.
#[derive(Subcommand, Debug)]
enum TopLevelCmd {
@ -69,8 +69,8 @@ enum TopLevelCmd {
/// Program entry point.
///
/// Parses the command‑line arguments and dispatches to the selected
/// sub‑command. Errors returned by the sub‑command handlers are shown
/// Parses the command-line arguments and dispatches to the selected
/// sub-command. Errors returned by the sub-command handlers are shown
/// in stdout and returned as a `miette::Result<()>`.
#[allow(clippy::unwrap_used)]
fn main() -> miette::Result<()> {
@ -98,11 +98,11 @@ fn main() -> miette::Result<()> {
/// Dispatches the parsed command to the appropriate handler.
///
/// # Arguments
/// * `cli` – The parsed command‑line options.
/// * `cli` - The parsed command-line options.
///
/// # Returns
/// * `Ok(())` on success.
/// * `Err(AppError)` if the chosen sub‑command handler fails.
/// * `Err(AppError)` if the chosen sub-command handler fails.
///
/// The function matches on the `TopLevelCmd` variant and calls the
/// corresponding handler in the `commands` module. Any error is

View File

@ -9,7 +9,7 @@ pub enum SuccessMessages {
#[display("Switched to epoch {_0}")]
EpochSwitchSuccess(lib_efo::epoch::EpochId),
#[display("All future events deleted – back to epoch {_0}")]
#[display("All future events deleted - back to epoch {_0}")]
DeletedAllFutureEvents(lib_efo::epoch::EpochId),
#[display("The folder was initialized as an epoch folder")]

View File

@ -374,15 +374,15 @@
"the Harvester",
"the Seeker",
"the Whisperer",
"the Tempest‑born",
"the Iron‑clad",
"the Tempest-born",
"the Iron-clad",
"the Moonlit",
"the Sun‑scarred",
"the Bone‑choked",
"the Frost‑kissed",
"the Sun-scarred",
"the Bone-choked",
"the Frost-kissed",
"the Ashen",
"the Shattered",
"the Echo‑bound",
"the Echo-bound",
"the Vile",
"the Harsh",
"the Unseen",
@ -540,7 +540,7 @@
},
{
"name": "city_corruption_scandal",
"description": "A high‑ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.",
"description": "A high-ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.",
"stats": [
{ "stat": "Economy", "value": -9 },
{ "stat": "Bureaucracy", "value": -7 },
@ -585,7 +585,7 @@
},
{
"name": "city_guild_suppression",
"description": "The council cracks down on the city’s merchant guilds, confiscating goods and driving merchants underground.",
"description": "The council cracks down on the city's merchant guilds, confiscating goods and driving merchants underground.",
"stats": [
{ "stat": "Trade", "value": -11 },
{ "stat": "Crime", "value": 6 },
@ -603,7 +603,7 @@
},
{
"name": "city_public_health_crisis",
"description": "A mysterious disease spreads through the city’s crowded streets, overwhelming the local infirmaries.",
"description": "A mysterious disease spreads through the city's crowded streets, overwhelming the local infirmaries.",
"stats": [
{ "stat": "Health", "value": -16 },
{ "stat": "Population", "value": -8 },
@ -612,7 +612,7 @@
},
{
"name": "city_transport_infrastructure_fail",
"description": "The city’s main aqueduct collapses, cutting off water supply to half the districts.",
"description": "The city's main aqueduct collapses, cutting off water supply to half the districts.",
"stats": [
{ "stat": "Infrastructure", "value": -15 },
{ "stat": "Population", "value": -4 },
@ -693,7 +693,7 @@
},
{
"name": "currency_devaluation",
"description": "The city’s coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.",
"description": "The city's coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.",
"stats": [
{ "stat": "Economy", "value": -13 },
{ "stat": "Trade", "value": -9 },
@ -711,7 +711,7 @@
},
{
"name": "resource_piracy",
"description": "Sea‑borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.",
"description": "Sea-borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.",
"stats": [
{ "stat": "Trade", "value": -12 },
{ "stat": "Economy", "value": -7 },
@ -720,7 +720,7 @@
},
{
"name": "steel_furnace_overheat",
"description": "A critical failure in the city’s primary steel furnace sparks an uncontrollable fire, destroying production lines.",
"description": "A critical failure in the city's primary steel furnace sparks an uncontrollable fire, destroying production lines.",
"stats": [
{ "stat": "Industry", "value": -17 },
{ "stat": "Economy", "value": -10 },
@ -747,7 +747,7 @@
},
{
"name": "foreign_factory_purchase",
"description": "A foreign conglomerate purchases the city’s largest textile mill, imposing new quotas that reduce local employment.",
"description": "A foreign conglomerate purchases the city's largest textile mill, imposing new quotas that reduce local employment.",
"stats": [
{ "stat": "Industry", "value": -9 },
{ "stat": "Economy", "value": -7 },
@ -774,7 +774,7 @@
},
{
"name": "bottleneck_transportation",
"description": "The city’s main rail line is seized by gangsters, disrupting the flow of raw materials to factories.",
"description": "The city's main rail line is seized by gangsters, disrupting the flow of raw materials to factories.",
"stats": [
{ "stat": "Infrastructure", "value": -8 },
{ "stat": "Industry", "value": -6 },
@ -819,7 +819,7 @@
},
{
"name": "naval_battle_victory",
"description": "The city’s navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy’s threat level.",
"description": "The city's navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy's threat level.",
"stats": [
{ "stat": "Military", "value": 12 },
{ "stat": "Threat", "value": -9 },
@ -846,7 +846,7 @@
},
{
"name": "training_expedition",
"description": "A focused military academy expedition hones the troops’ skills, raising overall strength at the cost of a temporary manpower drain.",
"description": "A focused military academy expedition hones the troops' skills, raising overall strength at the cost of a temporary manpower drain.",
"stats": [
{ "stat": "Strength", "value": 11 },
{ "stat": "Army", "value": -6 },
@ -891,7 +891,7 @@
},
{
"name": "peace_council",
"description": "A diplomatic summit ends a long‑standing border conflict, reducing threat levels and fostering cultural exchange.",
"description": "A diplomatic summit ends a long-standing border conflict, reducing threat levels and fostering cultural exchange.",
"stats": [
{ "stat": "Trade", "value": 10 },
{ "stat": "Culture", "value": 7 },
@ -927,7 +927,7 @@
},
{
"name": "military_training_expedition",
"description": "An intensive training expedition sharpens the army’s tactics, increasing overall strength without cost.",
"description": "An intensive training expedition sharpens the army's tactics, increasing overall strength without cost.",
"stats": [
{ "stat": "Strength", "value": 12 },
{ "stat": "Army", "value": 3 },
@ -982,7 +982,7 @@
},
{
"name": "plague_of_scorpion",
"description": "A deadly disease spreads through the populace, turning citizens into venom‑infused monsters.",
"description": "A deadly disease spreads through the populace, turning citizens into venom-infused monsters.",
"stats": [
{ "stat": "Health", "value": -22 },
{ "stat": "Population", "value": -16 },
@ -991,7 +991,7 @@
},
{
"name": "oil_fire_in_barnyard",
"description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army’s morale and strength.",
"description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army's morale and strength.",
"stats": [
{ "stat": "Industry", "value": -19 },
{ "stat": "Military", "value": -12 },
@ -1000,7 +1000,7 @@
},
{
"name": "fire_of_sacred_temple",
"description": "The city’s most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.",
"description": "The city's most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.",
"stats": [
{ "stat": "Culture", "value": -15 },
{ "stat": "Threat", "value": 12 },
@ -1018,7 +1018,7 @@
},
{
"name": "massive_barricade_breach",
"description": "A minor calamity overpowers the city’s fortifications, unleashing a wave of slaughter and chaos.",
"description": "A minor calamity overpowers the city's fortifications, unleashing a wave of slaughter and chaos.",
"stats": [
{ "stat": "Fortification", "value": -19 },
{ "stat": "Threat", "value": 20 },

View File

@ -4,12 +4,12 @@
//! structures so that the binary can quickly read/write its “current
//! position” without pulling the whole world into memory.
//!
//! * `EpochConfig` – lives in `.epochconfig`. It only remembers
//! * `EpochConfig` - lives in `.epochconfig`. It only remembers
//! which epoch folder should be considered “current” and a few
//! convenience fields (tags, path). It never holds any event or
//! world data.
//!
//! * `EpochInfo` – stored inside `epoch/<epoch_id>/.epochinfo`.
//! * `EpochInfo` - stored inside `epoch/<epoch_id>/.epochinfo`.
//! This file contains the *metadata* for that particular epoch
//! (seed, selected events, parent link, etc.). Again, it does **not**
//! hold the full world; that is handled elsewhere in the engine.
@ -119,8 +119,8 @@ impl std::ops::Deref for EpochId {
}
}
/// A flexible identifier for *any* epoch – the world may be
/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`).
/// A flexible identifier for *any* epoch - the world may be
/// addressed by a numeric ID or by a friendly tag (e.g. `"winter-b"`).
///
/// The enum is `untagged` so that serialising/deserialising does
/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`.
@ -128,7 +128,7 @@ impl std::ops::Deref for EpochId {
/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))`
/// * `"foo"` → `EpochIdentifier::Tag("foo".into())`
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON
#[serde(untagged)] // <-- no “type” wrapper is written to JSON
pub enum EpochIdentifier {
/// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`.
Tag(String),
@ -140,7 +140,7 @@ pub enum EpochIdentifier {
impl FromStr for EpochIdentifier {
type Err = clap::Error; // any `std::error::Error` works
/// Try to parse either a decimal number (-> `Id`) or any non‑empty
/// Try to parse either a decimal number (-> `Id`) or any non-empty
/// string (-> `Tag`).
///
/// Errors are converted to a Clap error so that the CLI shows a

View File

@ -1,10 +1,10 @@
//! Management of the *current‑epoch* configuration.
//! Management of the *current-epoch* configuration.
//!
//! The configuration is stored in a file named `.epoch` and contains only
//! the lightweight information needed for the CLI to switch between epochs
//! quickly:
//! * the numeric ID of the current epoch,
//! * a map of human‑friendly tags to epoch IDs,
//! * a map of human-friendly tags to epoch IDs,
//! * a map of known epoch IDs to unloaded metadata (`EpochInfo`).
//!
//! The world data and all event logs belong to the individual epoch
@ -30,16 +30,16 @@ use crate::{epoch::epoch_traits::Prettiable, error::EpochError, io_err_with_help
///
/// Only the minimal information needed for fast switches is stored:
/// * the numeric identifier of the selected epoch,
/// * a list of human‑readable tags,
/// * the absolute path to the epoch’s directory.
/// * a list of human-readable tags,
/// * the absolute path to the epoch's directory.
///
/// No world or event data lives here – it is purely a lightweight pointer.
/// No world or event data lives here - it is purely a lightweight pointer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpochConfig {
/// The epoch ID that the binary should consider “current”.
pub epoch_id: EpochId,
/// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`).
/// Optional human-friendly tags (e.g. `"winter-B"`, `"post-war"`).
pub tags: HashMap<String, EpochId>,
// TODO[6]: Can become important
// #[serde(skip)]
@ -102,7 +102,7 @@ impl EpochConfig {
Ok(self)
}
/// Loads the metadata for an epoch from disk into the in‑memory cache.
/// Loads the metadata for an epoch from disk into the in-memory cache.
///
/// The epoch identified by `epoch_id` must exist in `list_existing_epochs`.
/// The JSON file on disk is read, deserialized into an `EpochInfo`, and
@ -216,12 +216,12 @@ impl EpochConfig {
/// Insert a new epoch into the configuration and persist it.
///
/// The function creates the epoch’s directory, writes its metadata,
/// The function creates the epoch's directory, writes its metadata,
/// updates the internal maps, and finally writes the updated
/// configuration to disk.
///
/// # Returns
/// * `Ok(())` – the epoch was added and the configuration was saved.
/// * `Ok(())` - the epoch was added and the configuration was saved.
/// * `Err(EpochError::EpochAlreadyExists(..))` if an epoch with the same ID already exists.
pub fn insert_and_save(
&mut self,
@ -247,7 +247,7 @@ impl EpochConfig {
/// Load and display the metadata for a list of epoch IDs.
///
/// The function first ensures that each requested epoch’s metadata is
/// The function first ensures that each requested epoch's metadata is
/// loaded into memory, then displays a formatted log for each one.
pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> {
let mut items_to_log = Vec::with_capacity(list_ids.len());

View File

@ -3,7 +3,7 @@
//! The `EpochInfo` struct holds all information that the engine needs to
//! reconstruct a particular epoch.
//! It is persisted to `epoch/<epoch_id>/.epochinfo`. The file contains the epoch ID, the RNG
//! seed that produced the world, any optional tags, and a human‑readable
//! seed that produced the world, any optional tags, and a human-readable
//! summary. World data itself is stored separately (e.g. in `world.json`).
use cli_table::Table;
@ -32,7 +32,7 @@ use crate::{
"Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})"
)]
pub struct EpochInfo {
/// The ID of this epoch – should match the directory name.
/// The ID of this epoch - should match the directory name.
#[table(title = "ID")]
pub epoch_id: EpochId,
@ -46,11 +46,11 @@ pub struct EpochInfo {
// /// The engine uses this to replay the world from the
// /// parent epoch to the current one.
// pub selected_events: Vec<u64>,
/// Optional tags that help identify the epoch (e.g. `"Winter‑B"`).
/// Optional tags that help identify the epoch (e.g. `"Winter-B"`).
#[table(title = "Tags")]
pub tags: TagList,
/// Human‑readable description or summary, useful for the `log` command.
/// Human-readable description or summary, useful for the `log` command.
#[table(title = "Summary")]
pub summary: String,
}

View File

@ -2,7 +2,7 @@
//!
//! All traits used by the `lib_efo` library.
//! These traits are marker traits that describe behaviour
//! common to many of the library’s element types.
//! common to many of the library's element types.
#![warn(clippy::missing_docs_in_private_items)]
use cli_table::{Style, Table, WithTitle};
@ -20,10 +20,10 @@ pub trait Applyable {}
/// Elements that can advance to a next state over time.
///
/// Implementors usually provide a `.next()` method that returns the
/// element’s state after a time step (e.g., fading or diminishing).
/// element's state after a time step (e.g., fading or diminishing).
pub trait Nextable {}
/// Elements that can be rendered into a pretty, human‑readable form.
/// Elements that can be rendered into a pretty, human-readable form.
pub trait Prettiable: Display {
/// Shows many items as a table.
///
@ -65,7 +65,7 @@ pub trait ConfigWritable: Serialize {
/// * `action` - A description of the action for error reporting.
///
/// # Returns
/// * `Ok(String)` containing the pretty‑printed JSON.
/// * `Ok(String)` containing the pretty-printed JSON.
/// * `Err(EpochError::Serde)` if serialisation fails.
fn as_json(&self, action: String) -> Result<String, EpochError> {
serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
@ -83,8 +83,8 @@ pub trait ConfigWritable: Serialize {
/// file already exists.
///
/// # Arguments
/// * `action_description` – A human‑readable description used in error messages.
/// * `do_not_erase` – Determines whether to overwrite an existing file.
/// * `action_description` - A human-readable description used in error messages.
/// * `do_not_erase` - Determines whether to overwrite an existing file.
///
/// # Returns
/// * `Ok(())` on success.

View File

@ -1,7 +1,7 @@
//! Error types that arise when interacting with the storage layer.
//!
//! These are the only errors emitted by the `Storage` abstraction. They are
//! lightweight, strongly‑typed, and can be converted to the top‑level
//! lightweight, strongly-typed, and can be converted to the top-level
//! `AppError` via `thiserror`.
//!
//! The public items below are all lightweight error types that can be
@ -19,7 +19,7 @@ use miette::Diagnostic;
/// Errors that can be returned by the storage layer.
///
/// The variants are intentionally small – each one carries all the
/// The variants are intentionally small - each one carries all the
/// information required to surface a helpful message to the user.
// TODO[2]: Remove or rethink these errors
#[derive(Debug, Error, Diagnostic)]
@ -43,9 +43,9 @@ pub enum StorageError {
/// All errors that can occur while working with epochs.
///
/// The enum is deliberately _small_ – each variant is self‑contained and
/// The enum is deliberately _small_ - each variant is self-contained and
/// carries the information you need to surface a friendly message
/// to the user (and to the test‑suite).
/// to the user (and to the test-suite).
// TODO[2]: Split effectively user errors to avoid the usage of advice and such
#[derive(Error, Debug, Diagnostic)]
pub enum EpochError {
@ -136,12 +136,12 @@ pub enum EpochError {
EpochAlreadyExists(EpochId),
/// Attempt to switch to an epoch that has already been advanced past.
#[error("Cannot switch to epoch `{0}` – the world has already advanced beyond it")]
#[error("Cannot switch to epoch `{0}` - the world has already advanced beyond it")]
#[diagnostic(code(EpochError::SwitchPastEpoch))]
SwitchPastEpoch(EpochId),
/// The supplied epoch id is out of bounds (negative, zero or too large).
#[error("Invalid epoch id `{0}` – must be a positive, non‑overflowing integer")]
#[error("Invalid epoch id `{0}` - must be a positive, non-overflowing integer")]
#[diagnostic(code(EpochError::InvalidEpochId))]
InvalidEpochId(EpochId),
@ -155,7 +155,7 @@ pub enum EpochError {
#[diagnostic(code(EpochError::ParentEpochMissing))]
ParentEpochMissing(EpochId, EpochId),
/// Generic I/O errors that bubble up from other sub‑tasks.
/// Generic I/O errors that bubble up from other sub-tasks.
#[error("I/O error")]
#[diagnostic(code(EpochError::GenericIO))]
Io {
@ -219,7 +219,7 @@ pub enum EpochError {
UserError(#[help] UserErrors),
}
/// A small enum of explicit user‑facing error messages.
/// A small enum of explicit user-facing error messages.
///
/// The variants are deliberately simple; each one is rendered with a
/// clear message via `derive_more::Display`.

View File

@ -3,15 +3,15 @@
//! The **engine** that drives *Epoch Forge*. It contains a pure, representation of a fantasy world and all the logic needed to manipulate it.
//!
//! The crate is split into the following domains, each exposed as a public module:
//! - TODO[1]: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`).
//! - TODO[0]: `epoch` – manages the passage of time and epoch switching.
//! - TODO[1]: `event` – CRUD and evaluation of events that affect the world.
//! - TODO[4]: `org` – organisations, guilds, factions and their history.
//! - TODO[2]: `character` – individual characters, traits and lineage.
//! - TODO[1]: `town` – towns, cities, trade hubs and their populations.
//! - TODO[2]: `link` – relations such as wars, alliances, roads, commerce.
//! - TODO[3]: `storage` – generic persistence layer (`Store<T>`) with JSON/YAML back‑ends.
//! - TODO[4]: `util` – small helpers, ID generation, error types, etc.
//! - TODO[1]: `world` - holds the global state (`World`) and a lightweight snapshot (`Context`).
//! - TODO[0]: `epoch` - manages the passage of time and epoch switching.
//! - TODO[1]: `event` - CRUD and evaluation of events that affect the world.
//! - TODO[4]: `org` - organisations, guilds, factions and their history.
//! - TODO[2]: `character` - individual characters, traits and lineage.
//! - TODO[1]: `town` - towns, cities, trade hubs and their populations.
//! - TODO[2]: `link` - relations such as wars, alliances, roads, commerce.
//! - TODO[3]: `storage` - generic persistence layer (`Store<T>`) with JSON/YAML back-ends.
//! - TODO[4]: `util` - small helpers, ID generation, error types, etc.
//!
//! All public types implement `serde::Serialize / Deserialize` so that they can
//! be persisted easily. The `World` struct also offers a convenient

View File

@ -4,10 +4,10 @@
//! Infrastructure). Each field is a `GenericStat`, an internal wrapper around a numeric value
//! that provides convenience methods such as `max()`, `clamp()`, and arithmetic ops.
//!
//! The documentation for each field follows the same three‑part template:
//! * **Purpose** – What the stat represents.
//! * **Effect** – Gameplay consequence of the stat.
//! * **Source** – Formula or function that generates the stat value.
//! The documentation for each field follows the same three-part template:
//! * **Purpose** - What the stat represents.
//! * **Effect** - Gameplay consequence of the stat.
//! * **Source** - Formula or function that generates the stat value.
#![allow(dead_code)]
#![deny(clippy::missing_docs_in_private_items)]
@ -32,195 +32,195 @@ pub struct OverallStats {
// ──────────────────────── Demographics ────────────────────────
/// Total economic health of the entity.
///
/// **Purpose** – A single value summarizing all economic indicators.
/// **Effect** – Drives tax revenue, spending power, and overall economic influence.
/// **Source** – Sum of `industry`, `science`, `trade`, and other economic contributors.
/// **Purpose** - A single value summarizing all economic indicators.
/// **Effect** - Drives tax revenue, spending power, and overall economic influence.
/// **Source** - Sum of `industry`, `science`, `trade`, and other economic contributors.
pub demographics: GenericStat,
/// Population count.
///
/// **Purpose** – The number of citizens living in the entity.
/// **Effect** – Determines resource consumption, tax base, and potential unrest.
/// **Source** – Updated by the growth/decay formulas each turn.
/// **Purpose** - The number of citizens living in the entity.
/// **Effect** - Determines resource consumption, tax base, and potential unrest.
/// **Source** - Updated by the growth/decay formulas each turn.
pub population: GenericStat,
/// Per‑turn change in population.
/// Per-turn change in population.
///
/// **Purpose** – The growth rate of the population.
/// **Effect** – Predicts future needs and signals potential social unrest.
/// **Source** – Derived from `population`, `happiness`, and `stability`.
/// **Purpose** - The growth rate of the population.
/// **Effect** - Predicts future needs and signals potential social unrest.
/// **Source** - Derived from `population`, `happiness`, and `stability`.
pub growth_rate: GenericStat,
/// Crime level (0–1 scale).
/// Crime level (0-1 scale).
///
/// **Purpose** – How frequently crimes occur.
/// **Effect** – Can trigger riots and reduce stability.
/// **Source** – Result of the crime function (influenced by class disparity and law enforcement).
/// **Purpose** - How frequently crimes occur.
/// **Effect** - Can trigger riots and reduce stability.
/// **Source** - Result of the crime function (influenced by class disparity and law enforcement).
pub crime: GenericStat,
/// Base happiness of the population (0–1 scale).
/// Base happiness of the population (0-1 scale).
///
/// **Purpose** – A measure of citizen contentment.
/// **Effect** – Influences productivity, tax compliance, and unrest.
/// **Source** – Output of the happiness function (affected by class, war, infrastructure).
/// **Purpose** - A measure of citizen contentment.
/// **Effect** - Influences productivity, tax compliance, and unrest.
/// **Source** - Output of the happiness function (affected by class, war, infrastructure).
pub happiness: GenericStat,
// ──────────────────────── Economy ────────────────────────
/// Aggregate economic health of the entity.
///
/// **Purpose** – A single value summarizing all economic metrics.
/// **Effect** – Drives revenue, spending, and empire‑wide economic influence.
/// **Source** – Sum of `food`, `industry`, `science`, `trade`, etc.
/// **Purpose** - A single value summarizing all economic metrics.
/// **Effect** - Drives revenue, spending, and empire-wide economic influence.
/// **Source** - Sum of `food`, `industry`, `science`, `trade`, etc.
pub economy: GenericStat,
/// Food produced by the entity.
///
/// **Purpose** – Amount of consumable resources available.
/// **Effect** – Keeps the population alive and productive.
/// **Source** – `food = farm_yield + tech_level`.
/// **Purpose** - Amount of consumable resources available.
/// **Effect** - Keeps the population alive and productive.
/// **Source** - `food = farm_yield + tech_level`.
pub food: GenericStat,
/// Strength of the industry.
///
/// **Purpose** – Industrial production capacity.
/// **Effect** – Drives tax revenue and unit production.
/// **Source** – `industry = factory_output + tech_level`.
/// **Purpose** - Industrial production capacity.
/// **Effect** - Drives tax revenue and unit production.
/// **Source** - `industry = factory_output + tech_level`.
pub industry: GenericStat,
/// Scientific output.
///
/// **Purpose** – Rate of research progress.
/// **Effect** – Determines how quickly new technologies are unlocked.
/// **Source** – `science = research_center_output + tech_level`.
/// **Purpose** - Rate of research progress.
/// **Effect** - Determines how quickly new technologies are unlocked.
/// **Source** - `science = research_center_output + tech_level`.
pub science: GenericStat,
/// Trade volume / exports.
///
/// **Purpose** – Measure of export activity.
/// **Effect** – Influences influence and wealth.
/// **Source** – `trade = trade_network_output`.
/// **Purpose** - Measure of export activity.
/// **Effect** - Influences influence and wealth.
/// **Source** - `trade = trade_network_output`.
pub trade: GenericStat,
// // ──────────────────────── Social ────────────────────────
// /// Overall social prestige.
// ///
// /// **Purpose** – Reflects the cultural standing of the entity.
// /// **Effect** – Affects diplomacy and citizen morale.
// /// **Source** – Sum of `culture`, `education`, `tourism`, etc.
// /// **Purpose** - Reflects the cultural standing of the entity.
// /// **Effect** - Affects diplomacy and citizen morale.
// /// **Source** - Sum of `culture`, `education`, `tourism`, etc.
// pub social: GenericStat,
// /// Cultural output from arts, theatres, museums, etc.
// ///
// /// **Purpose** – Measure of cultural production.
// /// **Effect** – Drives tourism, prestige, and happiness.
// /// **Source** – `culture = Σ(cultural_building_output)`.
// /// **Purpose** - Measure of cultural production.
// /// **Effect** - Drives tourism, prestige, and happiness.
// /// **Source** - `culture = Σ(cultural_building_output)`.
// pub culture: GenericStat,
// /// Level of education/literacy.
// ///
// /// **Purpose** – Measure of the citizenry’s knowledge.
// /// **Effect** – Improves productivity, science output, and reduces unrest.
// /// **Source** – `education = Σ(education_building_output)`.
// /// **Purpose** - Measure of the citizenry's knowledge.
// /// **Effect** - Improves productivity, science output, and reduces unrest.
// /// **Source** - `education = Σ(education_building_output)`.
// pub education: GenericStat,
// /// Tourism revenue.
// ///
// /// **Purpose** – Income generated by visitors.
// /// **Effect** – Provides an additional income stream.
// /// **Source** – `tourism = number_of_tourists × price_per_tourist`.
// /// **Purpose** - Income generated by visitors.
// /// **Effect** - Provides an additional income stream.
// /// **Source** - `tourism = number_of_tourists x price_per_tourist`.
// pub tourism: GenericStat,
// /// Cultural influence over the region.
// ///
// /// **Purpose** – Measure of soft power.
// /// **Effect** – Grants diplomatic bonuses and increases sway in the empire.
// /// **Source** – `influence = culture × population`.
// /// **Purpose** - Measure of soft power.
// /// **Effect** - Grants diplomatic bonuses and increases sway in the empire.
// /// **Source** - `influence = culture x population`.
// pub influence: GenericStat,
// ──────────────────────── Military ────────────────────────
/// Overall military power.
///
/// **Purpose** – Composite measure of combat capability.
/// **Effect** – Determines defensive and offensive strength.
/// **Source** – Sum of `army`, `strength`, `fortification`, etc.
/// **Purpose** - Composite measure of combat capability.
/// **Effect** - Determines defensive and offensive strength.
/// **Source** - Sum of `army`, `strength`, `fortification`, etc.
pub military: GenericStat,
/// Number of battle‑ready units.
/// Number of battle-ready units.
///
/// **Purpose** – Size of the active army.
/// **Effect** – Directly dictates defense and attack potential.
/// **Source** – Sum of all trained and equipped units.
/// **Purpose** - Size of the active army.
/// **Effect** - Directly dictates defense and attack potential.
/// **Source** - Sum of all trained and equipped units.
pub army: GenericStat,
/// Composite strength of the army.
///
/// **Purpose** – Tech, training, and equipment bonuses aggregated.
/// **Effect** – Determines combat effectiveness and required force to defeat an enemy.
/// **Source** – `strength = Σ(unit_strength) × tech_bonus × training_bonus`.
/// **Purpose** - Tech, training, and equipment bonuses aggregated.
/// **Effect** - Determines combat effectiveness and required force to defeat an enemy.
/// **Source** - `strength = Σ(unit_strength) x tech_bonus x training_bonus`.
pub strength: GenericStat,
/// Defensive bonus from fortifications.
///
/// **Purpose** – Wall and tower defenses.
/// **Effect** – Adds a multiplier to overall defense.
/// **Source** – `fortification = Σ(fortification_building_bonus)`.
/// **Purpose** - Wall and tower defenses.
/// **Effect** - Adds a multiplier to overall defense.
/// **Source** - `fortification = Σ(fortification_building_bonus)`.
pub fortification: GenericStat,
/// Threat level facing the entity.
///
/// **Purpose** – Likelihood of being attacked.
/// **Effect** – Triggers early warning alerts and strategic decisions.
/// **Source** – `threat = (enemy_proximity + enemy_strength) / defense`.
/// **Purpose** - Likelihood of being attacked.
/// **Effect** - Triggers early warning alerts and strategic decisions.
/// **Source** - `threat = (enemy_proximity + enemy_strength) / defense`.
pub threat: GenericStat,
// ──────────────────────── Infrastructure ────────────────────────
/// Total infrastructure power.
///
/// **Purpose** – Overall built‑environment capacity.
/// **Effect** – Supports population size and efficiency.
/// **Source** – Sum of all infrastructure components.
/// **Purpose** - Overall built-environment capacity.
/// **Effect** - Supports population size and efficiency.
/// **Source** - Sum of all infrastructure components.
pub infrastructure: GenericStat,
/// Bureaucratic power.
///
/// **Purpose** – Efficiency of the city’s administrative machinery.
/// **Effect** – Improves resource management and policy implementation.
/// **Source** – `bureaucracy = Σ(bureaucracy_building_output)`.
/// **Purpose** - Efficiency of the city's administrative machinery.
/// **Effect** - Improves resource management and policy implementation.
/// **Source** - `bureaucracy = Σ(bureaucracy_building_output)`.
pub bureaucracy: GenericStat,
/// Transportation level.
///
/// **Purpose** – Availability and quality of transport infrastructure.
/// **Effect** – Impacts logistics, mobility, and trade.
/// **Source** – `transportation = Σ(transport_building_output)`.
/// **Purpose** - Availability and quality of transport infrastructure.
/// **Effect** - Impacts logistics, mobility, and trade.
/// **Source** - `transportation = Σ(transport_building_output)`.
pub transportation: GenericStat,
/// Sprawl / urban density.
///
/// **Purpose** – Measure of city sprawl and clutter.
/// **Effect** – Affects health, happiness, and infrastructure efficiency.
/// **Source** – `sprawl = Σ(sprawl_factor)`.
/// **Purpose** - Measure of city sprawl and clutter.
/// **Effect** - Affects health, happiness, and infrastructure efficiency.
/// **Source** - `sprawl = Σ(sprawl_factor)`.
pub sprawl: GenericStat,
/// Health infrastructure quality.
///
/// **Purpose** – Public health capacity.
/// **Effect** – Affects population health and can generate unrest.
/// **Source** – `health = output_of_health_function` (influenced by sanitation, disease spread, etc.).
/// **Purpose** - Public health capacity.
/// **Effect** - Affects population health and can generate unrest.
/// **Source** - `health = output_of_health_function` (influenced by sanitation, disease spread, etc.).
pub health: GenericStat,
}
/// Strategic context and meta‑data for an entity.
/// Strategic context and meta-data for an entity.
///
/// All fields are intentionally simple – the logic that interprets them
/// All fields are intentionally simple - the logic that interprets them
/// lives in separate modules (e.g. `map`, `network`, `governance`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MetaStats {
// ──── Location & Spatial Data (hidden) ───────────────────────────────
/// Cartesian coordinates of the entity on the world map.
///
/// **Purpose** – Position of the entity in the simulation grid.
/// **Effect** – Used for distance calculations, visibility, and
/// map‑based event logic.
/// **Source** – Supplied by the map generator.
/// **Purpose** - Position of the entity in the simulation grid.
/// **Effect** - Used for distance calculations, visibility, and
/// map-based event logic.
/// **Source** - Supplied by the map generator.
pub position: Position,
/// Identifier for the capital
@ -228,61 +228,61 @@ pub struct MetaStats {
// /// List of nearby resource nodes (mines, forests, farms, etc.).
// ///
// /// **Purpose** – Resource map around the entity.
// /// **Effect** – Drives the entity’s specialization and determines
// /// **Purpose** - Resource map around the entity.
// /// **Effect** - Drives the entity's specialization and determines
// /// the default output mix.
// /// **Source** – `resources = filter(resource_list, distance ≤ detection_radius)`.
// /// **Source** - `resources = filter(resource_list, distance ≤ detection_radius)`.
// pub resources: Vec<String>,
// /// The entity’s chosen specialization tag
// /// The entity's chosen specialization tag
// /// (e.g., “Agricultural Hub”, “Industrial Center”).
// ///
// /// **Purpose** – Identity that dictates default production multipliers.
// /// **Effect** – Alters output curves and trade attractiveness.
// /// **Source** – `specialization = tag_assigned_by_player_or_ai`.
// /// **Purpose** - Identity that dictates default production multipliers.
// /// **Effect** - Alters output curves and trade attractiveness.
// /// **Source** - `specialization = tag_assigned_by_player_or_ai`.
// pub specialization: String,
// ──── Strategic Positioning (hidden + public) ─────────────────────
/// Current governor or leader assigned to the entity.
///
/// **Purpose** – Leadership identity.
/// **Effect** – Adds personal bonuses and may modify policies
/// **Purpose** - Leadership identity.
/// **Effect** - Adds personal bonuses and may modify policies
/// or diplomatic stance.
/// **Source** – `governor = selected_leader_uuid`.
/// **Source** - `governor = selected_leader_uuid`.
pub governor: CharacterId,
// /// The entity’s classification (capital, trade hub, frontier post, etc.).
// /// The entity's classification (capital, trade hub, frontier post, etc.).
// ///
// /// **Purpose** – Functional role within the empire.
// /// **Effect** – Alters base production, tax rates, and
// /// **Purpose** - Functional role within the empire.
// /// **Effect** - Alters base production, tax rates, and
// /// certain event probabilities.
// /// **Source** – `role = tag_assigned_by_player_or_ai`.
// /// **Source** - `role = tag_assigned_by_player_or_ai`.
// pub role: String,
/// The faction or empire to which the entity currently belongs.
///
/// **Purpose** – Political affiliation.
/// **Effect** – Determines diplomatic relations, war status,
/// and access to empire‑wide bonuses.
/// **Source** – `faction = current_faction_uuid`.
/// **Purpose** - Political affiliation.
/// **Effect** - Determines diplomatic relations, war status,
/// and access to empire-wide bonuses.
/// **Source** - `faction = current_faction_uuid`.
pub faction: FactionId,
/// UIDs of all entities the entity is linked to (roads, trade routes,
/// alliances, war declarations, etc.).
///
/// **Purpose** – Connectivity network.
/// **Effect** – Influences economic, military, and diplomatic
/// **Purpose** - Connectivity network.
/// **Effect** - Influences economic, military, and diplomatic
/// interactions.
/// **Source** – `links = Vec<Uuid>` collected from the entity’s
/// **Source** - `links = Vec<Uuid>` collected from the entity's
/// network manager.
pub links: Vec<TownId>,
/// Prestige / reputation of the entity in the eyes of the empire
/// and foreign powers.
///
/// **Purpose** – Social standing metric.
/// **Effect** – Affects diplomatic influence, trade bonuses,
/// **Purpose** - Social standing metric.
/// **Effect** - Affects diplomatic influence, trade bonuses,
/// and event outcomes.
/// **Source** – `prestige = calculate_prestige(...)`.
/// **Source** - `prestige = calculate_prestige(...)`.
pub prestige: usize,
}
@ -380,18 +380,18 @@ thin_newtype!(FactionId, usize);
// --- TRAITS ---------------------------------------------------------------
/// A stat is a *game value* that can be converted to two different
/// normalised ranges – a 50‑point range for “gaming” logic and a
/// 10‑point range for “roll & UI” logic. The trait also exposes the
/// normalised ranges - a 50-point range for “gaming” logic and a
/// 10-point range for “roll & UI” logic. The trait also exposes the
/// underlying raw value and its visibility.
///
// TODO[7]: Change this with Deref+From
pub trait GameStat {
/// Convert the raw integer to a 50‑point scale.
/// Convert the raw integer to a 50-point scale.
fn to_50(&self) -> isize {
(self.get_value().clamp(0, 70) - 10).min(50)
}
/// Convert the raw integer to a 10‑point scale.
/// Convert the raw integer to a 10-point scale.
fn to_10(&self) -> isize {
self.to_50() / 5
}

View File

@ -10,12 +10,12 @@ use crate::stats::ListStats;
use crate::stats::OverallStats;
use crate::stats::StatPair;
/// Creates a thin, deref‑able wrapper around an inner type.
/// Creates a thin, deref-able wrapper around an inner type.
#[macro_export]
macro_rules! thin_newtype {
($name:ident, $inner:ty) => {
/// Thin wrapper that derefs to the inner type.
/// Ideal for zero‑overhead new‑type patterns.
/// Ideal for zero-overhead new-type patterns.
#[repr(transparent)]
#[derive(
Debug,

View File

@ -17,7 +17,7 @@ pub fn is_a_epoch_directory(_path: &Path) -> Result<(), EpochError> {
todo!()
}
/// Validate that the configuration file at `path` is well‑formed.
/// Validate that the configuration file at `path` is well-formed.
pub fn is_config_well_formated(_path: &Path) -> Result<(), EpochError> {
todo!()
}