epoch_forge/lib_efo/src/workspace.rs

981 lines
36 KiB
Rust

//! Format-2 HEAD, index, and worktree access.
use std::{
collections::BTreeMap,
fs,
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
entity::EntityIdentifier,
epoch::EpochInfo,
repository_format::{FormatError, RepositoryManifest, RepositorySnapshot, decode_manifest},
stats::EntityType,
transaction::{
RepositoryLock, TransactionError, replace_file, replace_files, replace_files_locked,
},
};
/// Manifest state removed alongside a recoverable future-history prune.
#[derive(Debug, Serialize, Deserialize)]
struct PruneMetadata {
/// Allocator value to restore when no replacement history was created.
next_epoch_id: crate::epoch::EpochId,
/// Tags whose targets were moved into the prune backup.
removed_tags: BTreeMap<String, crate::epoch::EpochId>,
}
/// A validated repository and its three state layers.
#[derive(Debug, Clone)]
pub struct Workspace {
/// Canonical repository root.
root: PathBuf,
/// Current repository manifest.
pub manifest: RepositoryManifest,
/// Immutable HEAD world.
pub head: EpochInfo,
/// Staged complete snapshot.
pub index: RepositorySnapshot,
/// Editable complete snapshot.
pub worktree: RepositorySnapshot,
}
/// Failures while accessing repository state.
#[derive(Debug, thiserror::Error)]
pub enum WorkspaceError {
/// The target already contains repository metadata.
#[error("repository already exists at `{0}`")]
AlreadyExists(PathBuf),
/// Filesystem access failed.
#[error("cannot access repository state `{path}`: {source}")]
Io {
/// Affected path.
path: PathBuf,
/// Underlying error.
#[source]
source: std::io::Error,
},
/// Stored JSON is malformed.
#[error("invalid repository state `{path}`: {source}")]
Json {
/// Affected path.
path: PathBuf,
/// Decode error.
#[source]
source: serde_json::Error,
},
/// Manifest detection failed.
#[error(transparent)]
Format(#[from] FormatError),
/// State layers do not belong together.
#[error("repository state is inconsistent: {0}")]
Inconsistent(String),
/// A requested entity selector did not resolve safely.
#[error("entity selector `{0}` did not match exactly one entity")]
Selector(String),
/// A commit would discard unstaged edits.
#[error("worktree has unstaged changes; stage them or restore the worktree before committing")]
Unstaged,
/// The index is identical to HEAD.
#[error("index has no changes to commit")]
EmptyCommit,
/// Later snapshots must be pruned before creating a new linear commit.
#[error("future epochs exist; run `efo prune-future` before committing")]
FutureExists,
/// An interrupted transaction must be recovered before reading layers.
#[error("an unfinished transaction exists; run `efo recover` before continuing")]
RecoveryRequired,
/// A history operation requires all three layers to agree.
#[error("repository has staged or unstaged changes; commit or restore them first")]
Dirty,
/// An inverse change overlaps later edits.
#[error("revert conflicts with later changes in {0}; nothing was changed")]
Conflict(String),
/// The requested committed epoch does not exist.
#[error("committed epoch {0} does not exist")]
EpochMissing(crate::epoch::EpochId),
/// Transaction safety rejected the write.
#[error(transparent)]
Transaction(#[from] TransactionError),
}
impl Workspace {
/// Create a new repository directly in the current format.
pub fn initialize(root: &Path, application_version: &str) -> Result<Self, WorkspaceError> {
let root = root.canonicalize().map_err(|source| io(root, source))?;
let manifest_path = root.join(".epoch");
if manifest_path.exists() || root.join(".efo").exists() || root.join("epoch/0").exists() {
return Err(WorkspaceError::AlreadyExists(root));
}
fs::create_dir_all(root.join(".efo")).map_err(|source| io(&root, source))?;
fs::create_dir_all(root.join("epoch/0")).map_err(|source| io(&root, source))?;
let repository_id = Uuid::new_v4();
let world = EpochInfo::default();
let manifest = RepositoryManifest::new(
repository_id,
crate::epoch::EpochId::new(0),
crate::epoch::EpochId::new(1),
application_version.to_owned(),
BTreeMap::new(),
);
let transient = RepositorySnapshot::new(repository_id, manifest.epoch_id, world.clone());
replace_files(
&root,
&[
(
root.join("epoch/0/epochinfo.json"),
encode(&world, "initial epoch")?,
),
(
root.join(".efo/index.json"),
encode(&transient, "initial index")?,
),
(
root.join(".efo/worktree.json"),
encode(&transient, "initial worktree")?,
),
(
root.join(".epoch"),
encode(&manifest, "repository manifest")?,
),
],
"init",
)?;
Self::open(&root)
}
/// Canonical repository root.
pub fn root(&self) -> &Path {
&self.root
}
/// Open and cross-check a repository.
pub fn open(root: &Path) -> Result<Self, WorkspaceError> {
let root = root.canonicalize().map_err(|source| io(root, source))?;
if root.join(".efo/transaction.json").exists() {
return Err(WorkspaceError::RecoveryRequired);
}
let manifest_path = root.join(".epoch");
let manifest = decode_manifest(&read(&manifest_path)?)?;
let head_path = root.join(format!("epoch/{}/epochinfo.json", manifest.epoch_id));
let head: EpochInfo = decode(&head_path)?;
let index_path = root.join(".efo/index.json");
let worktree_path = root.join(".efo/worktree.json");
let index: RepositorySnapshot = decode(&index_path)?;
let worktree: RepositorySnapshot = decode(&worktree_path)?;
for (name, snapshot) in [("index", &index), ("worktree", &worktree)] {
if snapshot.format_version != crate::repository_format::CURRENT_FORMAT_VERSION {
return Err(WorkspaceError::Inconsistent(format!(
"{name} has unsupported format {}",
snapshot.format_version
)));
}
if snapshot.repository_id != manifest.repository_id {
return Err(WorkspaceError::Inconsistent(format!(
"{name} belongs to another repository"
)));
}
if snapshot.base_epoch_id != manifest.epoch_id {
return Err(WorkspaceError::Inconsistent(format!(
"{name} is based on epoch {}, but HEAD is {}",
snapshot.base_epoch_id, manifest.epoch_id
)));
}
}
if head.epoch_id != manifest.epoch_id {
return Err(WorkspaceError::Inconsistent(
"HEAD snapshot ID does not match manifest".into(),
));
}
validate_world("HEAD", &head)?;
validate_world("index", &index.world)?;
validate_world("worktree", &worktree.world)?;
Ok(Self {
root,
manifest,
head,
index,
worktree,
})
}
/// Whether index differs from immutable HEAD.
pub fn has_staged_changes(&self) -> bool {
!same(&self.head, &self.index.world)
}
/// Whether worktree differs from index.
pub fn has_unstaged_changes(&self) -> bool {
!same(&self.index.world, &self.worktree.world)
}
/// Copy the complete worktree into the index.
pub fn stage_all(&mut self) -> Result<(), WorkspaceError> {
self.index.world = self.worktree.world.clone();
self.save_index("stage --all")
}
/// Copy world-level metadata from worktree into index.
pub fn stage_world(&mut self) -> Result<(), WorkspaceError> {
copy_world_metadata(&self.worktree.world, &mut self.index.world);
self.save_index("stage --world")
}
/// Copy selected entities from worktree into index, including deletions.
pub fn stage_entities(
&mut self,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
copy_entities(&self.worktree.world, &mut self.index.world, kind, selectors)?;
self.save_index("stage entities")
}
/// Restore the complete index from HEAD.
pub fn restore_index(&mut self) -> Result<(), WorkspaceError> {
self.index.world = self.head.clone();
self.save_index("restore --staged --all")
}
/// Restore the complete worktree from the index.
pub fn restore_worktree(&mut self) -> Result<(), WorkspaceError> {
self.worktree.world = self.index.world.clone();
self.save_worktree("restore --worktree --all")
}
/// Restore staged world metadata from HEAD.
pub fn restore_index_world(&mut self) -> Result<(), WorkspaceError> {
copy_world_metadata(&self.head, &mut self.index.world);
self.save_index("restore --staged --world")
}
/// Restore worktree world metadata from index.
pub fn restore_worktree_world(&mut self) -> Result<(), WorkspaceError> {
copy_world_metadata(&self.index.world, &mut self.worktree.world);
self.save_worktree("restore --worktree --world")
}
/// Restore selected index entities from HEAD.
pub fn restore_index_entities(
&mut self,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
copy_entities(&self.head, &mut self.index.world, kind, selectors)?;
self.save_index("restore --staged")
}
/// Restore selected worktree entities from index.
pub fn restore_worktree_entities(
&mut self,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
copy_entities(&self.index.world, &mut self.worktree.world, kind, selectors)?;
self.save_worktree("restore --worktree")
}
/// Persist a caller-modified worktree through the transaction layer.
pub fn save_worktree(&self, command: &str) -> Result<(), WorkspaceError> {
save(&self.root, ".efo/worktree.json", &self.worktree, command)
}
/// Apply one previewed entity change, rejecting stale editor snapshots under
/// the writer lock. `None` means creation/deletion; swapping arguments undoes
/// a change. HEAD and index are never written. In-memory state changes only
/// after the transaction succeeds.
pub fn apply_entity_change(
&mut self,
before: Option<&crate::entity::Entity>,
after: Option<&crate::entity::Entity>,
) -> Result<(), WorkspaceError> {
let lock = crate::transaction::RepositoryLock::acquire(&self.root, "entity editor")?;
let mut current = Self::open(&self.root)?;
if encode(&self.manifest, "manifest")? != encode(&current.manifest, "manifest")?
|| encode(&self.index, "index")? != encode(&current.index, "index")?
|| encode(&self.worktree, "worktree")? != encode(&current.worktree, "worktree")?
{
return Err(WorkspaceError::Conflict(
"repository changed since this editor snapshot; cancel and reload with r before retrying".into(),
));
}
let identity = before
.or(after)
.ok_or_else(|| WorkspaceError::Inconsistent("empty entity change".into()))?;
if let (Some(before), Some(after)) = (before, after)
&& (before.id != after.id || before.entity_type != after.entity_type)
{
return Err(WorkspaceError::Inconsistent(
"editing cannot change an entity UUID or type".into(),
));
}
let collection = current
.worktree
.world
.vec_entities_mut(&identity.entity_type);
let stored = collection.iter().find(|entity| entity.id == identity.id);
if !same_entity(stored, before) {
return Err(WorkspaceError::Conflict(format!(
"entity @{} differs from the preview",
identity.id
)));
}
if let Some(after) = after {
if after.name.trim().is_empty() || after.name.chars().any(char::is_control) {
return Err(WorkspaceError::Inconsistent(
"entity name must be non-empty and contain no control characters".into(),
));
}
if collection.iter().any(|entity| {
entity.id != after.id && entity.name.to_lowercase() == after.name.to_lowercase()
}) {
return Err(WorkspaceError::Conflict(format!(
"an entity named `{}` already exists in this collection",
after.name
)));
}
}
let position = collection
.iter()
.position(|entity| entity.id == identity.id);
match (position, after) {
(Some(index), Some(after)) => collection[index] = after.clone(),
(Some(index), None) => {
collection.remove(index);
}
(None, Some(after)) => collection.push(after.clone()),
(None, None) => {}
}
validate_world("edited worktree", &current.worktree.world)?;
crate::transaction::replace_files_locked(
&self.root,
&[(
self.root.join(".efo/worktree.json"),
encode(&current.worktree, "worktree")?,
)],
&lock,
)?;
*self = current;
Ok(())
}
/// Persist a caller-modified index through the transaction layer.
pub fn save_index(&self, command: &str) -> Result<(), WorkspaceError> {
save(&self.root, ".efo/index.json", &self.index, command)
}
/// Create an immutable epoch and advance all state layers atomically.
pub fn commit(&mut self, message: String) -> Result<crate::epoch::EpochId, WorkspaceError> {
if self.has_unstaged_changes() {
return Err(WorkspaceError::Unstaged);
}
if !self.future_epochs()?.is_empty() {
return Err(WorkspaceError::FutureExists);
}
validate_world("index", &self.index.world)?;
if !self.has_staged_changes() {
return Err(WorkspaceError::EmptyCommit);
}
let new_id = self.manifest.next_epoch_id;
let mut world = self.index.world.clone();
world.parent_epoch = Some(self.manifest.epoch_id);
world.epoch_id = new_id;
world.commit_message = message;
let mut manifest = self.manifest.clone();
manifest.epoch_id = new_id;
for tag in world
.tags
.iter()
.filter(|tag| !self.head.tags.contains(tag))
{
manifest.tags.insert(tag.clone(), new_id);
}
manifest.next_epoch_id =
crate::epoch::EpochId::new(new_id.id.checked_add(1).ok_or_else(|| {
WorkspaceError::Inconsistent("epoch ID allocator is exhausted".into())
})?);
let snapshot = RepositorySnapshot::new(manifest.repository_id, new_id, world.clone());
let epoch_path = self.root.join(format!("epoch/{new_id}/epochinfo.json"));
fs::create_dir_all(
epoch_path
.parent()
.ok_or_else(|| WorkspaceError::Inconsistent("epoch path has no parent".into()))?,
)
.map_err(|source| io(&epoch_path, source))?;
let replacements = [
(epoch_path, encode(&world, "epoch snapshot")?),
(
self.root.join(".efo/index.json"),
encode(&snapshot, "index")?,
),
(
self.root.join(".efo/worktree.json"),
encode(&snapshot, "worktree")?,
),
(self.root.join(".epoch"), encode(&manifest, "manifest")?),
];
replace_files(&self.root, &replacements, "commit")?;
self.manifest = manifest;
self.head = world;
self.index = snapshot.clone();
self.worktree = snapshot;
Ok(new_id)
}
/// Load one immutable epoch by ID.
pub fn load_epoch(&self, id: crate::epoch::EpochId) -> Result<EpochInfo, WorkspaceError> {
let path = self.root.join(format!("epoch/{id}/epochinfo.json"));
if !path.is_file() {
return Err(WorkspaceError::EpochMissing(id));
}
decode(&path)
}
/// Parse and validate one immutable epoch, including UUID links and types.
pub fn check_epoch(&self, id: crate::epoch::EpochId) -> Result<(), WorkspaceError> {
let epoch = self.load_epoch(id)?;
validate_world(&format!("epoch {id}"), &epoch)
}
/// Switch clean HEAD/index/worktree to an existing immutable epoch.
pub fn switch(&mut self, target: crate::epoch::EpochId) -> Result<(), WorkspaceError> {
if self.has_staged_changes() || self.has_unstaged_changes() {
return Err(WorkspaceError::Dirty);
}
let world = self.load_epoch(target)?;
let mut manifest = self.manifest.clone();
manifest.epoch_id = target;
let snapshot = RepositorySnapshot::new(manifest.repository_id, target, world.clone());
let replacements = [
(
self.root.join(".efo/index.json"),
encode(&snapshot, "index")?,
),
(
self.root.join(".efo/worktree.json"),
encode(&snapshot, "worktree")?,
),
(self.root.join(".epoch"), encode(&manifest, "manifest")?),
];
replace_files(&self.root, &replacements, "switch")?;
self.manifest = manifest;
self.head = world;
self.index = snapshot.clone();
self.worktree = snapshot;
Ok(())
}
/// Invert one historical epoch onto clean HEAD and commit the result.
pub fn revert(
&mut self,
target: crate::epoch::EpochId,
) -> Result<crate::epoch::EpochId, WorkspaceError> {
self.apply_revert(target)?;
self.index.world = self.worktree.world.clone();
self.commit(format!("Revert epoch {target}"))
}
/// Invert one historical epoch into the worktree without staging or committing it.
pub fn revert_to_worktree(
&mut self,
target: crate::epoch::EpochId,
) -> Result<(), WorkspaceError> {
self.apply_revert(target)?;
self.save_worktree("revert historical change")
}
/// Permanently move all state to `target` and delete every newer epoch.
pub fn hard_reset(
&mut self,
target: crate::epoch::EpochId,
) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
let world = self.load_epoch(target)?;
let removed = self
.all_epoch_ids()?
.into_iter()
.filter(|id| *id > target)
.collect::<Vec<_>>();
let mut manifest = self.manifest.clone();
manifest.epoch_id = target;
manifest.next_epoch_id = crate::epoch::EpochId::new(target.id + 1);
manifest.tags.retain(|_, id| *id <= target);
let snapshot = RepositorySnapshot::new(manifest.repository_id, target, world.clone());
let replacements = [
(
self.root.join(".efo/index.json"),
encode(&snapshot, "index")?,
),
(
self.root.join(".efo/worktree.json"),
encode(&snapshot, "worktree")?,
),
(self.root.join(".epoch"), encode(&manifest, "manifest")?),
];
replace_files(&self.root, &replacements, "hard reset")?;
for id in &removed {
let path = self.root.join("epoch").join(id.to_string());
fs::remove_dir_all(&path).map_err(|source| io(&path, source))?;
}
self.manifest = manifest;
self.head = world;
self.index = snapshot.clone();
self.worktree = snapshot;
Ok(removed)
}
/// Calculate an inverse historical change in the worktree.
fn apply_revert(&mut self, target: crate::epoch::EpochId) -> Result<(), WorkspaceError> {
if self.has_staged_changes() || self.has_unstaged_changes() {
return Err(WorkspaceError::Dirty);
}
let changed = self.load_epoch(target)?;
let parent_id = changed
.parent_epoch
.or_else(|| (target.id > 0).then(|| crate::epoch::EpochId::new(target.id - 1)))
.ok_or_else(|| WorkspaceError::Conflict("root epoch has no change to invert".into()))?;
let before = self.load_epoch(parent_id)?;
let mut result = self.head.clone();
invert_world(&before, &changed, &mut result)?;
result.epoch_id = self.manifest.epoch_id;
result.parent_epoch = self.head.parent_epoch;
result.commit_message = self.head.commit_message.clone();
self.worktree.world = result;
Ok(())
}
/// Advance entity time in the index and commit it with any staged changes.
pub fn advance_and_commit(&mut self) -> Result<crate::epoch::EpochId, WorkspaceError> {
if self.has_unstaged_changes() {
return Err(WorkspaceError::Unstaged);
}
self.index
.world
.iter_all_entities_mut()
.for_each(|entity| entity.increment_time());
self.index.world.summary.clear();
self.index.world.tags.clear();
// Time advancement is meaningful even for an empty world; this marker
// makes the new history event non-empty before `commit` assigns its
// final message and epoch identity.
self.index.world.commit_message = "Advance time".into();
self.worktree.world = self.index.world.clone();
self.commit("Advance time".into())
}
/// List snapshots numerically newer than current HEAD.
pub fn future_epochs(&self) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
self.epochs_after(self.manifest.epoch_id)
}
/// List committed epoch directories newer than `target`.
pub fn epochs_after(
&self,
target: crate::epoch::EpochId,
) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
Ok(self
.all_epoch_ids()?
.into_iter()
.filter(|id| *id > target)
.collect())
}
/// List every numeric epoch directory.
fn all_epoch_ids(&self) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
let mut ids = Vec::new();
for entry in fs::read_dir(self.root.join("epoch"))
.map_err(|source| io(&self.root.join("epoch"), source))?
{
let entry = entry.map_err(|source| io(&self.root.join("epoch"), source))?;
if entry
.file_type()
.map_err(|source| io(&entry.path(), source))?
.is_dir()
&& let Ok(id) = entry
.file_name()
.to_string_lossy()
.parse::<crate::epoch::EpochId>()
{
ids.push(id);
}
}
ids.sort_unstable();
Ok(ids)
}
/// Move future snapshots into a recoverable backup directory.
pub fn prune_future(&mut self) -> Result<PathBuf, WorkspaceError> {
if self.has_staged_changes() || self.has_unstaged_changes() {
return Err(WorkspaceError::Dirty);
}
let ids = self.future_epochs()?;
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| WorkspaceError::Inconsistent("system clock is before Unix epoch".into()))?
.as_secs();
let backup_root = self.root.join(format!(".efo/pruned/{stamp}"));
let backup = backup_root.join("epoch");
fs::create_dir_all(&backup).map_err(|source| io(&backup, source))?;
let removed_tags = self
.manifest
.tags
.iter()
.filter(|(_, id)| ids.contains(id))
.map(|(name, id)| (name.clone(), *id))
.collect();
let metadata = PruneMetadata {
next_epoch_id: self.manifest.next_epoch_id,
removed_tags,
};
let metadata_path = backup_root.join("prune.json");
let lock = RepositoryLock::acquire(&self.root, "prune-future")?;
replace_files_locked(
&self.root,
&[(metadata_path, encode(&metadata, "prune metadata")?)],
&lock,
)?;
for id in &ids {
let source = self.root.join(format!("epoch/{id}"));
let destination = backup.join(id.to_string());
fs::rename(&source, &destination).map_err(|source_error| io(&source, source_error))?;
}
let mut manifest = self.manifest.clone();
manifest.next_epoch_id = crate::epoch::EpochId::new(manifest.epoch_id.id + 1);
manifest.tags.retain(|_, id| !ids.contains(id));
replace_files_locked(
&self.root,
&[(self.root.join(".epoch"), encode(&manifest, "manifest")?)],
&lock,
)?;
self.manifest = manifest;
Ok(backup_root)
}
/// Restore all epoch directories from a prune backup.
pub fn restore_pruned(&mut self, backup: &Path) -> Result<usize, WorkspaceError> {
let epoch_backup = backup.join("epoch");
let metadata_path = backup.join("prune.json");
let metadata = if metadata_path.is_file() {
Some(decode::<PruneMetadata>(&metadata_path)?)
} else {
None
};
if let Some(metadata) = &metadata {
for name in metadata.removed_tags.keys() {
if self.manifest.tags.contains_key(name) {
return Err(WorkspaceError::Inconsistent(format!(
"cannot restore tag `{name}` because it already exists"
)));
}
}
}
let entries = fs::read_dir(&epoch_backup)
.map_err(|source| io(&epoch_backup, source))?
.collect::<Result<Vec<_>, _>>()
.map_err(|source| io(&epoch_backup, source))?;
for entry in &entries {
let destination = self.root.join("epoch").join(entry.file_name());
if destination.exists() {
return Err(WorkspaceError::Inconsistent(format!(
"cannot restore `{}` because it already exists",
destination.display()
)));
}
}
let lock = RepositoryLock::acquire(&self.root, "restore pruned history")?;
let mut restored = 0;
for entry in entries {
let destination = self.root.join("epoch").join(entry.file_name());
fs::rename(entry.path(), &destination).map_err(|source| io(&destination, source))?;
restored += 1;
}
let mut manifest = self.manifest.clone();
if let Some(metadata) = metadata {
manifest.next_epoch_id = manifest.next_epoch_id.max(metadata.next_epoch_id);
for (name, id) in metadata.removed_tags {
manifest.tags.insert(name, id);
}
} else if let Some(last) = self.all_epoch_ids()?.last() {
manifest.next_epoch_id = crate::epoch::EpochId::new(last.id + 1);
}
replace_files_locked(
&self.root,
&[(self.root.join(".epoch"), encode(&manifest, "manifest")?)],
&lock,
)?;
self.manifest = manifest;
Ok(restored)
}
}
/// Apply entity and summary inverses, refusing overlapping later edits.
fn invert_world(
before: &EpochInfo,
changed: &EpochInfo,
current: &mut EpochInfo,
) -> Result<(), WorkspaceError> {
macro_rules! invert_collection {
($field:ident) => {
invert_entities(
&before.$field,
&changed.$field,
&mut current.$field,
stringify!($field),
)?;
};
}
invert_collection!(characters);
invert_collection!(towns);
invert_collection!(events);
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()));
}
}
Ok(())
}
/// Invert changed entities by stable UUID with whole-entity conflict checks.
fn invert_entities(
before: &[crate::entity::Entity],
changed: &[crate::entity::Entity],
current: &mut Vec<crate::entity::Entity>,
label: &str,
) -> Result<(), WorkspaceError> {
let mut ids = before
.iter()
.chain(changed)
.map(|entity| entity.id)
.collect::<Vec<_>>();
ids.sort_unstable();
ids.dedup();
for id in ids {
let old = before.iter().find(|entity| entity.id == id);
let new = changed.iter().find(|entity| entity.id == id);
if same_entity(old, new) {
continue;
}
let now = current.iter().find(|entity| entity.id == id);
if same_entity(now, old) {
continue;
}
if !same_entity(now, new) {
return Err(WorkspaceError::Conflict(format!("{label} entity @{id}")));
}
current.retain(|entity| entity.id != id);
if let Some(entity) = old {
current.push(entity.clone());
}
}
Ok(())
}
/// Compare optional entities through their persisted representation.
fn same_entity(
left: Option<&crate::entity::Entity>,
right: Option<&crate::entity::Entity>,
) -> bool {
left.and_then(|value| serde_json::to_value(value).ok())
== right.and_then(|value| serde_json::to_value(value).ok())
}
/// Copy selected collection entries with delete semantics.
fn copy_entities(
source: &EpochInfo,
destination: &mut EpochInfo,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
for selector in selectors {
let source_matches = matches(source.vec_entities(&kind), selector);
let destination_matches = matches(destination.vec_entities(&kind), selector);
let identity = match (source_matches.as_slice(), destination_matches.as_slice()) {
([entity], _) => entity.id,
([], [entity]) => entity.id,
_ => return Err(WorkspaceError::Selector(selector.to_string())),
};
let replacement = source
.vec_entities(&kind)
.iter()
.find(|entity| entity.id == identity)
.cloned();
let target = destination.vec_entities_mut(&kind);
target.retain(|entity| entity.id != identity);
if let Some(entity) = replacement {
target.push(entity);
}
}
Ok(())
}
/// Copy mutable metadata not owned by an entity collection.
fn copy_world_metadata(source: &EpochInfo, destination: &mut EpochInfo) {
destination.rng_seed = source.rng_seed;
destination.tags = source.tags.clone();
destination.summary = source.summary.clone();
}
/// Validate stable identity, collection type, and relationship targets.
fn validate_world(label: &str, world: &EpochInfo) -> Result<(), WorkspaceError> {
let mut identities = BTreeMap::new();
for (entities, expected) in [
(&world.characters, EntityType::Character),
(&world.towns, EntityType::Town),
(&world.events, EntityType::Event),
(&world.calamities, EntityType::Calamity),
(&world.organizations, EntityType::Organization),
(&world.blockers, EntityType::Blocker),
] {
for entity in entities {
if entity.id.is_nil() || identities.insert(entity.id, expected).is_some() {
return Err(WorkspaceError::Inconsistent(format!(
"{label} contains a missing or duplicate entity UUID"
)));
}
if entity.entity_type != expected {
return Err(WorkspaceError::Inconsistent(format!(
"{label} stores `{}` in the wrong collection",
entity.name
)));
}
}
}
for entity in world
.characters
.iter()
.chain(&world.towns)
.chain(&world.events)
.chain(&world.calamities)
.chain(&world.organizations)
.chain(&world.blockers)
{
let value = serde_json::to_value(entity).map_err(|source| WorkspaceError::Json {
path: PathBuf::from(label),
source,
})?;
if let Some(links) = value
.pointer("/metadata/links")
.and_then(serde_json::Value::as_array)
{
for link in links {
let id: uuid::Uuid =
serde_json::from_value(link["other_id"].clone()).map_err(|source| {
WorkspaceError::Json {
path: PathBuf::from(label),
source,
}
})?;
let kind: EntityType =
serde_json::from_value(link["other_type"].clone()).map_err(|source| {
WorkspaceError::Json {
path: PathBuf::from(label),
source,
}
})?;
if identities.get(&id) != Some(&kind) {
return Err(WorkspaceError::Inconsistent(format!(
"{label} entity `{}` links to missing or mistyped @{id}",
entity.name
)));
}
}
}
for (field, kind) in [
("capital", EntityType::Town),
("governor", EntityType::Character),
] {
let Some(target) = value.pointer(&format!("/metadata/{field}")) else {
continue;
};
if target.is_null() {
continue;
}
let id: uuid::Uuid =
serde_json::from_value(target.clone()).map_err(|source| WorkspaceError::Json {
path: PathBuf::from(label),
source,
})?;
if identities.get(&id) != Some(&kind) {
return Err(WorkspaceError::Inconsistent(format!(
"{label} entity `{}` has a missing or mistyped {field} @{id}",
entity.name
)));
}
}
}
Ok(())
}
/// Find collection entries matching the public CLI identifier rules.
fn matches<'a>(
entities: &'a [crate::entity::Entity],
selector: &EntityIdentifier,
) -> Vec<&'a crate::entity::Entity> {
entities
.iter()
.filter(|entity| match selector {
EntityIdentifier::Name(name) => {
entity.name.to_lowercase().starts_with(&name.to_lowercase())
}
EntityIdentifier::Id(id) => entity.id.to_string().starts_with(id),
})
.collect()
}
/// Compare serializable worlds exactly.
fn same(left: &EpochInfo, right: &EpochInfo) -> bool {
serde_json::to_value(left).ok() == serde_json::to_value(right).ok()
}
/// Decode one repository JSON file.
fn decode<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, WorkspaceError> {
serde_json::from_slice(&read(path)?).map_err(|source| WorkspaceError::Json {
path: path.to_path_buf(),
source,
})
}
/// Read one repository file with path-aware diagnostics.
fn read(path: &Path) -> Result<Vec<u8>, WorkspaceError> {
fs::read(path).map_err(|source| io(path, source))
}
/// Serialize and transactionally replace one state layer.
fn save<T: Serialize>(
root: &Path,
relative: &str,
value: &T,
command: &str,
) -> Result<(), WorkspaceError> {
let path = root.join(relative);
let bytes = serde_json::to_vec_pretty(value).map_err(|source| WorkspaceError::Json {
path: path.clone(),
source,
})?;
replace_file(root, &path, &bytes, command)?;
Ok(())
}
/// Encode transaction content with a meaningful synthetic path.
fn encode<T: Serialize>(value: &T, label: &str) -> Result<Vec<u8>, WorkspaceError> {
serde_json::to_vec_pretty(value).map_err(|source| WorkspaceError::Json {
path: PathBuf::from(label),
source,
})
}
/// Attach the attempted path to an I/O error.
fn io(path: &Path, source: std::io::Error) -> WorkspaceError {
WorkspaceError::Io {
path: path.to_path_buf(),
source,
}
}