feat: adjudicate fights and wars
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good
Details
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good
Details
This commit is contained in:
parent
59db826aa2
commit
88d3fc4695
|
|
@ -248,9 +248,9 @@ and [`docs/presentation-design.md`](docs/presentation-design.md).
|
|||
blockers, explaining avoided/dampened/destroyed outcomes.
|
||||
- [x] Resolve resident and positioned characters deterministically; document
|
||||
the initial policy for characters currently in transit.
|
||||
- [ ] Add generic multi-side conflict records, participant validation, pure
|
||||
- [x] Add generic multi-side conflict records, participant validation, pure
|
||||
fight/war round resolution, victory, stalemate, and explicit ending.
|
||||
- [ ] Add conflict commands and focused fight/war aliases with preview-first,
|
||||
- [x] Add conflict commands and focused fight/war aliases with preview-first,
|
||||
worktree-only application and restore/stage/commit/revert coverage.
|
||||
- [ ] Cover every adjudication level/disposition, corruption, allocation limits,
|
||||
multi-side conflict, and diffusion/conflict integration.
|
||||
|
|
|
|||
|
|
@ -74,7 +74,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, reviewable/committed revert, backed-up pruning, and explicit hard reset | Branching and merging |
|
||||
| Entities | Add, edit, list, inspect, diff, and delete six built-in types | Custom types and custom fields; bulk operations |
|
||||
| Generation and simulation | Generate deterministic seeded worlds; define roads; preview/apply travel and spatial event diffusion; record player rolls and explicit game-master adjudications (`influx`) | Automatic arrival targeting, conflict simulation, and setting template packs |
|
||||
| Generation and simulation | Generate deterministic seeded worlds; roads, travel, event diffusion/arrival resolution; record external rolls and adjudications; run multi-side fights and wars | Setting template packs and interpolated in-transit positions |
|
||||
| Interfaces | Complete CLI; `efo-tui` browser and entity editor | TUI staging/commits; GUI/web (out of scope) |
|
||||
|
||||
`efo show all` gives a world overview; per-type commands such as
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
||||
pub mod adjudicate;
|
||||
pub mod conflict;
|
||||
pub mod diffuse;
|
||||
pub mod entity_generic;
|
||||
pub mod epoch;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,450 @@
|
|||
//! Preview-first fight and war commands.
|
||||
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use clap::{Args, Subcommand, ValueEnum};
|
||||
use lib_efo::{
|
||||
adjudication::{
|
||||
AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec,
|
||||
apply_to_world, preview,
|
||||
},
|
||||
conflict::{
|
||||
ConflictKind, ConflictStatus, ParticipantRef, conflict_id, create_conflict, find_conflict,
|
||||
finish_round,
|
||||
},
|
||||
entity::EntityIdentifier,
|
||||
stats::EntityType,
|
||||
workspace::Workspace,
|
||||
};
|
||||
|
||||
use crate::{commands::adjudicate::parse_effect, error::AppError};
|
||||
|
||||
/// Generic conflict operations.
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum ConflictCmd {
|
||||
/// Preview or create a fight/war.
|
||||
Start(ConflictStartArgs),
|
||||
/// List fights and wars.
|
||||
List,
|
||||
/// Show participants and applied rounds.
|
||||
Show(ConflictShowArgs),
|
||||
/// Preview or adjudicate the next round.
|
||||
Advance(ConflictAdvanceArgs),
|
||||
/// Preview or explicitly end a conflict.
|
||||
End(ConflictEndArgs),
|
||||
}
|
||||
|
||||
/// New conflict definition.
|
||||
#[derive(Debug, Args)]
|
||||
#[command(
|
||||
after_long_help = "EXAMPLE:\n efo conflict start 'Bridge fight' --kind fight --side red:town:Haven --side blue:org:Guild --apply"
|
||||
)]
|
||||
pub struct ConflictStartArgs {
|
||||
/// Human conflict name.
|
||||
name: String,
|
||||
/// Bounded fight or persistent war.
|
||||
#[arg(long, value_enum)]
|
||||
kind: ConflictKind,
|
||||
/// SIDE:KIND:ENTITY[:WEIGHT]; repeat for every participant.
|
||||
#[arg(long, required = true, value_name = "SIDE:KIND:ENTITY[:WEIGHT]")]
|
||||
side: Vec<String>,
|
||||
/// Create the conflict in the worktree; preview is the default.
|
||||
#[arg(long)]
|
||||
apply: bool,
|
||||
}
|
||||
|
||||
/// Existing conflict selector.
|
||||
#[derive(Debug, Args)]
|
||||
pub struct ConflictShowArgs {
|
||||
/// Name/prefix or @UUID.
|
||||
conflict: String,
|
||||
}
|
||||
|
||||
/// One adjudicated round.
|
||||
#[derive(Debug, Args)]
|
||||
#[command(
|
||||
after_long_help = "EXAMPLE:\n efo conflict advance 'Bridge fight' --side-outcome red:good:applied --side-outcome blue:bad:dampened --result 'players rolled 11 and 4' --apply"
|
||||
)]
|
||||
pub struct ConflictAdvanceArgs {
|
||||
/// Name/prefix or @UUID.
|
||||
conflict: String,
|
||||
/// SIDE:LEVEL:DISPOSITION; exactly one for every active side.
|
||||
#[arg(long, required = true, value_name = "SIDE:LEVEL:DISPOSITION")]
|
||||
side_outcome: Vec<String>,
|
||||
/// External results retained verbatim.
|
||||
#[arg(long, default_value = "not recorded")]
|
||||
result: String,
|
||||
/// Shared explicit STAT:DELTA; omit for progressive policy defaults.
|
||||
#[arg(long, value_name = "STAT:DELTA")]
|
||||
effect: Vec<String>,
|
||||
/// Optional game-master explanation.
|
||||
#[arg(long, default_value = "")]
|
||||
note: String,
|
||||
/// Complete replacement adjudication policy JSON.
|
||||
#[arg(long)]
|
||||
config: Option<std::path::PathBuf>,
|
||||
/// Apply the round atomically; preview is the default.
|
||||
#[arg(long)]
|
||||
apply: bool,
|
||||
}
|
||||
|
||||
/// Explicit conflict ending.
|
||||
#[derive(Debug, Args)]
|
||||
pub struct ConflictEndArgs {
|
||||
/// Name/prefix or @UUID.
|
||||
conflict: String,
|
||||
/// Why the game master ended it.
|
||||
#[arg(long)]
|
||||
reason: String,
|
||||
/// Update the worktree; preview is the default.
|
||||
#[arg(long)]
|
||||
apply: bool,
|
||||
}
|
||||
|
||||
/// Dispatch conflict operations.
|
||||
pub fn handle(command: &ConflictCmd) -> Result<(), AppError> {
|
||||
match command {
|
||||
ConflictCmd::Start(args) => start(args),
|
||||
ConflictCmd::List => list(),
|
||||
ConflictCmd::Show(args) => show(args),
|
||||
ConflictCmd::Advance(args) => advance(args),
|
||||
ConflictCmd::End(args) => end(args),
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview and optionally create a conflict.
|
||||
fn start(args: &ConflictStartArgs) -> Result<(), AppError> {
|
||||
let mut workspace = Workspace::open(Path::new("."))?;
|
||||
let mut participants = args
|
||||
.side
|
||||
.iter()
|
||||
.map(|raw| parse_participant(&workspace.worktree.world, raw))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
participants.sort_unstable_by_key(|participant| participant.id);
|
||||
let id = conflict_id(&args.name, args.kind, &participants);
|
||||
let conflict = create_conflict(
|
||||
&workspace.worktree.world,
|
||||
id,
|
||||
args.name.clone(),
|
||||
args.kind,
|
||||
participants,
|
||||
)?;
|
||||
if workspace.worktree.world.conflicts.contains_key(&id) {
|
||||
return Err(lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"conflict @{} already exists",
|
||||
id
|
||||
))
|
||||
.into());
|
||||
}
|
||||
let mut output = format!(
|
||||
"Conflict preview · {} · {:?} · @{}\n",
|
||||
conflict.name, conflict.kind, conflict.id
|
||||
);
|
||||
for participant in &conflict.participants {
|
||||
let entity = workspace
|
||||
.worktree
|
||||
.world
|
||||
.find_entity_strict(participant.id, Some(participant.entity_type))?;
|
||||
output.push_str(&format!(
|
||||
"• {} · {} ({:?}) · weight {}\n",
|
||||
participant.side, entity.name, participant.entity_type, participant.committed_weight
|
||||
));
|
||||
}
|
||||
if !args.apply {
|
||||
output.push_str("Nothing changed. Re-run with `--apply` to update the worktree.\n");
|
||||
print!("{output}");
|
||||
return Ok(());
|
||||
}
|
||||
workspace.worktree.world.conflicts.insert(id, conflict);
|
||||
workspace.save_worktree("start conflict")?;
|
||||
output.push_str("✓ Conflict stored in the worktree. Undo: efo restore --worktree --all\n");
|
||||
print!("{output}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List conflicts in stable UUID order.
|
||||
fn list() -> Result<(), AppError> {
|
||||
let workspace = Workspace::open(Path::new("."))?;
|
||||
let mut output = format!("Conflicts · {}\n", workspace.worktree.world.conflicts.len());
|
||||
for conflict in workspace.worktree.world.conflicts.values() {
|
||||
output.push_str(&format!(
|
||||
"• {} · {:?} · {} · round {} · @{}\n",
|
||||
conflict.name,
|
||||
conflict.kind,
|
||||
status_label(&conflict.status),
|
||||
conflict.round,
|
||||
conflict.id
|
||||
));
|
||||
}
|
||||
print!("{output}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Show one conflict.
|
||||
fn show(args: &ConflictShowArgs) -> Result<(), AppError> {
|
||||
let workspace = Workspace::open(Path::new("."))?;
|
||||
let conflict = find_conflict(&workspace.worktree.world, &args.conflict)?;
|
||||
let mut output = format!(
|
||||
"{} · {:?} · {} · round {} · @{}\n",
|
||||
conflict.name,
|
||||
conflict.kind,
|
||||
status_label(&conflict.status),
|
||||
conflict.round,
|
||||
conflict.id
|
||||
);
|
||||
for participant in &conflict.participants {
|
||||
let entity = workspace
|
||||
.worktree
|
||||
.world
|
||||
.find_entity_strict(participant.id, Some(participant.entity_type))?;
|
||||
output.push_str(&format!(
|
||||
"• {} · {} ({:?}){}\n",
|
||||
participant.side,
|
||||
entity.name,
|
||||
participant.entity_type,
|
||||
if participant.removed {
|
||||
" · removed"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
));
|
||||
}
|
||||
output.push_str(&format!("Rounds · {}\n", conflict.rounds.len()));
|
||||
print!("{output}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Preview and optionally apply one complete round.
|
||||
fn advance(args: &ConflictAdvanceArgs) -> Result<(), AppError> {
|
||||
let mut workspace = Workspace::open(Path::new("."))?;
|
||||
let conflict = find_conflict(&workspace.worktree.world, &args.conflict)?.clone();
|
||||
if !conflict.status.can_advance() {
|
||||
return Err(lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"{} is already {}",
|
||||
conflict.name,
|
||||
status_label(&conflict.status)
|
||||
))
|
||||
.into());
|
||||
}
|
||||
let outcomes = parse_outcomes(&args.side_outcome)?;
|
||||
let active_sides = conflict
|
||||
.participants
|
||||
.iter()
|
||||
.filter(|participant| !participant.removed)
|
||||
.map(|participant| participant.side.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
if outcomes.keys().cloned().collect::<HashSet<_>>() != active_sides {
|
||||
return Err(lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"provide exactly one --side-outcome for each active side: {}",
|
||||
active_sides.into_iter().collect::<Vec<_>>().join(", ")
|
||||
))
|
||||
.into());
|
||||
}
|
||||
let config = match &args.config {
|
||||
Some(path) => AdjudicationConfig::load(path)?,
|
||||
None => AdjudicationConfig::embedded()?,
|
||||
};
|
||||
let effects = args
|
||||
.effect
|
||||
.iter()
|
||||
.map(|raw| parse_effect(raw))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut reports = Vec::new();
|
||||
let mut removed = HashSet::new();
|
||||
let mut output = format!(
|
||||
"Conflict round preview · {} · round {}\n",
|
||||
conflict.name,
|
||||
conflict.round + 1
|
||||
);
|
||||
for participant in conflict
|
||||
.participants
|
||||
.iter()
|
||||
.filter(|participant| !participant.removed)
|
||||
{
|
||||
let (level, disposition) = outcomes[&participant.side];
|
||||
let target = workspace
|
||||
.worktree
|
||||
.world
|
||||
.find_entity_strict(participant.id, Some(participant.entity_type))?;
|
||||
let spec = AdjudicationSpec {
|
||||
level,
|
||||
disposition,
|
||||
source: conflict.id,
|
||||
external_result: args.result.clone(),
|
||||
note: args.note.clone(),
|
||||
effects: effects.clone(),
|
||||
policy_id: config.policy_id.clone(),
|
||||
};
|
||||
let report = preview(&config, &spec, target, conflict.round + 1)?;
|
||||
if disposition == AdjudicationDisposition::Destroyed {
|
||||
removed.insert(participant.id);
|
||||
}
|
||||
output.push_str(&format!(
|
||||
"• {} · {} · {:?}/{:?}",
|
||||
participant.side, target.name, level, disposition
|
||||
));
|
||||
for change in &report.changes {
|
||||
output.push_str(&format!(
|
||||
" · {:?} {} → {}",
|
||||
change.stat, change.before, change.after
|
||||
));
|
||||
}
|
||||
output.push('\n');
|
||||
reports.push((participant.entity_type, report));
|
||||
}
|
||||
let mut projected = conflict.clone();
|
||||
finish_round(
|
||||
&mut projected,
|
||||
reports.iter().map(|(_, report)| report.id).collect(),
|
||||
&removed,
|
||||
)?;
|
||||
output.push_str(&format!("Result · {}\n", status_label(&projected.status)));
|
||||
if !args.apply {
|
||||
output.push_str("Nothing changed. Re-run with `--apply` to update the worktree.\n");
|
||||
print!("{output}");
|
||||
return Ok(());
|
||||
}
|
||||
let mut updated = workspace.worktree.world.clone();
|
||||
for (kind, report) in &reports {
|
||||
updated = apply_to_world(&updated, &config, report, *kind)?;
|
||||
}
|
||||
updated.conflicts.insert(projected.id, projected);
|
||||
workspace.worktree.world = updated;
|
||||
workspace.save_worktree("advance conflict")?;
|
||||
output.push_str("✓ Round stored in the worktree. Undo: efo restore --worktree --all\n");
|
||||
print!("{output}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Preview and optionally explicitly end a conflict.
|
||||
fn end(args: &ConflictEndArgs) -> Result<(), AppError> {
|
||||
if args.reason.trim().is_empty() {
|
||||
return Err(
|
||||
lib_efo::conflict::ConflictError::Invalid("end reason cannot be empty".into()).into(),
|
||||
);
|
||||
}
|
||||
let mut workspace = Workspace::open(Path::new("."))?;
|
||||
let id = find_conflict(&workspace.worktree.world, &args.conflict)?.id;
|
||||
let name = workspace.worktree.world.conflicts[&id].name.clone();
|
||||
let mut output = format!("Conflict end preview · {name}\nReason · {}\n", args.reason);
|
||||
if !args.apply {
|
||||
output.push_str("Nothing changed. Re-run with `--apply` to update the worktree.\n");
|
||||
print!("{output}");
|
||||
return Ok(());
|
||||
}
|
||||
workspace
|
||||
.worktree
|
||||
.world
|
||||
.conflicts
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| lib_efo::conflict::ConflictError::Missing(args.conflict.clone()))?
|
||||
.status = ConflictStatus::Ended {
|
||||
reason: args.reason.clone(),
|
||||
};
|
||||
workspace.save_worktree("end conflict")?;
|
||||
output.push_str("✓ Conflict ended in the worktree. Undo: efo restore --worktree --all\n");
|
||||
print!("{output}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parse one participant selector.
|
||||
fn parse_participant(
|
||||
world: &lib_efo::epoch::EpochInfo,
|
||||
raw: &str,
|
||||
) -> Result<ParticipantRef, AppError> {
|
||||
let parts = raw.split(':').collect::<Vec<_>>();
|
||||
if !(3..=4).contains(&parts.len()) {
|
||||
return Err(lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"participant `{raw}` must use SIDE:KIND:ENTITY[:WEIGHT]"
|
||||
))
|
||||
.into());
|
||||
}
|
||||
let kind = parse_kind(parts[1])?;
|
||||
let identifier = if let Some(id) = parts[2].strip_prefix('@') {
|
||||
EntityIdentifier::Id(id.into())
|
||||
} else {
|
||||
EntityIdentifier::Name(parts[2].into())
|
||||
};
|
||||
let entity = world.find_entity_of_type(&Some(identifier), &kind)?;
|
||||
let weight = parts
|
||||
.get(3)
|
||||
.map_or(Ok(1), |value| value.parse::<u32>())
|
||||
.map_err(|_| {
|
||||
lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"participant `{raw}` has an invalid weight"
|
||||
))
|
||||
})?;
|
||||
Ok(ParticipantRef {
|
||||
entity_type: kind,
|
||||
id: entity.id,
|
||||
side: parts[0].into(),
|
||||
committed_weight: weight,
|
||||
removed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse a stored entity kind.
|
||||
fn parse_kind(raw: &str) -> Result<EntityType, AppError> {
|
||||
match raw.to_ascii_lowercase().as_str() {
|
||||
"character" | "chr" => Ok(EntityType::Character),
|
||||
"town" => Ok(EntityType::Town),
|
||||
"org" | "organization" | "organisation" => Ok(EntityType::Organization),
|
||||
"event" => Ok(EntityType::Event),
|
||||
"calamity" => Ok(EntityType::Calamity),
|
||||
"blocker" => Ok(EntityType::Blocker),
|
||||
_ => Err(
|
||||
lib_efo::conflict::ConflictError::Invalid(format!("unknown entity kind `{raw}`"))
|
||||
.into(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse and reject duplicate side outcomes.
|
||||
fn parse_outcomes(
|
||||
raw: &[String],
|
||||
) -> Result<BTreeMap<String, (AdjudicationLevel, AdjudicationDisposition)>, AppError> {
|
||||
let mut outcomes = BTreeMap::new();
|
||||
for value in raw {
|
||||
let parts = value.split(':').collect::<Vec<_>>();
|
||||
if parts.len() != 3 {
|
||||
return Err(lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"outcome `{value}` must use SIDE:LEVEL:DISPOSITION"
|
||||
))
|
||||
.into());
|
||||
}
|
||||
let level = AdjudicationLevel::from_str(parts[1], true).map_err(|_| {
|
||||
lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"unknown adjudication level `{}`",
|
||||
parts[1]
|
||||
))
|
||||
})?;
|
||||
let disposition = AdjudicationDisposition::from_str(parts[2], true).map_err(|_| {
|
||||
lib_efo::conflict::ConflictError::Invalid(format!("unknown disposition `{}`", parts[2]))
|
||||
})?;
|
||||
if outcomes
|
||||
.insert(parts[0].into(), (level, disposition))
|
||||
.is_some()
|
||||
{
|
||||
return Err(lib_efo::conflict::ConflictError::Invalid(format!(
|
||||
"side `{}` has more than one outcome",
|
||||
parts[0]
|
||||
))
|
||||
.into());
|
||||
}
|
||||
}
|
||||
Ok(outcomes)
|
||||
}
|
||||
|
||||
/// Compact lifecycle label.
|
||||
fn status_label(status: &ConflictStatus) -> String {
|
||||
match status {
|
||||
ConflictStatus::Planned => "planned".into(),
|
||||
ConflictStatus::Active => "active".into(),
|
||||
ConflictStatus::Stalemate => "stalemate".into(),
|
||||
ConflictStatus::Won { side } => format!("won by {side}"),
|
||||
ConflictStatus::Ended { reason } => format!("ended: {reason}"),
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
use lib_efo::{
|
||||
adjudication::AdjudicationError,
|
||||
conflict::ConflictError,
|
||||
error::{EpochError, StorageError},
|
||||
repository_format::FormatError,
|
||||
simulation::SimulationError,
|
||||
|
|
@ -20,6 +21,9 @@ use thiserror::Error;
|
|||
/// All errors that can bubble up to the CLI.
|
||||
#[derive(Debug, Error, Diagnostic)]
|
||||
pub enum AppError {
|
||||
/// Conflict validation or lifecycle transition failed.
|
||||
#[error("Conflict stopped: {0}")]
|
||||
Conflict(#[from] ConflictError),
|
||||
/// External-roll adjudication validation or application failed.
|
||||
#[error("Adjudication stopped: {0}")]
|
||||
Adjudication(#[from] AdjudicationError),
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ use clap::{Parser, Subcommand};
|
|||
use crate::{
|
||||
commands::{
|
||||
adjudicate::AdjudicateCmd,
|
||||
conflict::ConflictCmd,
|
||||
diffuse::DiffuseCmd,
|
||||
entity_generic::EntitySubCommands,
|
||||
epoch::cli_epoch::EpochCmd,
|
||||
|
|
@ -74,6 +75,9 @@ struct Cli {
|
|||
/// argument structure.
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum TopLevelCmd {
|
||||
/// Create and adjudicate fights or wars.
|
||||
#[command(subcommand, visible_aliases = ["fight", "war"])]
|
||||
Conflict(ConflictCmd),
|
||||
/// Record and apply a player roll interpreted by the game master.
|
||||
#[command(subcommand, visible_alias = "influx")]
|
||||
Adjudicate(AdjudicateCmd),
|
||||
|
|
@ -185,6 +189,7 @@ fn main() -> miette::Result<()> {
|
|||
/// stdout and returned as a `miette::Result<()>`.
|
||||
fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
|
||||
match cli.command {
|
||||
TopLevelCmd::Conflict(cmd) => commands::conflict::handle(&cmd),
|
||||
TopLevelCmd::Adjudicate(cmd) => commands::adjudicate::handle(&cmd),
|
||||
TopLevelCmd::Init(cmd) => commands::init::init(&cmd),
|
||||
TopLevelCmd::Recover(cmd) => commands::safety::handle_recover(&cmd),
|
||||
|
|
|
|||
|
|
@ -85,6 +85,8 @@ fn help_version_and_invalid_invocations_follow_cli_conventions() {
|
|||
&["gen", "event", "--help"][..],
|
||||
&["adjudicate", "--help"][..],
|
||||
&["influx", "preview", "--help"][..],
|
||||
&["conflict", "--help"][..],
|
||||
&["fight", "--help"][..],
|
||||
] {
|
||||
let output = efo(&repo, args);
|
||||
assert_success(&output);
|
||||
|
|
@ -107,6 +109,174 @@ fn help_version_and_invalid_invocations_follow_cli_conventions() {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fights_and_wars_are_adjudicated_previewed_and_reversible() {
|
||||
let repo = TestRepo::new();
|
||||
assert_success(&efo(&repo, &["init"]));
|
||||
assert_success(&efo(
|
||||
&repo,
|
||||
&["town", "add", "Haven", "--stats", "health:100"],
|
||||
));
|
||||
assert_success(&efo(
|
||||
&repo,
|
||||
&["org", "add", "Guild", "--stats", "health:100"],
|
||||
));
|
||||
assert_success(&efo(
|
||||
&repo,
|
||||
&["chr", "add", "Aria", "--stats", "health:100"],
|
||||
));
|
||||
assert_success(&efo(&repo, &["stage", "--all"]));
|
||||
assert_success(&efo(&repo, &["commit", "-m", "Create combatants"]));
|
||||
let baseline = snapshot(&repo, 0);
|
||||
|
||||
let start_args = [
|
||||
"conflict",
|
||||
"start",
|
||||
"Bridge War",
|
||||
"--kind",
|
||||
"war",
|
||||
"--side",
|
||||
"red:town:Haven",
|
||||
"--side",
|
||||
"blue:org:Guild:2",
|
||||
"--side",
|
||||
"green:chr:Aria",
|
||||
];
|
||||
let preview = efo(&repo, &start_args);
|
||||
assert_success(&preview);
|
||||
assert!(stdout(&preview).contains("Conflict preview"));
|
||||
assert_eq!(snapshot(&repo, 0), baseline);
|
||||
let mut apply_start = start_args.to_vec();
|
||||
apply_start.push("--apply");
|
||||
assert_success(&efo(&repo, &apply_start));
|
||||
assert_eq!(
|
||||
snapshot(&repo, 0)["conflicts"]
|
||||
.as_object()
|
||||
.expect("conflicts")
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
|
||||
assert_eq!(snapshot(&repo, 0), baseline);
|
||||
assert_success(&efo(&repo, &apply_start));
|
||||
|
||||
let first_round = [
|
||||
"conflict",
|
||||
"advance",
|
||||
"Bridge",
|
||||
"--side-outcome",
|
||||
"red:good:applied",
|
||||
"--side-outcome",
|
||||
"blue:bad:dampened",
|
||||
"--side-outcome",
|
||||
"green:excellent:destroyed",
|
||||
"--result",
|
||||
"three player rolls",
|
||||
];
|
||||
let round_preview = efo(&repo, &first_round);
|
||||
assert_success(&round_preview);
|
||||
assert!(stdout(&round_preview).contains("round 1"));
|
||||
assert!(stdout(&round_preview).contains("Result · active"));
|
||||
assert_eq!(
|
||||
snapshot(&repo, 0)["adjudications"]
|
||||
.as_object()
|
||||
.expect("records")
|
||||
.len(),
|
||||
0
|
||||
);
|
||||
let mut apply_round = first_round.to_vec();
|
||||
apply_round.push("--apply");
|
||||
assert_success(&efo(&repo, &apply_round));
|
||||
let after_round = snapshot(&repo, 0);
|
||||
let conflict = after_round["conflicts"]
|
||||
.as_object()
|
||||
.expect("conflicts")
|
||||
.values()
|
||||
.next()
|
||||
.expect("conflict");
|
||||
assert_eq!(conflict["round"], 1);
|
||||
assert_eq!(conflict["status"]["state"], "active");
|
||||
assert!(
|
||||
conflict["participants"]
|
||||
.as_array()
|
||||
.expect("participants")
|
||||
.iter()
|
||||
.any(|participant| participant["removed"] == true)
|
||||
);
|
||||
assert_eq!(
|
||||
after_round["characters"]
|
||||
.as_array()
|
||||
.expect("characters")
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
after_round["adjudications"]
|
||||
.as_object()
|
||||
.expect("records")
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
assert_success(&efo(&repo, &["stage", "--all"]));
|
||||
assert_success(&efo(&repo, &["commit", "-m", "First war round"]));
|
||||
|
||||
let before_end = snapshot(&repo, 0);
|
||||
let end_preview = efo(
|
||||
&repo,
|
||||
&[
|
||||
"conflict",
|
||||
"end",
|
||||
"Bridge",
|
||||
"--reason",
|
||||
"A negotiated pause",
|
||||
],
|
||||
);
|
||||
assert_success(&end_preview);
|
||||
assert!(stdout(&end_preview).contains("Nothing changed"));
|
||||
assert_eq!(snapshot(&repo, 0), before_end);
|
||||
assert_success(&efo(
|
||||
&repo,
|
||||
&[
|
||||
"conflict",
|
||||
"end",
|
||||
"Bridge",
|
||||
"--reason",
|
||||
"A negotiated pause",
|
||||
"--apply",
|
||||
],
|
||||
));
|
||||
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
|
||||
assert_eq!(snapshot(&repo, 0), before_end);
|
||||
|
||||
let decisive = efo(
|
||||
&repo,
|
||||
&[
|
||||
"war",
|
||||
"advance",
|
||||
"Bridge",
|
||||
"--side-outcome",
|
||||
"red:good:applied",
|
||||
"--side-outcome",
|
||||
"blue:apocalypse:destroyed",
|
||||
"--apply",
|
||||
],
|
||||
);
|
||||
assert_success(&decisive);
|
||||
assert!(stdout(&decisive).contains("won by red"));
|
||||
assert_success(&efo(&repo, &["stage", "--all"]));
|
||||
assert_success(&efo(&repo, &["commit", "-m", "Red wins"]));
|
||||
assert_success(&efo(&repo, &["revert", "3"]));
|
||||
let reverted = snapshot(&repo, 0);
|
||||
let conflict = reverted["conflicts"]
|
||||
.as_object()
|
||||
.expect("conflicts")
|
||||
.values()
|
||||
.next()
|
||||
.expect("conflict");
|
||||
assert_eq!(conflict["round"], 1);
|
||||
assert_eq!(conflict["status"]["state"], "active");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_adjudications_preview_apply_audit_and_restore() {
|
||||
let repo = TestRepo::new();
|
||||
|
|
|
|||
|
|
@ -177,6 +177,35 @@ effects are multiplied by that percentage. A destroyed event has 0% potency,
|
|||
stops an active frontier, and cannot start another diffusion; restore or revert
|
||||
the ruling to recover it. `efo adjudicate list EVENT` displays this state.
|
||||
|
||||
## Fights and wars
|
||||
|
||||
Conflicts are generic multi-side records whose participants remain ordinary
|
||||
entities. Start is preview-first:
|
||||
|
||||
```text
|
||||
efo conflict start "Bridge War" --kind war \
|
||||
--side red:town:Haven --side blue:org:Guild:2
|
||||
efo conflict start "Bridge War" --kind war \
|
||||
--side red:town:Haven --side blue:org:Guild:2 --apply
|
||||
```
|
||||
|
||||
Advance one round with exactly one external adjudication per active side:
|
||||
|
||||
```text
|
||||
efo conflict advance "Bridge War" \
|
||||
--side-outcome red:good:applied \
|
||||
--side-outcome blue:bad:dampened \
|
||||
--result "players rolled 11 and 4" [--apply]
|
||||
```
|
||||
|
||||
`fight` and `war` are visible aliases for `conflict`. Outcomes reuse the same
|
||||
levels, dispositions, progressive defaults, and explicit `--effect` overrides.
|
||||
`destroyed` removes a participant from this conflict but never deletes its
|
||||
entity. A fight stalemates after one unresolved round; a war stays active until
|
||||
one side remains. Use `conflict show`, `conflict list`, or
|
||||
`conflict end --reason ... [--apply]`. Every mutation affects only the
|
||||
worktree and supports restore, stage, commit, and historical revert.
|
||||
|
||||
## Generation and output
|
||||
|
||||
`efo gen character|town|event|exotic|calamity|blocker` prints generated content
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ absent.
|
|||
| [#15 Clamp stats](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/15) | Addressed: CLI/TUI mutations clamp normalized persistent stats to `0..=120`, event/blocker modifiers and growth to `-120..=120`, and population remains an unbounded non-negative count (or a bounded negative modifier). Workspace validation rejects bypassed invalid state. | Move these defaults into schemas if custom-stat domains become configurable. |
|
||||
| [#14 Build fsck](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/14) | Addressed for read-only validation: every epoch is parsed and checked for duplicate IDs, collection types, ordinary links, governors, and capitals. | Put serializer rewriting in a separately previewed repair command, not `fsck`. |
|
||||
| [#13 Add all cards into pre-events](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/13) | Explicitly deferred by the maintainer for this milestone. | Revisit only when requested. |
|
||||
| [#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 explicit game-master adjudications. | Deliver after adjudication persistence and diffusion integration; see `resolution-conflict-design.md`. |
|
||||
| [#12 Add fight/war](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/12) | Functionally complete: persistent multi-side fights/wars, mixed participants, per-side external adjudications, deterministic lifecycle, participant removal, explicit ending, aliases, validation, and recovery workflows are implemented. | Close the live tracker issue after review. |
|
||||
| [#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) | Functionally complete: `adjudicate`/`influx` records the external roll and all six levels/dispositions, supports progressive or explicit effects, persists source potency, and makes destroyed events stop diffusion. Audit, stale-state, restoration, and repository validation are covered. | Close the live tracker issue after review. |
|
||||
|
|
|
|||
|
|
@ -215,6 +215,7 @@ insertion order.
|
|||
## Issue #12: fight and war
|
||||
|
||||
Conflict reuses adjudication records instead of directly coupling entities.
|
||||
The implementation uses the versioned `epoch-forge/conflict-gm-1` ruleset.
|
||||
|
||||
```text
|
||||
ConflictState {
|
||||
|
|
@ -232,18 +233,17 @@ missing IDs, zero committed weight, and fewer than two sides are invalid.
|
|||
Side labels are user strings so organisations, coalitions, departments, or
|
||||
individuals fit the same model.
|
||||
|
||||
A fight is a bounded, normally single-resolution conflict. A war is persistent
|
||||
A fight is a bounded, single-resolution conflict. A war is persistent
|
||||
and advances in explicit rounds. Neither automatically creates/deletes normal
|
||||
entities. Resolution may propose stat changes and may generate ordinary Event
|
||||
entities through configuration; these appear in the worktree diff like other
|
||||
changes.
|
||||
entities. Resolution applies explicit or configured-default stat effects;
|
||||
rulesets that generate ordinary Event entities remain a future extension.
|
||||
|
||||
Proposed CLI:
|
||||
Implemented CLI:
|
||||
|
||||
```text
|
||||
efo conflict start NAME --kind fight --side red:town:Haven --side blue:org:Guild
|
||||
efo conflict preview CONFLICT [--rounds N]
|
||||
efo conflict advance CONFLICT [--rounds N] --apply
|
||||
efo conflict advance CONFLICT --side-outcome red:good:applied \
|
||||
--side-outcome blue:bad:dampened [--apply]
|
||||
efo conflict show CONFLICT
|
||||
efo conflict end CONFLICT --reason TEXT [--apply]
|
||||
efo fight ... # focused alias/help surface
|
||||
|
|
@ -252,9 +252,10 @@ efo war ... # focused alias/help surface
|
|||
|
||||
Starting and ending are preview-first worktree changes. Advancing resolves all
|
||||
sides in stable order, snapshots participant inputs for stale-state detection,
|
||||
and produces typed round reports. Victory and stalemate come solely from the
|
||||
versioned ruleset. A command cannot advance an ended conflict or silently
|
||||
reapply an already recorded round.
|
||||
and produces typed round reports. In the initial ruleset, a fight with multiple
|
||||
sides remaining stalemates after round one; a war remains active until one side
|
||||
remains; zero sides is a stalemate. A command cannot advance a finished
|
||||
conflict or silently reapply an already recorded round.
|
||||
|
||||
Acceptance gates cover two and three-sided conflicts, mixed entity types,
|
||||
fight completion, multi-round war, victory/stalemate, participant removal,
|
||||
|
|
@ -295,8 +296,8 @@ upgrade path under issue #17.
|
|||
future defaults; resolution atomically covers towns and selected
|
||||
resident/positioned characters, explains positioned/linked protection,
|
||||
records avoided targets, and stops diffusion when destroyed.
|
||||
5. Add generic conflict state and pure round resolution.
|
||||
6. Expose conflict/fight/war preview/apply commands and recovery tests.
|
||||
5. **Complete:** add generic conflict state and pure round resolution.
|
||||
6. **Complete:** expose conflict/fight/war preview/apply commands and recovery tests.
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -10,6 +10,18 @@ use crate::{epoch::EpochInfo, stats::EntityType};
|
|||
/// Stable ruleset used by this release.
|
||||
pub const DEFAULT_CONFLICT_RULESET: &str = "epoch-forge/conflict-gm-1";
|
||||
|
||||
/// Derive a stable conflict identity from its authored starting content.
|
||||
pub fn conflict_id(name: &str, kind: ConflictKind, participants: &[ParticipantRef]) -> Uuid {
|
||||
let bytes = serde_json::to_vec(&(name, kind, participants)).unwrap_or_default();
|
||||
let mut high = 0xcbf2_9ce4_8422_2325_u64;
|
||||
let mut low = 0x8422_2325_cbf2_9ce4_u64;
|
||||
for byte in bytes {
|
||||
high = (high ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
low = (low ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01d3);
|
||||
}
|
||||
Uuid::from_u128((u128::from(high) << 64) | u128::from(low))
|
||||
}
|
||||
|
||||
/// Whether a conflict is a bounded fight or persistent war.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ static SUB_NAME: &str = "epochinfo.json";
|
|||
///
|
||||
/// The wrapper exists mainly to give the collection a semantic type
|
||||
/// and to hide the internal representation.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Display)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Display)]
|
||||
#[display("{inner:?}")]
|
||||
pub struct TagList {
|
||||
/// The inner vector of tags
|
||||
|
|
|
|||
|
|
@ -713,7 +713,7 @@ impl Workspace {
|
|||
}
|
||||
}
|
||||
|
||||
/// Apply entity and summary inverses, refusing overlapping later edits.
|
||||
/// Apply entity and metadata inverses, refusing overlapping later edits.
|
||||
fn invert_world(
|
||||
before: &EpochInfo,
|
||||
changed: &EpochInfo,
|
||||
|
|
@ -735,13 +735,26 @@ fn invert_world(
|
|||
invert_collection!(calamities);
|
||||
invert_collection!(organizations);
|
||||
invert_collection!(blockers);
|
||||
if before.summary != changed.summary {
|
||||
if current.summary == changed.summary {
|
||||
current.summary = before.summary.clone();
|
||||
} else if current.summary != before.summary {
|
||||
return Err(WorkspaceError::Conflict("summary".into()));
|
||||
}
|
||||
macro_rules! invert_metadata {
|
||||
($field:ident) => {
|
||||
if before.$field != changed.$field {
|
||||
if current.$field == changed.$field {
|
||||
current.$field = before.$field.clone();
|
||||
} else if current.$field != before.$field {
|
||||
return Err(WorkspaceError::Conflict(stringify!($field).into()));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
invert_metadata!(rng_seed);
|
||||
invert_metadata!(tags);
|
||||
invert_metadata!(summary);
|
||||
invert_metadata!(roads);
|
||||
invert_metadata!(mobility);
|
||||
invert_metadata!(diffusions);
|
||||
invert_metadata!(adjudications);
|
||||
invert_metadata!(event_adjudications);
|
||||
invert_metadata!(conflicts);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue