feat: address inspection tracker issues

This commit is contained in:
Dandaedre 2026-09-21 23:48:27 +02:00
parent f3a5aa0d58
commit 95193f4f42
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
11 changed files with 377 additions and 67 deletions

View File

@ -47,6 +47,12 @@ reviewable worktree inverse, `revert --commit` warns before adding history, and
Recoverable future pruning remains the recommended alternative and rewinds the
next epoch to `HEAD + 1`, with allocator and tags included in its backup.
**Tracker checkpoint — inspection and audit: complete.** Gitea issues #18 and
#19 are addressed by unified filtered entity/epoch inspection, and #14 now
validates links in every historical epoch. The remaining tracker items are
mapped to implemented, partial, blocked, and planned work in
[`docs/issue-audit.md`](docs/issue-audit.md).
## Phase 0 — audit and guardrails
- [x] Inventory workspace crates, commands, persistence files, CI, and tests.

View File

@ -57,7 +57,7 @@ pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> {
if entry.file_type()?.is_dir()
&& let Ok(id) = entry.file_name().to_string_lossy().parse()
{
workspace.load_epoch(id)?;
workspace.check_epoch(id)?;
checked += 1;
}
}

View File

@ -1,39 +1,102 @@
//! Inspect entities in the current epoch.
//! Unified entity and epoch inspection.
use clap::Subcommand;
use lib_efo::{Displayable, stats::EntityType};
use std::path::Path;
use clap::{Args, ValueEnum};
use lib_efo::{
Displayable,
entity::Entity,
epoch::{EpochId, EpochIdentifier, EpochInfo},
stats::{EntityType, Position},
workspace::Workspace,
};
use crate::error::AppError;
/// Entity collections that can be displayed from the current epoch.
#[derive(Subcommand, Debug)]
pub enum ShowCmd {
/// Show all entity collections.
/// Collection selected by `efo show`.
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum ShowKind {
/// Every entity collection.
#[default]
All,
/// Show events.
/// Events.
Event,
/// Show characters.
/// Characters.
#[value(alias = "chr")]
Character,
/// Show towns.
/// Towns.
Town,
/// Show calamities.
/// Calamities.
Calamity,
/// Show organisations.
/// Organisations.
#[value(aliases = ["org", "organisation"])]
Organization,
/// Show blockers.
/// Blockers.
Blocker,
/// Committed epoch summaries.
Epoch,
}
/// Display the selected collection from the repository's current epoch.
pub fn handle_show_cmd(cmd: &ShowCmd) -> Result<(), AppError> {
let workspace = lib_efo::workspace::Workspace::open(std::path::Path::new("."))?;
render(cmd, &workspace.worktree.world)
/// Amount of information rendered for each match.
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum ShowDetail {
/// Compact identity, position, and aggregate statistics.
#[default]
Short,
/// Short output plus descriptions and epoch metadata.
Long,
/// Complete entity trees/stat tables or persisted epoch JSON.
Full,
}
/// Render selected collections from an already loaded world.
fn render(cmd: &ShowCmd, epoch: &lib_efo::epoch::EpochInfo) -> Result<(), AppError> {
let selected: &[(&str, EntityType)] = match cmd {
ShowCmd::All => &[
/// Search and rendering options for `efo show`.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo show\n efo show town\n efo show all --name north\n efo show calamity --text dragon --detail long\n efo show town --position 66,57\n efo show epoch --detail long\n efo show epoch --epoch 3 --detail full"
)]
pub struct ShowArgs {
/// Collection to inspect; defaults to all entities.
#[arg(value_enum, default_value_t)]
kind: ShowKind,
/// Case-insensitive substring of the entity name.
#[arg(long)]
name: Option<String>,
/// Case-insensitive substring of the name or description.
#[arg(long)]
text: Option<String>,
/// Exact entity position.
#[arg(long)]
position: Option<Position>,
/// Read a committed epoch by numeric ID or exact tag instead of the worktree.
#[arg(long)]
epoch: Option<EpochIdentifier>,
/// Output detail level.
#[arg(long, value_enum, default_value_t)]
detail: ShowDetail,
}
/// Display filtered repository content through one command surface.
pub fn handle_show_cmd(args: &ShowArgs) -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
if matches!(args.kind, ShowKind::Epoch) {
return render_epochs(args, &workspace);
}
let world = args
.epoch
.as_ref()
.map(|identifier| resolve(&workspace, identifier))
.transpose()?
.map(|id| workspace.load_epoch(id))
.transpose()?
.unwrap_or_else(|| workspace.worktree.world.clone());
render_entities(args, &world);
Ok(())
}
/// Render selected entity collections and filters.
fn render_entities(args: &ShowArgs, world: &EpochInfo) {
let selected: &[(&str, EntityType)] = match args.kind {
ShowKind::All => &[
("Characters", EntityType::Character),
("Towns", EntityType::Town),
("Events", EntityType::Event),
@ -41,25 +104,136 @@ fn render(cmd: &ShowCmd, epoch: &lib_efo::epoch::EpochInfo) -> Result<(), AppErr
("Organisations", EntityType::Organization),
("Blockers", EntityType::Blocker),
],
ShowCmd::Event => &[("Events", EntityType::Event)],
ShowCmd::Character => &[("Characters", EntityType::Character)],
ShowCmd::Town => &[("Towns", EntityType::Town)],
ShowCmd::Calamity => &[("Calamities", EntityType::Calamity)],
ShowCmd::Organization => &[("Organisations", EntityType::Organization)],
ShowCmd::Blocker => &[("Blockers", EntityType::Blocker)],
ShowKind::Event => &[("Events", EntityType::Event)],
ShowKind::Character => &[("Characters", EntityType::Character)],
ShowKind::Town => &[("Towns", EntityType::Town)],
ShowKind::Calamity => &[("Calamities", EntityType::Calamity)],
ShowKind::Organization => &[("Organisations", EntityType::Organization)],
ShowKind::Blocker => &[("Blockers", EntityType::Blocker)],
ShowKind::Epoch => unreachable!("epochs are dispatched separately"),
};
for (index, (title, entity_type)) in selected.iter().enumerate() {
if index > 0 {
for (section, (title, entity_type)) in selected.iter().enumerate() {
if section > 0 {
println!();
}
let entities = epoch.vec_entities(entity_type);
println!("{title} ({})", entities.len());
if entities.is_empty() {
let matches = world
.vec_entities(entity_type)
.iter()
.filter(|entity| matches_filters(entity, args))
.collect::<Vec<_>>();
println!("{title} ({})", matches.len());
if matches.is_empty() {
println!(" — none");
continue;
}
for entity in matches {
match args.detail {
ShowDetail::Short => println!("{}", entity.short_display(world)),
ShowDetail::Long => {
println!("{}", entity.short_display(world));
if !entity.description.trim().is_empty() {
println!(" {}", entity.description);
}
}
ShowDetail::Full => entity.print_full(world),
}
}
}
}
/// Apply all requested entity predicates.
fn matches_filters(entity: &Entity, args: &ShowArgs) -> bool {
let name = entity.name.to_lowercase();
let description = entity.description.to_lowercase();
args.name
.as_ref()
.is_none_or(|query| name.contains(&query.to_lowercase()))
&& args.text.as_ref().is_none_or(|query| {
let query = query.to_lowercase();
name.contains(&query) || description.contains(&query)
})
&& args
.position
.as_ref()
.is_none_or(|position| entity.position().distance(position) == 0)
}
/// Render one epoch or every stored epoch in numeric order.
fn render_epochs(args: &ShowArgs, workspace: &Workspace) -> Result<(), AppError> {
let ids = if let Some(identifier) = &args.epoch {
vec![resolve(workspace, identifier)?]
} else {
let mut ids = std::fs::read_dir(workspace.root().join("epoch"))?
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().to_string_lossy().parse::<EpochId>().ok())
.collect::<Vec<_>>();
ids.sort_unstable();
ids
};
for id in ids {
let epoch = workspace.load_epoch(id)?;
let head = if id == workspace.manifest.epoch_id {
"*"
} else {
print!("{}", entities.short_display(epoch));
" "
};
match args.detail {
ShowDetail::Short => println!("{head} epoch {id} — {}", message(&epoch)),
ShowDetail::Long => {
println!("{head} epoch {id} — {}", message(&epoch));
println!(
" parent: {} · entities: {} · tags: {}",
epoch
.parent_epoch
.map_or_else(|| "—".into(), |id| id.to_string()),
entity_count(&epoch),
if epoch.tags.is_empty() {
"—".into()
} else {
epoch.tags.to_string()
}
);
if !epoch.summary.is_empty() {
println!(" summary: {}", epoch.summary);
}
}
ShowDetail::Full => println!(
"{}",
serde_json::to_string_pretty(&epoch).map_err(lib_efo::error::StorageError::from)?
),
}
}
Ok(())
}
/// Resolve a numeric epoch ID or exact tag.
fn resolve(workspace: &Workspace, identifier: &EpochIdentifier) -> Result<EpochId, AppError> {
match identifier {
EpochIdentifier::Id(id) => Ok(*id),
EpochIdentifier::Tag(tag) => workspace
.manifest
.tags
.get(tag)
.copied()
.ok_or_else(|| lib_efo::error::EpochError::EpochNotFound(tag.clone()).into()),
}
}
/// Human commit-message fallback.
fn message(epoch: &EpochInfo) -> &str {
if epoch.commit_message.is_empty() {
"initial snapshot"
} else {
&epoch.commit_message
}
}
/// Total entities in an epoch.
fn entity_count(epoch: &EpochInfo) -> usize {
epoch.characters.len()
+ epoch.towns.len()
+ epoch.events.len()
+ epoch.calamities.len()
+ epoch.organizations.len()
+ epoch.blockers.len()
}

View File

@ -35,7 +35,7 @@ use crate::{
history::{CommitCmd, LogCmd, PruneFutureCmd, ResetCmd, RevertCmd, SwitchCmd},
init::InitCmd,
safety::{LockCmd, RecoverCmd},
show::ShowCmd,
show::ShowArgs,
state::{RestoreCmd, StageCmd, StateDiffCmd},
status::StatusCmd,
},
@ -101,9 +101,8 @@ enum TopLevelCmd {
/// Advance or query the current epoch.
#[command(subcommand)]
Epoch(EpochCmd),
/// Inspect entities in the current epoch
#[command(subcommand)]
Show(ShowCmd),
/// Inspect and filter entities or committed epochs.
Show(ShowArgs),
/// Handle characters
#[command(subcommand)]
#[command(visible_alias = "character")]

View File

@ -537,3 +537,85 @@ fn seeded_world_generation_previews_applies_and_restores() {
));
assert_eq!(snapshot(&repo, 0), first);
}
#[test]
fn unified_show_filters_entities_and_summarises_epochs() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
assert_success(&efo(
&repo,
&[
"town",
"add",
"Northwatch",
"--position",
"10,20",
"--desc",
"A fortress watching for dragons",
],
));
assert_success(&efo(
&repo,
&["town", "add", "Southport", "--position", "30,40"],
));
let default_show = efo(&repo, &["show"]);
assert_success(&default_show);
assert!(stdout(&default_show).contains("Northwatch"));
assert!(stdout(&default_show).contains("@"));
let by_name = efo(&repo, &["show", "town", "--name", "north"]);
assert_success(&by_name);
assert!(stdout(&by_name).contains("Northwatch"));
assert!(!stdout(&by_name).contains("Southport"));
let by_text = efo(
&repo,
&["show", "all", "--text", "dragon", "--detail", "long"],
);
assert_success(&by_text);
assert!(stdout(&by_text).contains("fortress watching for dragons"));
let by_position = efo(&repo, &["show", "town", "--position", "30,40"]);
assert_success(&by_position);
assert!(!stdout(&by_position).contains("Northwatch"));
assert!(stdout(&by_position).contains("Southport"));
assert_success(&efo(&repo, &["stage", "--all"]));
assert_success(&efo(&repo, &["commit", "-m", "Populate ports"]));
let epochs = efo(&repo, &["show", "epoch", "--detail", "long"]);
assert_success(&epochs);
assert!(stdout(&epochs).contains("epoch 0"));
assert!(stdout(&epochs).contains("epoch 1 — Populate ports"));
let full_epoch = efo(
&repo,
&["show", "epoch", "--epoch", "1", "--detail", "full"],
);
assert_success(&full_epoch);
assert!(stdout(&full_epoch).contains("\"commit_message\": \"Populate ports\""));
}
#[test]
fn fsck_validates_links_inside_historical_epochs() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
assert_success(&efo(&repo, &["chr", "add", "Aria"]));
assert_success(&efo(&repo, &["town", "add", "Durn", "--governor", "Aria"]));
assert_success(&efo(&repo, &["stage", "--all"]));
assert_success(&efo(&repo, &["commit", "-m", "Govern Durn"]));
let path = repo.path().join("epoch/1/epochinfo.json");
let mut epoch: serde_json::Value =
serde_json::from_slice(&fs::read(&path).expect("read epoch")).expect("parse epoch");
epoch["characters"][0]["metadata"]["links"][0]["other_id"] =
serde_json::Value::String(Uuid::new_v4().to_string());
fs::write(
&path,
serde_json::to_vec_pretty(&epoch).expect("encode broken epoch"),
)
.expect("write broken epoch");
let check = efo(&repo, &["epoch", "fsck"]);
assert!(!check.status.success());
assert!(stderr(&check).contains("links to missing or mistyped"));
}

View File

@ -14,6 +14,8 @@ behavior clearly.
- [Simulation and world generation](simulation-worldgen-design.md): seeded
fuzzing, roads, movement, diffusion, map rendering, and config packaging.
- [Roadmap](roadmap.md): current work and stretch proposals.
- [Gitea issue audit](issue-audit.md): disposition and dependencies of the
upstream tracker backlog.
Start with the project [README](../README.md). Contributors should also read
[AGENTS.md](../AGENTS.md) and maintain [AGENTS-TASKS.md](../AGENTS-TASKS.md).

View File

@ -79,9 +79,13 @@ the retained target.
already staged changes, advances entity time, and commits one new monotonic ID.
`efo epoch fsck` validates all state layers and every immutable epoch.
`efo show all` lists every collection in the current epoch. `show character`,
`show town`, `show event`, `show calamity`, and `show blocker` select one
collection. Use `<noun> show IDENTIFIER` for full details of one entity.
`efo show` defaults to every collection. `show character`, `show town`, `show
event`, `show calamity`, `show organization`, and `show blocker` select one.
Filter with `--name TEXT`, `--text TEXT`, or `--position X,Y`; select a
committed snapshot with `--epoch ID_OR_TAG`. `--detail short|long|full`
controls output density. `efo show epoch` lists committed epoch summaries and
accepts the same `--epoch` and detail options. Use `<noun> show IDENTIFIER` for
the complete details of one entity by its name or stable ID.
## Generation and output

27
docs/issue-audit.md Normal file
View File

@ -0,0 +1,27 @@
# Gitea issue audit
This audit maps the open issues from the
[project tracker](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues)
to the current codebase as of 2026-09-21. Tracker entries predate several
milestones, so an open checkbox does not necessarily mean the behavior is
absent.
| Issue | Current assessment | Next action |
|---|---|---|
| [#19 Tweak Show](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/19) | Addressed: normal rows now use a dedicated short renderer with name, kind, stable ID, position, and aggregate stats. | Verify visual density in real terminals. |
| [#18 Implement show](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/18) | Addressed for the CLI: `show` defaults to all, dispatches every collection, filters by name/text/position, reads historical epochs, and renders epoch summaries at three detail levels. | Consider structured output and richer stat predicates later. |
| [#17 Serialization errors/upgrades](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/17) | Version detection and actionable rejection are complete. No legacy release exists, so a speculative upgrader was intentionally removed. | Add explicit `1.x` migrations when the first real format change exists. |
| [#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) | Open. Effect bounds exist, but a documented global stat-domain policy does not. | Define per-stat versus configurable bounds before enforcement. |
| [#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. |
| [#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. |
| [#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. |
Preferred order: finish display buffering/structured output, specify stat
bounds and custom fields, implement roads/residency, then build influx,
fight/war, and diffusion on those foundations.

View File

@ -24,6 +24,18 @@ impl Displayable for Entity {
}
}
/// Compact human summary with stable identity and useful world context.
fn short_display(&self, _epoch_info: &EpochInfo) -> String {
format!(
" • {:24} {} @{} · {} · {}",
self.name,
self.entity_type.to_shortest(),
&self.id.to_string()[..8],
self.metadata.position.to_shortest(),
self.stats.to_symbol(),
)
}
/// One-liner used for auto-generation of `Vec<T>` displays
// TODO: URGENT: Change this display
fn oneline_display(&self) -> String {

View File

@ -295,24 +295,8 @@ impl EpochConfig {
Ok(())
}
/// Update **all** temporary values of every entity in the current epoch.
///
/// # Safety
/// * The caller must guarantee that the current epoch is **loaded** and
/// its storage is still valid for the duration of the call.
/// * The function performs raw pointer arithmetic / `unsafe` reads/writes
/// on the internal data structures. No other thread may be mutably
/// borrowing the same data at the same time.
pub unsafe fn update_all_temporary_values(&mut self) {}
/// Reset **all** temporary values to the current live values.
///
/// # Safety
/// * The caller must ensure that the current epoch is loaded and that
/// no other mutable references to the same data exist.
/// * This method writes directly into the entity structs; any concurrent
/// access will lead to undefined behaviour.
pub unsafe fn reset_temporary_stats(&mut self) -> Result<(), EpochError> {
pub fn reset_temporary_stats(&mut self) -> Result<(), EpochError> {
let current_epoch = self.try_load_current_as_mut()?;
current_epoch
.vec_entities_mut(&stats::EntityType::Town)
@ -322,14 +306,6 @@ impl EpochConfig {
Ok(())
}
/// Update temporary values for every entity assuming the current epoch
/// is loaded.
///
/// # Safety
/// * Same as `update_all_temporary_values`: the current epoch must be
/// loaded and no other mutable references may exist.
pub unsafe fn update_temps(&mut self) {}
/// Insert a new epoch into the configuration and persist it.
///
/// The function creates the epoch's directory, writes its metadata,

View File

@ -434,6 +434,12 @@ impl Workspace {
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() {
@ -881,6 +887,28 @@ fn validate_world(label: &str, world: &EpochInfo) -> Result<(), WorkspaceError>
}
}
}
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(())
}