feat: add safe epoch diff and consistency checks

This commit is contained in:
Dandaedre 2026-09-20 20:53:27 +02:00
parent 94b3d75b2b
commit 59a533e2f3
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
13 changed files with 268 additions and 48 deletions

View File

@ -11,7 +11,7 @@ work belongs here before implementation.
- [x] Record product and engineering conventions in `AGENTS.md`.
- [x] Capture baseline `--help` output and exercise a complete temporary-repo
workflow; record every command that panics, lies, or mutates unexpectedly.
- [ ] Run formatting and strict Clippy; classify all warnings.
- [x] Run formatting and strict Clippy; remove all baseline warnings.
- [x] Map the current `.epochconfig` / epoch-directory format and its recovery
properties before changing persistence.
@ -31,13 +31,14 @@ work belongs here before implementation.
## Phase 2 — test and harden the existing product
- [ ] Add CLI integration-test infrastructure using the built `efo` binary and
- [x] Add CLI integration-test infrastructure using the built `efo` binary and
isolated temporary directories.
- [ ] Test root and nested help, version output, invalid commands, and exit
status/stderr conventions.
- [ ] Test `init`, including non-empty directories, already initialised repos,
and the promised `--force` semantics.
- [ ] Test `status` and repository discovery/error reporting.
- [ ] Test `status` and repository discovery/error reporting. (Happy-path
status is covered; repository discovery and error cases remain.)
- [ ] Test the full entity lifecycle for each exposed type: add, show, edit,
diff, and delete by name and stable identifier.
- [ ] Test epoch workflows: next, log, switch, diff, tag, summary, and reset.
@ -53,8 +54,8 @@ work belongs here before implementation.
command surface; remove its current generated demonstration output.
- [ ] Make `efo status` clearly show current epoch, timeline divergence/future
snapshots, entity totals, and a clean/modified indicator if detectable.
- [ ] Implement and test truthful `epoch diff` output.
- [ ] Implement `epoch fsck` with read-only checks for config, directories,
- [x] Implement and test truthful `epoch diff` output.
- [x] Implement `epoch fsck` with read-only checks for config, directories,
parent links, tags, IDs, entity references, and parseability.
- [ ] Make `init --force` safe and explicit; it must not silently destroy an
existing Epoch Forge repository or unrelated files.

2
Cargo.lock generated
View File

