diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index bf22cd2..7cd0115 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -243,6 +243,11 @@ These require user approval and are not part of the current implementation: ## Audit notes +- [x] Replace duplicated epoch/layer comparison code with a deterministic, + serializable `WorldDiff`, changed-field details, importance marks, and a + buffered CLI renderer (tracker issues #11 and part of #10). +- [ ] Tracker issue #13 is intentionally deferred at the maintainer's request. + - The old README described organisation/link/event interfaces absent from the parser; the rewritten docs now distinguish current and planned behavior. - The old demo `show` output, ignored `init --force`, and panicking `epoch diff` diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index e4198b6..33698d6 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -3,8 +3,7 @@ use std::path::Path; use lib_efo::{ - entity::Entity, - epoch::{EpochId, EpochIdentifier, EpochInfo}, + epoch::{EpochId, EpochIdentifier}, error::EpochError, workspace::Workspace, }; @@ -77,10 +76,13 @@ pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> { .transpose()? .unwrap_or(workspace.manifest.epoch_id); println!("Epoch {start_id} → {end_id}"); - print_world_diff( - &workspace.load_epoch(start_id)?, - &workspace.load_epoch(end_id)?, - )?; + print!( + "{}", + crate::commands::state::render_diff( + &workspace.load_epoch(start_id)?, + &workspace.load_epoch(end_id)? + ) + ); } cli_epoch::EpochCmd::Log(args) => { let mut id = Some(workspace.manifest.epoch_id); @@ -118,54 +120,3 @@ fn resolve_epoch(workspace: &Workspace, identifier: &EpochIdentifier) -> Result< .ok_or_else(|| EpochError::EpochNotFound(tag.clone()).into()), } } - -/// Print deterministic entity and summary changes between committed worlds. -fn print_world_diff(start: &EpochInfo, end: &EpochInfo) -> Result<(), AppError> { - let collections = [ - ("characters", &start.characters, &end.characters), - ("towns", &start.towns, &end.towns), - ("events", &start.events, &end.events), - ("calamities", &start.calamities, &end.calamities), - ("organisations", &start.organizations, &end.organizations), - ("blockers", &start.blockers, &end.blockers), - ]; - let mut changes = 0; - for (label, before, after) in collections { - let added = after - .iter() - .filter(|entity| !before.iter().any(|old| old.id == entity.id)); - let removed = before - .iter() - .filter(|entity| !after.iter().any(|new| new.id == entity.id)); - let modified = after.iter().filter(|entity| { - before - .iter() - .find(|old| old.id == entity.id) - .is_some_and(|old| { - serde_json::to_value(old).ok() != serde_json::to_value(*entity).ok() - }) - }); - let rows: Vec<(&str, &Entity)> = added - .map(|entity| ("+", entity)) - .chain(removed.map(|entity| ("-", entity))) - .chain(modified.map(|entity| ("~", entity))) - .collect(); - if !rows.is_empty() { - println!("\n{label}"); - for (marker, entity) in &rows { - println!(" {marker} {} @{}", entity.name, entity.id); - } - changes += rows.len(); - } - } - if start.summary != end.summary { - changes += 1; - println!("\nsummary\n - {}\n + {}", start.summary, end.summary); - } - if changes == 0 { - println!("No differences."); - } else { - println!("\n{changes} change(s)"); - } - Ok(()) -} diff --git a/bin_efo/src/commands/state.rs b/bin_efo/src/commands/state.rs index 9467fc7..7ffb845 100644 --- a/bin_efo/src/commands/state.rs +++ b/bin_efo/src/commands/state.rs @@ -4,7 +4,11 @@ use std::path::Path; use clap::{Args, ValueEnum}; use lib_efo::{ - entity::EntityIdentifier, epoch::EpochInfo, stats::EntityType, workspace::Workspace, + diff::{ChangeKind, WorldDiff}, + entity::EntityIdentifier, + epoch::EpochInfo, + stats::EntityType, + workspace::Workspace, }; use crate::error::AppError; @@ -108,12 +112,15 @@ pub fn status() -> Result<(), AppError> { println!("└─ Next epoch {}", workspace.manifest.next_epoch_id); if workspace.has_staged_changes() { println!("\nStaged changes"); - print_diff(&workspace.head, &workspace.index.world); + print!("{}", render_diff(&workspace.head, &workspace.index.world)); println!("Use `efo diff --staged` to review the next commit."); } if workspace.has_unstaged_changes() { println!("\nUnstaged changes"); - print_diff(&workspace.index.world, &workspace.worktree.world); + print!( + "{}", + render_diff(&workspace.index.world, &workspace.worktree.world) + ); println!("Use `efo diff` to review edits, then `efo stage ...`."); } Ok(()) @@ -178,97 +185,59 @@ pub fn diff(command: &StateDiffCmd) -> Result<(), AppError> { ) }; println!("{title}"); - print_diff(from, to); + print!("{}", render_diff(from, to)); Ok(()) } /// Render added, removed, and modified entities deterministically. -fn print_diff(from: &EpochInfo, to: &EpochInfo) { - let collections = [ - ("characters", &from.characters, &to.characters), - ("towns", &from.towns, &to.towns), - ("events", &from.events, &to.events), - ("calamities", &from.calamities, &to.calamities), - ("organisations", &from.organizations, &to.organizations), - ("blockers", &from.blockers, &to.blockers), - ]; - let mut count = 0; - for (name, old, new) in collections { - for entity in new - .iter() - .filter(|item| !old.iter().any(|prior| prior.id == item.id)) - { - println!(" + {name}: {} @{}", entity.name, entity.id); - count += 1; - } - for entity in old - .iter() - .filter(|item| !new.iter().any(|next| next.id == item.id)) - { - println!(" - {name}: {} @{}", entity.name, entity.id); - count += 1; - } - for entity in new.iter().filter(|item| { - old.iter() - .find(|prior| prior.id == item.id) - .is_some_and(|prior| { - serde_json::to_value(prior).ok() != serde_json::to_value(*item).ok() - }) - }) { - let prior = old.iter().find(|prior| prior.id == entity.id); - let fields = prior.map_or_else(Vec::new, |value| changed_fields(value, entity)); - println!( - " ~ {name}: {} @{}{}", - entity.name, - entity.id, - if fields.is_empty() { - String::new() - } else { - format!(" [{}]", fields.join(", ")) - } - ); - count += 1; - } +pub(crate) fn render_diff(from: &EpochInfo, to: &EpochInfo) -> String { + let diff = WorldDiff::between(from, to); + let mut output = String::new(); + for change in &diff.entities { + let marker = match change.change { + ChangeKind::Added => "+", + ChangeKind::Removed => "-", + ChangeKind::Modified => "~", + }; + let importance = if change.important { " !" } else { "" }; + let fields = if change.fields.is_empty() { + String::new() + } else { + format!(" [{}]", change.fields.join(", ")) + }; + output.push_str(&format!( + " {marker} {}: {} @{}{}{importance}\n", + collection_name(change.entity_type), + change.name, + change.id, + fields + )); } - if from.summary != to.summary { - println!(" ~ world summary: {:?} → {:?}", from.summary, to.summary); - count += 1; + if let Some((before, after)) = &diff.summary { + output.push_str(&format!(" ~ world summary: {before:?} → {after:?}\n")); } - if from.tags.as_slice() != to.tags.as_slice() { - println!( - " ~ world tags: {:?} → {:?}", - from.tags.as_slice(), - to.tags.as_slice() - ); - count += 1; + if let Some((before, after)) = &diff.tags { + output.push_str(&format!(" ~ world tags: {before:?} → {after:?}\n")); } - if count == 0 { - println!(" No changes."); + if diff.is_empty() { + output.push_str(" No changes.\n"); } else { - println!("{count} change(s)"); + output.push_str(&format!("{} change(s)\n", diff.len())); } + output } -/// List top-level persisted fields that changed on one entity. -fn changed_fields( - before: &lib_efo::entity::Entity, - after: &lib_efo::entity::Entity, -) -> Vec { - let (Ok(serde_json::Value::Object(before)), Ok(serde_json::Value::Object(after))) = - (serde_json::to_value(before), serde_json::to_value(after)) - else { - return Vec::new(); - }; - let mut keys = before - .keys() - .chain(after.keys()) - .cloned() - .collect::>(); - keys.sort(); - keys.dedup(); - keys.into_iter() - .filter(|key| before.get(key) != after.get(key)) - .collect() +/// Stable human collection label. +fn collection_name(kind: EntityType) -> &'static str { + match kind { + EntityType::Character => "characters", + EntityType::Player => "players", + EntityType::Town => "towns", + EntityType::Event => "events", + EntityType::Calamity => "calamities", + EntityType::Organization => "organisations", + EntityType::Blocker => "blockers", + } } /// Human-readable boolean state without relying on colour or icons. diff --git a/bin_efo/tests/cli_workflows.rs b/bin_efo/tests/cli_workflows.rs index 8da019a..1164be9 100644 --- a/bin_efo/tests/cli_workflows.rs +++ b/bin_efo/tests/cli_workflows.rs @@ -146,7 +146,7 @@ fn init_status_diff_and_fsck_workflow() { assert_success(&diff); let diff_text = stdout(&diff); assert!(diff_text.contains("Epoch 0 → 1")); - assert!(diff_text.contains("+ Aria")); + assert!(diff_text.contains("+ characters: Aria")); let fsck = efo(&repo, &["epoch", "fsck"]); assert_success(&fsck); diff --git a/docs/commands.md b/docs/commands.md index 9e94d00..7bec3b3 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -21,6 +21,8 @@ parent directories. `efo --help` is the authoritative syntax. later ones. - `efo epoch summary TEXT` and `efo epoch tag TAG` annotate the current epoch. - `efo epoch diff START [END]` reports added, removed, and modified entities. + A trailing `!` marks changes considered especially consequential (towns, + events, calamities, or statistic/duration changes). `END` defaults to the current epoch. - `efo epoch fsck` performs a read-only consistency check of epoch IDs, tags, and entity UUIDs. It does not repair damage. diff --git a/docs/issue-audit.md b/docs/issue-audit.md index 83a74c6..b9b7490 100644 --- a/docs/issue-audit.md +++ b/docs/issue-audit.md @@ -14,10 +14,10 @@ absent. | [#16 Rewrite backend](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/16) | Addressed by `Workspace`, typed snapshots, transactional writes, broad integration coverage, and removal of the remaining unjustified legacy `unsafe fn` declarations. | Avoid rewriting stable code wholesale; continue adding focused tests. | | [#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) | Needs current source data and a definition of “pre-event”; the issue has no acceptance details. | Fold cards into versioned worldgen configuration after clarification. | +| [#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) | Open simulation feature. | Model it as configured events/relationships after custom fields and influx semantics settle. | -| [#11 Epoch Diffing](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/11) | User-visible epoch and layer diffs are implemented and tested. A reusable typed diff model and importance ranking remain open. | Extract comparison logic when structured output or importance rules need it. | -| [#10 Display functions](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/10) | Partially addressed: unified show routing and three detail levels are coherent, but older renderers still print directly. | Introduce a writer/buffer boundary alongside structured output. | +| [#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 routing and three detail levels are coherent, and every diff is rendered into a buffer before one output write. Older entity renderers still print directly. | Finish the writer/buffer boundary for `show`. | | [#9 Adding influx](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9) | Open and underspecified. | Define versioned deterministic severity and avoidance rules before commands. | | [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Planned in the simulation roadmap; blocked on roads, residency, and deterministic routing. | Complete simulation checkpoints 2–3 in order. | | [#6 HashMap/HashSet](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/6) | Vectors remain the stable serialized representation; replacing them would churn the format. | Add ephemeral UUID/name indexes only if profiling justifies them. | diff --git a/lib_efo/src/diff.rs b/lib_efo/src/diff.rs new file mode 100644 index 0000000..3aac59c --- /dev/null +++ b/lib_efo/src/diff.rs @@ -0,0 +1,163 @@ +//! Typed, deterministic differences between complete world snapshots. + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::{entity::Entity, epoch::EpochInfo, stats::EntityType}; + +/// Nature of an entity-level change. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ChangeKind { + /// Entity exists only in the later snapshot. + Added, + /// Entity exists only in the earlier snapshot. + Removed, + /// Entity exists in both snapshots with changed persisted fields. + Modified, +} + +/// One stable entity change. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EntityChange { + /// Added, removed, or modified. + pub change: ChangeKind, + /// Persisted entity category. + pub entity_type: EntityType, + /// Stable identity. + pub id: Uuid, + /// Human name from the relevant snapshot. + pub name: String, + /// Changed top-level JSON fields for modifications. + pub fields: Vec, + /// Whether this change merits prominence in concise summaries. + pub important: bool, +} + +/// Complete semantic difference between two worlds. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorldDiff { + /// Deterministically ordered entity changes. + pub entities: Vec, + /// Summary before/after when changed. + pub summary: Option<(String, String)>, + /// Tags before/after when changed. + pub tags: Option<(Vec, Vec)>, +} + +impl WorldDiff { + /// Compute a deterministic diff suitable for CLI and structured output. + pub fn between(before: &EpochInfo, after: &EpochInfo) -> Self { + let mut diff = Self::default(); + for (kind, old, new) in [ + (EntityType::Character, &before.characters, &after.characters), + (EntityType::Town, &before.towns, &after.towns), + (EntityType::Event, &before.events, &after.events), + (EntityType::Calamity, &before.calamities, &after.calamities), + ( + EntityType::Organization, + &before.organizations, + &after.organizations, + ), + (EntityType::Blocker, &before.blockers, &after.blockers), + ] { + collect(kind, old, new, &mut diff.entities); + } + diff.entities + .sort_by_key(|change| (kind_order(change.entity_type), change.id)); + if before.summary != after.summary { + diff.summary = Some((before.summary.clone(), after.summary.clone())); + } + if before.tags.as_slice() != after.tags.as_slice() { + diff.tags = Some(( + before.tags.as_slice().to_vec(), + after.tags.as_slice().to_vec(), + )); + } + diff + } + + /// Total semantic changes including world metadata. + pub fn len(&self) -> usize { + self.entities.len() + usize::from(self.summary.is_some()) + usize::from(self.tags.is_some()) + } + + /// Whether nothing changed. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// Append the additions, removals, and modifications for one entity collection. +fn collect(kind: EntityType, before: &[Entity], after: &[Entity], output: &mut Vec) { + for entity in after { + match before.iter().find(|prior| prior.id == entity.id) { + None => output.push(change(ChangeKind::Added, kind, entity, Vec::new())), + Some(prior) => { + let fields = changed_fields(prior, entity); + if !fields.is_empty() { + output.push(change(ChangeKind::Modified, kind, entity, fields)); + } + } + } + } + for entity in before + .iter() + .filter(|entity| !after.iter().any(|later| later.id == entity.id)) + { + output.push(change(ChangeKind::Removed, kind, entity, Vec::new())); + } +} + +/// Construct one change while applying the shared importance policy. +fn change( + change: ChangeKind, + entity_type: EntityType, + entity: &Entity, + fields: Vec, +) -> EntityChange { + let important = matches!( + entity_type, + EntityType::Town | EntityType::Event | EntityType::Calamity + ) || fields + .iter() + .any(|field| field == "stats" || field == "duration"); + EntityChange { + change, + entity_type, + id: entity.id, + name: entity.name.clone(), + fields, + important, + } +} + +/// Return the sorted top-level persisted fields whose values differ. +fn changed_fields(before: &Entity, after: &Entity) -> Vec { + let (Ok(serde_json::Value::Object(before)), Ok(serde_json::Value::Object(after))) = + (serde_json::to_value(before), serde_json::to_value(after)) + else { + return Vec::new(); + }; + let mut fields = before + .keys() + .chain(after.keys()) + .filter(|key| before.get(*key) != after.get(*key)) + .cloned() + .collect::>(); + fields.sort(); + fields.dedup(); + fields +} + +/// Give entity kinds a stable order independent of enum implementation details. +fn kind_order(kind: EntityType) -> u8 { + match kind { + EntityType::Character => 0, + EntityType::Player => 1, + EntityType::Town => 2, + EntityType::Event => 3, + EntityType::Calamity => 4, + EntityType::Organization => 5, + EntityType::Blocker => 6, + } +} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index c474c30..865d31c 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -14,6 +14,7 @@ use crate::epoch::EpochInfo; #[macro_use] #[allow(unused_assignments)] pub mod error; +pub mod diff; pub mod entity; pub mod epoch; pub mod naming; diff --git a/lib_efo/tests/diff.rs b/lib_efo/tests/diff.rs new file mode 100644 index 0000000..0375144 --- /dev/null +++ b/lib_efo/tests/diff.rs @@ -0,0 +1,47 @@ +use lib_efo::{ + diff::{ChangeKind, WorldDiff}, + entity::Entity, + epoch::EpochInfo, + stats::EntityType, +}; + +fn entity(id: u128, name: &str, kind: EntityType) -> Entity { + let mut entity = Entity::default(); + entity.id = uuid::Uuid::from_u128(id); + entity.name = name.into(); + entity.entity_type = kind; + entity +} + +#[test] +fn typed_diff_is_deterministic_and_marks_important_world_changes() { + let mut before = EpochInfo::default(); + before + .characters + .push(entity(2, "Aria", EntityType::Character)); + before.towns.push(entity(1, "Durn", EntityType::Town)); + let mut after = before.clone(); + after.characters[0].description = "Changed".into(); + after.towns.clear(); + after.events.push(entity(3, "Storm", EntityType::Event)); + after.summary = "After storm".into(); + + let diff = WorldDiff::between(&before, &after); + + assert_eq!(diff.len(), 4); + assert_eq!(diff.entities[0].change, ChangeKind::Modified); + assert_eq!(diff.entities[0].fields, vec!["description"]); + assert!(!diff.entities[0].important); + assert_eq!(diff.entities[1].change, ChangeKind::Removed); + assert!(diff.entities[1].important); + assert_eq!(diff.entities[2].change, ChangeKind::Added); + assert!(diff.entities[2].important); + assert_eq!(diff.summary, Some((String::new(), "After storm".into()))); +} + +#[test] +fn typed_diff_serializes_for_future_machine_output() { + let diff = WorldDiff::between(&EpochInfo::default(), &EpochInfo::default()); + let value = serde_json::to_value(diff).expect("serialize diff"); + assert_eq!(value["entities"], serde_json::json!([])); +}