@ -269,7 +269,6 @@ dependencies = [
"colored",
"derive_more",
"env_logger",
"insta",
"lib_efo",
"log",
"miette",
@ -419,7 +418,6 @@ dependencies = [
"cli-table",
"colored",
"derive_more",
"env_logger",
"insta",
"log",
"miette",

View File

@ -61,14 +61,13 @@ Run `efo --help`, `efo <command> --help`, or see the
| Area | Available now | Not available yet |
|---|---|---|
| Repository | Initialise in the current directory; inspect status | Discovery from child directories; locking; migrations |
| Timeline | Advance, switch, log, tag, summarise, delete future epochs | World diff; integrity repair; branching; atomic restore/revert |
| Timeline | Advance, switch, log, tag, summarise, diff, check integrity, delete future epochs | Integrity repair; branching; atomic restore/revert |
| Entities | Add, edit, list, inspect, diff, and delete five built-in types | Organisations; custom types and custom fields; bulk operations |
| Generation | Generate character, town, event, calamity, blocker, and exotic names | Deterministic seed controls and template packs |
| Interfaces | CLI | TUI (possible stretch goal); GUI/web (out of scope) |
Some commands in the 0.1.0 parser are known incomplete. `epoch diff`,
`epoch fsck`, and the top-level `show` command are being repaired and should not
be relied upon until their roadmap items are checked. The per-type commands,
The top-level `show` command is known incomplete and should not be relied upon
until its roadmap item is checked. The per-type commands,
such as `efo chr show`, are the supported way to inspect entities.
## Documentation

View File

@ -20,6 +20,3 @@ log = {workspace = true}
derive_more = {workspace = true}
colored = {workspace = true}
uuid = {workspace = true}
[dev-dependencies]
insta = {workspace = true}

View File

@ -163,6 +163,7 @@ pub struct AddArgs {
}
#[derive(Args, Debug)]
/// Arguments for modifying an existing entity.
pub struct EditArgs {
/// Identifier (name or `@tag`) of the entity to edit
pub identifier: EntityIdentifier,
@ -182,6 +183,7 @@ pub struct EditArgs {
}
#[derive(Args, Debug)]
/// Fields shared by entity creation and editing commands.
pub struct CommonArgs {
/// A position Identifier, either a grid position (~x,y), exact position (x,y) or a tag (@uuid)
#[arg(short = 'p', long)]
@ -426,8 +428,8 @@ fn handle_diff_entity(
main_epoch.try_load(&id)?;
main_epoch.try_load(&id2)?;
let epoch_current = unsafe { main_epoch.try_load_id(id) }?;
let epoch_past = unsafe { main_epoch.try_load_id(id2) }?;
let epoch_current = main_epoch.loaded_epoch(id)?;
let epoch_past = main_epoch.loaded_epoch(id2)?;
let current_entity =
epoch_current.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?;
let past_entity =

View File

@ -52,7 +52,8 @@ use crate::{
success::{SuccessMessages, display_success},
};
use lib_efo::{
epoch::{EpochConfig, EpochId, epoch_traits::ConfigWritable},
entity::Entity,
epoch::{EpochConfig, EpochId, EpochInfo, epoch_traits::ConfigWritable},
error::EpochError,
};
use log::{debug, info};
@ -90,7 +91,7 @@ pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> {
cli_epoch::EpochCmd::Switch(args) => handle_switch(args, &mut main_epoch),
cli_epoch::EpochCmd::Next(args) => handle_next(args, &mut main_epoch),
cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch),
cli_epoch::EpochCmd::Diff(args) => handle_diff(args),
cli_epoch::EpochCmd::Diff(args) => handle_diff(args, &mut main_epoch),
cli_epoch::EpochCmd::Tag(args) => handle_taging(args, &mut main_epoch),
cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch),
cli_epoch::EpochCmd::Summary(args) => handle_summary(args, &mut main_epoch),
@ -131,14 +132,79 @@ fn handle_summary(args: &cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Re
/// Show a diff between two epochs.
///
/// Currently unimplemented. The function is a placeholder until a
/// world-level diff algorithm is available.
///
/// 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;
unimplemented!("Blocker: There is actually no way to diff the world yet")
fn handle_diff(args: &cli_epoch::Diff, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let start_id = main_epoch.get_epoch_id(&args.start)?;
let end_id = args
.end
.as_ref()
.map(|id| main_epoch.get_epoch_id(id))
.transpose()?
.unwrap_or(main_epoch.epoch_id);
let start = main_epoch.load_epoch(start_id)?.clone();
let end = main_epoch.load_epoch(end_id)?.clone();
println!("Epoch {start_id} → {end_id}");
print_world_diff(&start, &end)?;
Ok(())
}
/// Print additions, removals, and modifications between two world snapshots.
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),
("blockers", &start.blockers, &end.blockers),
];
let mut changes = 0;
for (label, before, after) in collections {
let added: Vec<&Entity> = after
.iter()
.filter(|entity| !before.iter().any(|old| old.id == entity.id))
.collect();
let removed: Vec<&Entity> = before
.iter()
.filter(|entity| !after.iter().any(|new| new.id == entity.id))
.collect();
let modified: Vec<&Entity> = 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()
})
})
.collect();
if added.is_empty() && removed.is_empty() && modified.is_empty() {
continue;
}
changes += added.len() + removed.len() + modified.len();
println!("\n{label}");
for entity in added {
println!(" + {} @{}", entity.name, entity.id);
}
for entity in removed {
println!(" - {} @{}", entity.name, entity.id);
}
for entity in modified {
println!(" ~ {} @{}", entity.name, entity.id);
}
}
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(())
}
/// Show a log of all epochs up to the current one.
@ -320,7 +386,62 @@ fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<
///
/// 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;
unimplemented!()
let ids: Vec<EpochId> = main_epoch.list_existing_epochs.keys().copied().collect();
if !main_epoch
.list_existing_epochs
.contains_key(&main_epoch.epoch_id)
{
Err(EpochError::TreeInvalid(
main_epoch.epoch_id,
"the current epoch is missing".to_string(),
))?;
}
for id in &ids {
let epoch = main_epoch.load_epoch(*id)?.clone();
if epoch.epoch_id != *id {
Err(EpochError::TreeInvalid(
*id,
format!("snapshot declares epoch {}", epoch.epoch_id),
))?;
}
let mut entity_ids = std::collections::HashSet::new();
for entity in epoch
.characters
.iter()
.chain(&epoch.towns)
.chain(&epoch.events)
.chain(&epoch.calamities)
.chain(&epoch.blockers)
{
if entity.id.is_nil() || !entity_ids.insert(entity.id) {
Err(EpochError::TreeInvalid(
*id,
format!("entity `{}` has a missing or duplicate UUID", entity.name),
))?;
}
}
for tag in epoch.tags.iter() {
if main_epoch.tags.get(tag) != Some(id) {
Err(EpochError::TreeInvalid(
*id,
format!("tag `{tag}` is inconsistent with .epoch"),
))?;
}
}
}
for (tag, id) in &main_epoch.tags {
if !ids.contains(id) {
Err(EpochError::TreeInvalid(
*id,
format!("tag `{tag}` points to a missing epoch"),
))?;
}
}
println!(
"✓ Repository is consistent ({} epoch(s) checked).",
ids.len()
);
Ok(())
}

View File

@ -16,8 +16,7 @@ pub(crate) fn status(cmd: &StatusCmd) -> Result<(), crate::error::AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
let current_epoch = if let Some(epoch_id) = cmd.custom_id {
main_epoch.try_load(&epoch_id)?;
unsafe { main_epoch.try_load_id(epoch_id)? }
main_epoch.load_epoch(epoch_id)?
} else {
main_epoch.try_load_current()?
};

View File

@ -0,0 +1,105 @@
//! End-to-end tests for user-visible CLI workflows.
use std::{
fs,
path::{Path, PathBuf},
process::{Command, Output},
};
use uuid::Uuid;
struct TestRepo(PathBuf);
impl TestRepo {
fn new() -> Self {
let path = std::env::temp_dir().join(format!("efo-cli-test-{}", Uuid::new_v4()));
fs::create_dir(&path).expect("create temporary repository directory");
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TestRepo {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn efo(repo: &TestRepo, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_efo"))
.args(args)
.current_dir(repo.path())
.env("NO_COLOR", "1")
.output()
.expect("run efo")
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).into_owned()
}
fn assert_success(output: &Output) {
assert!(
output.status.success(),
"command failed\nstdout:\n{}\nstderr:\n{}",
stdout(output),
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn help_is_available_without_a_repository() {
let repo = TestRepo::new();
let output = efo(&repo, &["--help"]);
assert_success(&output);
let text = stdout(&output);
assert!(text.contains("Usage: efo <COMMAND>"));
assert!(text.contains("epoch"));
assert!(text.contains("status"));
}
#[test]
fn init_status_diff_and_fsck_workflow() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
assert!(repo.path().join(".epoch").is_file());
assert!(repo.path().join("epoch/0/epochinfo.json").is_file());
let status = efo(&repo, &["status"]);
assert_success(&status);
assert!(stdout(&status).contains("Epoch 0"));
assert_success(&efo(&repo, &["chr", "add", "Aria"]));
assert_success(&efo(&repo, &["epoch", "next"]));
assert_success(&efo(&repo, &["chr", "edit", "Aria", "--prestige-add", "2"]));
let diff = efo(&repo, &["epoch", "diff", "0", "1"]);
assert_success(&diff);
let diff_text = stdout(&diff);
assert!(diff_text.contains("Epoch 0 → 1"));
assert!(diff_text.contains("~ Aria"));
let fsck = efo(&repo, &["epoch", "fsck"]);
assert_success(&fsck);
assert!(stdout(&fsck).contains("Repository is consistent (2 epoch(s) checked)"));
}
#[test]
fn fsck_reports_a_snapshot_with_the_wrong_id_without_panicking() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
let snapshot_path = repo.path().join("epoch/0/epochinfo.json");
let text = fs::read_to_string(&snapshot_path).expect("read snapshot");
let changed = text.replacen("\"id\": 0", "\"id\": 9", 1);
fs::write(snapshot_path, changed).expect("corrupt snapshot for test");
let output = efo(&repo, &["epoch", "fsck"]);
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("Invalid epoch tree"), "{stderr}");
assert!(!stderr.contains("panicked"), "{stderr}");
}

View File

@ -15,11 +15,12 @@ parent directories. `efo <command> --help` is the authoritative syntax.
- `efo epoch switch ID_OR_TAG` checks out an existing snapshot without deleting
later ones. Its currently accepted `--force` flag has no effect.
- `efo epoch summary TEXT` and `efo epoch tag TAG` annotate the current epoch.
- `efo epoch diff START [END]` reports added, removed, and modified entities.
`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.
- `efo epoch reset` permanently deletes every epoch after the current one.
`epoch diff` and `epoch fsck` are exposed in 0.1.0 but incomplete and currently
panic. They are current-release defects, not usable capabilities.
## Entities
The built-in nouns are `chr`, `town`, `event`, `calamity`, and `blocker`:

View File

@ -40,8 +40,9 @@ efo status
```
Back up before `epoch reset`; Epoch Forge cannot recover its deleted folders.
For corruption, stop mutating, copy the complete directory, and restore from a
known-good backup. `epoch fsck` is not usable in 0.1.0.
For corruption, stop mutating, copy the complete directory, and run the
read-only `efo epoch fsck`. Restore from a known-good backup; `fsck` deliberately
does not repair or discard data.
The config records a writer version, but automatic migrations and unknown-field
retention are not implemented. The intended compatibility policy is that newer

View File

@ -9,7 +9,6 @@ serde = {workspace = true}
thiserror = {workspace = true}
clap = {workspace = true}
miette = {workspace = true}
env_logger = {workspace = true}
log = {workspace = true}
derive_more = {workspace = true}
cli-table = "0.5.0"

View File

@ -174,19 +174,10 @@ impl EpochConfig {
/// * Propagates any error from `try_load`.
pub fn try_load_current(&mut self) -> Result<&EpochInfo, EpochError> {
self.try_load(&self.epoch_id.clone())?;
unsafe { self.try_load_id(self.epoch_id) }
self.loaded_epoch(self.epoch_id)
}
/// Load an epoch by its identifier.
///
/// The caller must guarantee that the epoch has already been loaded into
/// the cache (e.g. by calling `try_load`). This function is marked `unsafe`
/// because it performs a raw reference conversion without performing that
/// check.
///
/// # Safety
/// Calling this function when the requested epoch has not yet been
/// loaded results in undefined behaviour.
/// Return an epoch that has already been loaded into the cache.
///
/// # Arguments
/// * `epoch_id` - Identifier of the epoch to load.
@ -197,16 +188,22 @@ impl EpochConfig {
/// unknown.
/// * `Err(EpochError::LoadingEpochId(..))` - The epoch data is not yet
/// present in the cache.
pub unsafe fn try_load_id(&self, epoch_id: EpochId) -> Result<&EpochInfo, EpochError> {
pub fn loaded_epoch(&self, epoch_id: EpochId) -> Result<&EpochInfo, EpochError> {
let current = self
.list_existing_epochs
.get(&epoch_id)
.ok_or(EpochError::EpochHashingImpossible(file!(), line!()))?
.as_ref()
.ok_or(EpochError::LoadingEpochId(self.epoch_id))?;
.ok_or(EpochError::LoadingEpochId(epoch_id))?;
Ok(current)
}
/// Load an epoch from disk and return its cached value.
pub fn load_epoch(&mut self, epoch_id: EpochId) -> Result<&EpochInfo, EpochError> {
self.try_load(&epoch_id)?;
self.loaded_epoch(epoch_id)
}
/// Load the currently active epoch mutably.
///
/// This is a convenience wrapper that forwards to `try_load_id_as_mut`

View File

@ -288,7 +288,7 @@ impl NamingData {
.collect();
// Combine with a space - you could also use a hyphen or nothing
format!("{pref}{} {pref2}{}", &first, &last)
format!("{pref}{first} {pref2}{last}")
}
}