Compare commits

...

52 Commits
v0.1.0 ... main

Author SHA1 Message Date
Dandaedre 88d3fc4695
feat: adjudicate fights and wars
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-22 04:50:25 +02:00
Dandaedre 59db826aa2
feat: add persistent conflict model 2026-09-22 04:41:29 +02:00
Dandaedre 49b05cafbf
feat: resolve diffusion arrivals 2026-09-22 03:38:52 +02:00
Dandaedre 17747d7f48
feat: persist adjudicated event potency
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-22 03:20:35 +02:00
Dandaedre dcb3bce2ad
feat: add progressive adjudication defaults 2026-09-22 03:11:26 +02:00
Dandaedre 831c07b192
feat: record external adjudications 2026-09-22 02:59:15 +02:00
Dandaedre 9481146bce
fix: model influx as external adjudication 2026-09-22 02:51:21 +02:00
Dandaedre 0e9999fa18
feat: add deterministic influx rules
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-22 02:28:46 +02:00
Dandaedre 4bf484a96e
docs: prepare tracker simulation and output work 2026-09-22 01:46:15 +02:00
Dandaedre 70123bf0d5
feat: add reversible event diffusion 2026-09-22 01:04:30 +02:00
Dandaedre 0b62ab9968
feat: add reversible roads and travel 2026-09-22 00:41:09 +02:00
Dandaedre c5e4cf27d1
refactor: buffer inspection output 2026-09-22 00:31:23 +02:00
Dandaedre f36a339d5c
perf: add ephemeral entity indexes 2026-09-22 00:29:21 +02:00
Dandaedre 40b4bc1a35
refactor: centralize typed world diffs 2026-09-22 00:26:39 +02:00
Dandaedre 6210f5e737
fix: enforce entity stat domains 2026-09-22 00:20:11 +02:00
Dandaedre 95193f4f42
feat: address inspection tracker issues 2026-09-21 23:48:27 +02:00
Dandaedre f3a5aa0d58
fix: rewind allocator when pruning future 2026-09-21 23:31:38 +02:00
Dandaedre c52bc49d05
feat: clarify revert and add hard reset 2026-09-21 21:44:53 +02:00
Dandaedre 8d0a1538a1
feat: add previewed TUI entity creation and editing with undo 2026-09-21 19:26:40 +02:00
Dandaedre 83bcbf8180
feat: toggle formatted and JSON entity details in the TUI 2026-09-21 19:09:46 +02:00
Dandaedre e7241a3874
feat: mature the read-only TUI browser for release 2026-09-21 19:03:15 +02:00
Dandaedre fc6c28e67b
feat: add curated Draän example world
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-21 18:44:35 +02:00
Dandaedre 41abf73006
chore: relocate local test repository
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-21 02:41:44 +02:00
Dandaedre 728cc23cf2
test: raise measured coverage above 70 percent
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-21 02:39:38 +02:00
Dandaedre 79ce7f84d3
feat: add deterministic configured world generation
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-21 02:17:44 +02:00
Dandaedre 4a8af40dc6
docs: design spatial simulation and worldgen 2026-09-21 02:12:52 +02:00
Dandaedre 150be03511
refactor: make reversible format the initial layout 2026-09-21 02:10:24 +02:00
Dandaedre 3f7db618b2
feat: add read-only repository tui
Rust CI Epoch Forge passed all CI checks.
Gitea/epoch_forge/pipeline/head This commit looks good Details
2026-09-21 01:25:25 +02:00
Dandaedre ee40a29987
docs: approve first tui checkpoint 2026-09-21 01:17:39 +02:00
Dandaedre d841899545
feat: show staged and unstaged status details 2026-09-21 00:42:18 +02:00
Dandaedre 0b9fba78a0
feat: complete reversible format 2 history 2026-09-21 00:41:49 +02:00
Dandaedre c6442bdeac
feat: add atomic format 2 commits and log 2026-09-21 00:29:13 +02:00
Dandaedre d938e27288
feat: add format 2 staging and restore workflow 2026-09-21 00:25:33 +02:00
Dandaedre 3332810491
feat: expose lock inspection and recovery 2026-09-21 00:20:36 +02:00
Dandaedre 881fc7265a
feat: add repository locks and recovery journal 2026-09-21 00:19:46 +02:00
Dandaedre b73030a4fb
feat: add explicit format migration workflow 2026-09-21 00:03:04 +02:00
Dandaedre 50d9c3bff8
feat: add validated repository migration engine 2026-09-21 00:00:39 +02:00
Dandaedre b87dd9eda8
feat: establish versioned repository format 2026-09-20 22:16:37 +02:00
Dandaedre d4548ff479
docs: propose reversible staging contract 2026-09-20 22:09:02 +02:00
Dandaedre 1f24bc58b9
docs: complete dependable daily CLI milestone 2026-09-20 22:04:06 +02:00
Dandaedre cd09677471
feat: document and validate reversible daily workflows 2026-09-20 22:02:22 +02:00
Dandaedre cff2cd0dcf
feat: add organisation management and compatible naming 2026-09-20 22:00:08 +02:00
Dandaedre 36757dca57
feat: add portable terminal output feature 2026-09-20 21:57:25 +02:00
Dandaedre 3e18ddb870
docs: complete trustworthy foundation milestone 2026-09-20 21:02:27 +02:00
Dandaedre 8609816990
test: cover complete CLI repository workflows 2026-09-20 21:00:07 +02:00
Dandaedre c24e4b5696
fix: make snapshot writes atomic and reject unsupported stats 2026-09-20 20:58:58 +02:00
Dandaedre f1e3addc16
docs: record completed hardening work 2026-09-20 20:56:40 +02:00
Dandaedre b6f74e6e83
fix: keep status complete and name generation read-only 2026-09-20 20:56:21 +02:00
Dandaedre a3708a843f
fix: make init safe and show repository state 2026-09-20 20:54:58 +02:00
Dandaedre 59a533e2f3
feat: add safe epoch diff and consistency checks 2026-09-20 20:53:27 +02:00
Dandaedre 94b3d75b2b
docs: align guides with current CLI behavior 2026-09-20 20:50:59 +02:00
Dandaedre d9b656f74c
docs: establish project guardrails and delivery plan 2026-09-20 20:47:41 +02:00
103 changed files with 21527 additions and 862 deletions

7
.gitignore vendored
View File

@ -29,3 +29,10 @@ testepo*
naming.json
config.toml
tarpaulin-report.html
# Local repositories used for manual CLI testing and IDE inspection.
/.local/
# Local source material used to curate examples. Finished examples belong in
# /examples and remain tracked.
/ressources/

View File

@ -1,8 +1,16 @@
[last_run_clean]
run_status = "Success"
lines_parsed = 110
coverage = 48.83
lines_parsed = 5
[last_run_clean.run_duration]
secs = 27
nanos = 30003945
secs = 0
nanos = 55273825
[last_run_incremental]
run_status = "Success"
lines_parsed = 174
coverage = 78.44
[last_run_incremental.run_duration]
secs = 6
nanos = 681584522

402
AGENTS-TASKS.md Normal file
View File

@ -0,0 +1,402 @@
# Epoch Forge delivery plan
This is the working backlog for bringing the current CLI to a trustworthy
early-alpha release. Checkboxes describe completion, not intention. Newly found
work belongs here before implementation.
**Milestone 1 — trustworthy foundation: complete.** Phases 0–2 passed their
acceptance gates on 2026-09-20.
**Milestone 2 — dependable daily CLI: complete.** Phase 3 passed its acceptance
gates on 2026-09-20. The Phase 4 format contract was approved on 2026-09-20.
**Milestone 3 — safe format transition: superseded before release.** Its
prototype migration proved the transaction design, then was deliberately
removed when the reversible layout became the only initial format.
**Milestone 4 — Git-like reversible workflow: complete.** Phase 4 passed its
default and portable test, Clippy, and release gates on 2026-09-21. Format 1.0
is native, transactional, staged, immutable, and recoverable.
**Milestone 5 — first TUI checkpoint: complete.** Its read-only scope,
terminal lifecycle, keyboard contract, and accessibility gate passed default
and portable release gates on 2026-09-21. See
[`docs/tui-design.md`](docs/tui-design.md).
**Milestone 6 — pre-release format consolidation: complete.** Native
initialisation now creates the reversible format directly; the unreleased
prototype reader, migration command, fixtures, and compatibility aliases are
removed. Future evolution uses explicit `1.x` major/minor versions. Default
and portable quality and release gates passed on 2026-09-21.
**Milestone 7 — deterministic worldgen foundation: complete.** The spatial,
fuzzing, configuration, rendering, and release-asset contract is approved in
[`docs/simulation-worldgen-design.md`](docs/simulation-worldgen-design.md).
Embedded and override configuration, deterministic generation, safe CLI apply,
packaging, and default/portable release gates passed on 2026-09-21.
**Example checkpoint — curated Draän base world: complete.** A clean,
committed repository with a copied 3840×2160 map, 50 positioned entities, lore,
governance links, and active events is tracked under
[`examples/ravenous-draan`](examples/ravenous-draan/README.md). Integration
tests open it as a real repository and validate its map and world invariants.
**History semantics checkpoint: complete.** `revert` now defaults to a
reviewable worktree inverse, `revert --commit` warns before adding history, and
`reset --hard` provides a previewed, explicitly confirmed destructive rewind.
Recoverable future pruning remains the recommended alternative and never
reuses removed epoch IDs; allocator and tags are 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).
**Tracker checkpoint — stat domains: complete.** Issue #15 now has one
enforced policy across CLI edits, TUI drafts, derived-stat recalculation, and
workspace validation without clamping real population counts.
**Tracker prework — issues #9, #8, #10, and #12: complete.** The shared
deterministic resolution, diffusion-outcome, generic conflict, presentation,
export, persistence, CLI, safety, and test contracts are implementation-ready
in [`docs/resolution-conflict-design.md`](docs/resolution-conflict-design.md)
and [`docs/presentation-design.md`](docs/presentation-design.md).
## Phase 0 — audit and guardrails
- [x] Inventory workspace crates, commands, persistence files, CI, and tests.
- [x] Run the untouched baseline test suite (58 library tests; 0 binary tests).
- [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.
- [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.
## Phase 1 — honest documentation and CLI contract
- [x] Replace the README's advertised-but-missing commands with a concise,
verified capability summary and working quick start.
- [x] Add `docs/README.md` as the documentation index.
- [x] Add a command reference based on verified `--help` behavior.
- [x] Document the repository layout, identifiers, epochs, persistence, and
manual backup/recovery procedure.
- [x] Add an architecture guide covering crate boundaries and data flow.
- [x] Add a compatibility policy for stored data and CLI scripts.
- [x] Add a roadmap that distinguishes implemented, current-release, planned,
and stretch work.
- [x] Correct typos, stale rustdoc examples, and misleading comments.
## Phase 2 — test and harden the existing product
- [x] Add CLI integration-test infrastructure using the built `efo` binary and
isolated temporary directories.
- [x] Test root and nested help, version output, invalid commands, and exit
status/stderr conventions.
- [x] Test `init`, including non-empty directories, already initialised repos,
and the promised `--force` semantics.
- [x] Test `status` and repository discovery/error reporting.
- [x] Test the full entity lifecycle for each exposed type: add, show, edit,
diff, and delete by name and stable identifier.
- [x] Test epoch workflows: next, log, switch, diff, tag, summary, and reset.
- [x] Test malformed/corrupt configuration and snapshot files without panics.
- [x] Test interrupted/failed writes where feasible and implement atomic file
replacement for repository metadata and epoch snapshots.
- [x] Remove currently reported unused dependencies and the demo `show` path.
- [x] Make format, tests, strict Clippy, and release build pass.
## Phase 3 — finish the intended current CLI
- [x] Make `efo show` inspect actual world state or replace it with a coherent
command surface; remove its current generated demonstration output.
- [x] Make `efo status` clearly show current epoch, timeline divergence/future
snapshots, entity totals, and a clean/modified indicator if detectable.
- [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.
- [x] Make `init --force` safe and explicit; it must not silently destroy an
existing Epoch Forge repository or unrelated files.
- [x] Resolve naming inconsistencies (`chr`, calamity mapped to monster,
missing organisation surface) with aliases/deprecation where compatibility
warrants it.
- [x] Improve all command help with examples and valid-value guidance.
- [x] Replace ambiguous success output and Nerd-Font-only semantics with clear,
attractive Unicode output that degrades safely without colour.
- [x] Ensure entity editing validates type-specific fields and reports useful
recovery advice.
- [x] Ensure every existing mutation has a documented and tested reversal via
epoch switching/reset/restore or an explicit backup workflow.
## Phase 4 — Git-like reversible workflow
- [x] Approve the written design for working state, pseudo-staging, committed
epochs, and recovery semantics before implementing it. See
[the Phase 4 proposal](docs/staging-design.md).
- [x] Define `diff`, `stage`, `unstage`/`restore --staged`, `commit`, `restore`,
`revert`, and `log` behavior, including entity-level selection.
- [x] Define crash consistency, locking, concurrent-process behavior, and
repository format versioning.
- [x] Retire the pre-release migration fixture matrix once its source format
was confirmed never to have shipped.
- [x] Make `efo init` create HEAD, index, worktree, and format-1.0 manifest
transactionally without a migration step.
- [x] Add durable single-file transaction journaling, exclusive writer locks,
lock inspection/break primitives, and deterministic interrupted-write
recovery.
- [x] Extend transactions across ordered multi-file commits with rollback
copies and a manifest-last commit point.
- [x] Remove the obsolete migration rollback surface and retain transaction
recovery for interrupted writes.
- [x] Implement worktree/index-aware `status`, `diff`, `stage`, and both restore
directions without changing immutable epochs.
- [x] Implement committed epochs, `log`, reviewable and conflict-safe `revert`,
backed-up `prune-future`, and explicit previewed `reset --hard` destruction.
- [x] Complete Phase 4 only after every ordinary mistake is reversible without
manual JSON editing and both default and portable release gates pass.
## Phase 5 — organisation-agnostic extensibility (upcoming release)
- [ ] Design custom fields with stable serialization and typed scalar/list/map
values; retain unknown fields across old/new binary round trips.
- [ ] Generalise faction/organisation concepts without baking in fantasy-game
assumptions.
- [ ] Define schemas/templates, optional validation, inheritance, and display
ordering for custom entity kinds.
- [ ] Provide import/export and migration tooling before changing defaults.
- [ ] Test repositories containing user-defined fields and entity kinds.
## TUI checkpoint 1 — safe repository browser
- [x] Approve the separate-binary architecture and read-only first-pass scope.
- [x] Define keyboard navigation, compact-layout, accessibility, and terminal
restoration requirements.
- [x] Add the `efo-tui` workspace binary without coupling `lib_efo` to a
terminal framework.
- [x] Render HEAD/index/worktree status and all entity collections.
- [x] Provide collection, entity, and detail navigation with contextual help.
- [x] Report unsupported, corrupt, locked, and interrupted repositories with the
next useful CLI command.
- [x] Unit test state transitions and deterministic rendering with a test
backend.
- [x] Document installation, startup, keys, scope, and CLI fallback paths.
- [x] Pass default and portable formatting, test, strict Clippy, and release
gates without running release-only badge tooling.
## Simulation and generation track
### Checkpoint 1 — deterministic configuration-driven worldgen
- [x] Define cumulative event/settlement/region/world generation levels.
- [x] Choose embedded defaults plus explicit local `--config` overrides.
- [x] Define seeded reproducibility, preview/apply behavior, and restoration.
- [x] Add a versioned `WorldGenConfig` with strict semantic validation.
- [x] Move canonical defaults to `lib_efo/assets/worldgen/default.json` and
embed them in the library.
- [x] Generate deterministic IDs, positions, names, events, and entity counts
from a caller-supplied seed without thread-local randomness.
- [x] Add `efo gen world --level ... --seed ... [--config ...] [--apply]` with
preview as the default and worktree-only application.
- [x] Add seed-replay, invalid-config, invariant, and CLI reversal tests.
- [x] Package the editable config and schema notes as a reproducible zip;
document the Gitea release upload endpoint without publishing in routine CI.
### Checkpoint 2 — roads, residency, and travel
- [x] Add stable, validated road edges between positioned place entities.
- [x] Model resident, roaming, and travelling character states without
overloading governance links.
- [x] Implement deterministic shortest-time routing with road speed and slower
direct-travel fallback.
- [x] Preview travel plans and advance progress only through staged simulation
ticks with clear restore/revert guidance.
- [x] Exercise disconnected, cyclic, duplicate, malformed, and legacy topology
in deterministic tests; broader cargo-fuzz targets remain release hardening.
### Checkpoint 3 — spatial event diffusion
- [x] Define event origins, speed, frontier, affected-set, and expiry data.
- [x] Diffuse over roads and slower direct distance using configured
coefficients and deterministic tie-breaking.
- [x] Preview each tick with route/reason output before applying it.
- [x] Test repeated application, convergence, expiry, disconnected graphs, and
deterministic replay across many seeds.
### Checkpoint 3.5 — tracker simulation resolution (#9, #8, #12)
- [x] Approve the shared prework contract in
`docs/resolution-conflict-design.md`.
- [x] Add a separately versioned, embedded `AdjudicationConfig` with strict
validation, external replacement, safety limits, and release packaging.
- [x] Correct the original influx assumption: an adjudication records a
player-made external roll plus the master's level, disposition, explanation,
and explicit effects; Epoch Forge never rolls or invents an effect.
- [x] Implement all six stable master-assigned levels, explicit effects,
disposition-controlled attenuation, clamping, and stale-checkable reports.
- [x] Persist idempotent, stale-state-checked adjudication records with workspace
and historical `fsck` validation.
- [x] Add preview/apply/list `adjudicate` commands plus the familiar `influx`
alias and complete help examples. Records deliberately cannot be cleared
independently of their effects; use worktree restore or historical revert.
- [x] Make explicit effects optional: embedded/configurable defaults use a
monotonic excellent-to-apocalypse dampening scale, while any `--effect`
replaces the fallback and the audit record identifies which path was used.
- [x] Persist source-event potency outside ordinary statistics, monotonically
dampen future policy-default effects, expose it in command output, and make a
destroyed ruling expire/prevent diffusion with restore/revert recovery.
- [x] Resolve diffusion arrivals against protected towns and configured
blockers, explaining avoided/dampened/destroyed outcomes.
- [x] Resolve resident and positioned characters deterministically; document
the initial policy for characters currently in transit.
- [x] Add generic multi-side conflict records, participant validation, pure
fight/war round resolution, victory, stalemate, and explicit ending.
- [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.
- [x] Cover deterministic preview, explicit effects, attenuation, avoided and
destroyed no-op effects, clamping, stale/repeated application, CLI audit,
aliasing, and worktree restoration.
### Presentation completion (#10)
- [x] Approve the remaining renderer/export contract in
`docs/presentation-design.md` and inventory production direct output.
- [ ] Add shared output options, semantic document blocks, a single process
sink, and an atomic non-overwriting output-file writer.
- [ ] Migrate destructive/safety and simulation previews to typed reports and
buffered human/plain/JSON rendering.
- [ ] Migrate state/history, entity, and generation output without changing
domain behavior.
- [ ] Remove production printing from `lib_efo`; retain strings or writer-based
compatibility APIs only where necessary.
- [ ] Add a source-policy check preventing new production print macros outside
the output sink and entry error boundary.
- [ ] Test colour/portable/redirection behavior, stable JSON schemas, output
collisions, permission failures, atomicity, large lists, and help examples.
- Raw audit baseline: 122 print-macro call sites across 15 source files;
comments and test-only calls will be excluded when enforcing the final gate.
### Checkpoint 4 — PNG map rendering
- [ ] Store optional base-map path and coordinate bounds without embedding
image bytes in repository history.
- [ ] Render entities, roads, travellers, events, and diffusion fronts onto a
supplied PNG or a generated blank RGBA canvas.
- [ ] Use shape and labels as well as colour, enforce allocation limits, and
atomically write a distinct output path.
- [ ] Add pixel/snapshot fixtures for blank and supplied-base rendering.
- [ ] Add `efo map render` help, examples, and recovery-safe error messages.
## Stretch goals — proposal only
These require user approval and are not part of the current implementation:
- [x] Previewed TUI entity creation/editing and one-step undo through library
transactions (authorized in the entity-authoring request below).
- [ ] Branching timelines with named branches and merge/conflict workflows.
- [ ] Shell completions and man pages generated from the Clap command model.
- [ ] JSON/JSONL output modes and stable query/filter expressions for scripts.
- [ ] Template packs for different settings (empire, company, guild, nation).
- [ ] Repository hooks for validation or simulation before committing an epoch.
- [ ] Optional signed snapshots and append-only audit records.
- [ ] Deterministic seeded simulation and reproducible random generation.
- [ ] Plugin/scripting boundary after the storage compatibility contract settles.
## 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).
- [x] Add ephemeral UUID/name `EntityIndex` lookup and duplicate detection while
preserving ordered vectors as the stable repository representation (#6).
- [x] Make full entity, unified show, epoch show, and diff presentation return
buffered strings before the CLI writes them (tracker issue #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`
/ `epoch fsck` paths were replaced and covered by CLI tests.
- The former ignored `epoch switch --force` placeholder was removed; there is
no uncommitted/staged state for it to discard in the current format.
- Nerd Font rendering remains the default; portable text/Unicode rendering is
available through `--no-default-features` and passes its own test matrix.
- Name generation used to create `naming.json` in the working directory; this
was removed in favor of read-only embedded defaults.
- The binary now has eleven integration tests covering every exposed entity type,
timeline workflows, invalid input, and corrupted repositories.
- Phase 4 adds worktree/index state, entity and world staging, explicit restore,
manifest-last commits, parent-linked log/revert/switch, backed-up pruning,
writer locks, journals, and deterministic recovery.
- The binary integration workflows and format-1.0 library coverage
includes clean/dirty layers, commits, conflict refusal, time advancement,
include lock exclusion and interrupted-journal refusal.
- The separate read-only `efo-tui` binary browses status and all entity
collections with semantic labels, guarded terminal restoration, reload,
contextual help, compact-layout fallback, and three focused unit tests.
- After pre-release format consolidation, all 88 default-feature tests, 84
portable-output tests, strict Clippy, and both release builds passed on
2026-09-21.
- The worldgen foundation raised coverage to 93 default-feature tests and 89
portable-output tests; strict Clippy and both release builds still pass.
- Local source material under `ressources/` is ignored; the curated Draän
example remains tracked and carries a warning about its provisional reserved
setting/map rights.
- The milestone-only `rust_autobadges` run was attempted, but this installed
version misreported passing tests as failing and coverage as unavailable.
Its false generated badges were discarded; the prior badges were preserved.
- [x] Add focused `EpochInfo` collection, lookup, link, replacement, and
position tests; document and provide a runnable `lib_efo` repository example.
- [x] Configure Tarpaulin around its subprocess-attribution limitation and
refresh `rust_autobadges` at a directly measured coverage level above 70%.
## TUI release-readiness pass
- [x] Add searchable, sorted entity lists and HEAD/index/worktree browsing.
- [x] Improve detail rendering, bounded scrolling, paging, and compact layouts.
- [x] Preserve selection on reload and expose full reload diagnostics.
- [x] Harden terminal lifecycle, Ctrl-C, non-terminal startup, and no-colour output.
- [x] Add rendering, navigation, failure, and binary workflow coverage; update docs.
- Decision: this pass matures the read-only browser; interactive writes retain
the preview/recovery design requirements in `docs/tui-design.md`.
- Fixed multiline JSON details, stale reload selection, help clipping, blank
overscroll, and list-window jumps when navigating upward.
- The browser uses Ratatui's locked rendered-line measurement feature for exact
wrapped scroll bounds. Persisted repository data is unchanged.
- Validation: 109 all-feature tests and 105 portable tests, formatting, strict
Clippy, both release builds, and Unix PTY navigation/resize/restoration checks.
TUI coverage includes nine state/render tests and three binary startup tests.
- Release boundary: write workflows and history comparison stay in the CLI;
cross-terminal visual review remains useful before publishing a final release.
## TUI formatted details
- [x] Default entity/event details to a readable, sectioned presentation.
- [x] Toggle formatted/raw JSON with `v`, preserving selection and resetting scroll.
- [x] Cover modal keys and both representations; update help and docs and run gates.
- Decision: format serialized fields in the TUI so nested/future metadata stays
visible without changing domain types or persistence.
- Validation: 112 all-feature tests and 108 portable tests, formatting, strict
Clippy, both release builds, and the PTY smoke check passed.
## TUI entity authoring
- [x] Add forms for all six entity collections, validation, save previews, and draft cancellation.
- [x] Save only the worktree through library transactions with locked stale-state checks.
- [x] Add previewed one-step undo preserving the exact prior entity, including unstaged edits.
- [x] Cover creation/edit/undo, lock/conflict/failure paths, modal input and terminal workflows.
- [x] Update browser-only scope and help; pass quality gates and commit.
- Decision: this request authorizes TUI entity writes. HEAD/index remain read-only;
staging, commits, relationship editing, and general deletion remain CLI operations.
- Save checks hold the writer lock from fresh-state validation through the
journalled worktree write. Undo retains its own save-time snapshot so reload
cannot accidentally permit overwriting later edits. Entity order is preserved.
- Forms edit name, description, exact position, duration, effect, bounds, and
absolute statistics; relationship metadata and UUID/type remain intact.
- Undo is one step and session-local. Commit valuable work for durable recovery;
an index restore is intentionally documented as discarding all unstaged edits.
- Validation: 120 all-feature tests, 116 portable tests, formatting, strict
Clippy, default/portable release builds, and Unix PTY create/edit/preview/undo/
discard/multiline-paste/terminal-restoration checks passed.

78
AGENTS.md Normal file
View File

@ -0,0 +1,78 @@
# Epoch Forge contributor guide
Epoch Forge is a CLI-first, local world-state manager. Its primary product
qualities are, in order: safety and reversibility, ease of use, compatibility
with existing repositories, and pleasant terminal output. Do not add a GUI,
web service, or TUI unless a task explicitly changes that scope.
## Product vocabulary
- A **repository** is a directory initialised by `efo init`.
- An **epoch** is an immutable-in-spirit snapshot of world state. Commands may
edit the checked-out epoch, but every destructive workflow must have a clear
recovery path.
- An **entity** is a typed game object such as a character, town, event,
blocker, calamity, or (eventually) organisation.
- An **identifier** may be a human-readable name or the stable `@UUID` form.
- The CLI is `efo`; `lib_efo` owns the domain and persistence logic while
`bin_efo` owns argument parsing and presentation.
## Engineering rules
1. Preserve persisted data compatibility. If a format change is unavoidable,
add a version/migration plan and fixtures before changing it.
2. Mutating commands must either complete fully or leave the prior on-disk
state usable. Prefer write-to-temporary-then-rename where practical.
3. Destructive commands require an explicit, documented recovery path. Model
vocabulary after Git where it helps: `status`, `log`, `diff`, `switch`,
`restore`, and later `stage`/`commit`.
4. Errors must say what failed, identify the relevant object/path, and suggest
the next useful command when one exists. Do not panic for user input or
repository corruption.
5. `efo --help` and every subcommand's `--help` are user documentation. Include
meaningful summaries, argument value hints, and examples where Clap allows.
6. Human output should be compact, aligned, Unicode-aware, and colour only when
appropriate for the terminal. Machine-readable output must remain plain and
stable. Never require a Nerd Font to understand essential output.
7. Keep domain operations in `lib_efo`; CLI handlers should parse, invoke, and
render. Avoid `unsafe`, unchecked `unwrap`, and hidden working-directory
mutations.
8. Custom organisation/entity fields are a planned compatibility direction.
Avoid closed designs that prevent adding schema-less metadata later.
## Quality gates
Run before each implementation commit:
```text
cargo fmt --all -- --check
cargo test --workspace --all-targets --all-features --locked
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
```
Add tests at the lowest useful layer and CLI integration tests for observable
workflows. Tests that touch a repository must use a temporary directory and
must not depend on execution order. Snapshot tests are appropriate for stable
human output; assertions on structured data are preferred for persistence.
Tarpaulin and `rust_autobadges` are release-time tools. Do not run them in CI or
for routine commits. Refresh their badges only for a significant release.
## Documentation and commits
- Keep the README short: purpose, honest capability summary, quick start,
safety model, and links into `docs/`.
- Keep commands, repository format, architecture, and roadmap in focused,
cross-linked files under `docs/`.
- Update documentation in the same commit as user-visible behavior.
- Maintain `AGENTS-TASKS.md`: mark completed items, add discoveries, and record
decisions that affect later work.
- Commit small coherent changes regularly. Use conventional subjects such as
`docs:`, `test:`, `fix:`, `feat:`, and `refactor:`. Never mix an unrelated
cleanup with a behavior change.
## Definition of done
A task is done when behavior is implemented, failure modes are covered, the
full quality gates pass, CLI help and relevant docs agree with reality, and the
change is committed with `AGENTS-TASKS.md` updated.

616
Cargo.lock generated
View File

@ -26,6 +26,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "anstream"
version = "0.6.21"
@ -76,6 +82,21 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "approx"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
dependencies = [
"num-traits",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "backtrace"
version = "0.3.76"
@ -102,9 +123,9 @@ dependencies = [
[[package]]
name = "bitflags"
version = "2.10.0"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bumpalo"
@ -112,6 +133,21 @@ version = "3.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
[[package]]
name = "by_address"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
[[package]]
name = "castaway"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
dependencies = [
"rustversion",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
@ -149,7 +185,7 @@ dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
]
[[package]]
@ -178,7 +214,7 @@ checksum = "9f7c1b60bae2c3d45228dfb096046aa51ef6c300de70b658d7a13fcb0c4f832e"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
]
[[package]]
@ -196,6 +232,20 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "compact_str"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"
dependencies = [
"castaway",
"cfg-if",
"itoa",
"rustversion",
"ryu",
"static_assertions",
]
[[package]]
name = "console"
version = "0.15.11"
@ -217,6 +267,33 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "crossterm"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
dependencies = [
"bitflags",
"crossterm_winapi",
"derive_more",
"document-features",
"mio",
"parking_lot",
"rustix",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
dependencies = [
"winapi",
]
[[package]]
name = "csv"
version = "1.4.0"
@ -238,6 +315,46 @@ dependencies = [
"memchr",
]
[[package]]
name = "darling"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 3.0.6",
]
[[package]]
name = "darling_macro"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
dependencies = [
"darling_core",
"quote",
"syn 3.0.6",
]
[[package]]
name = "deranged"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
[[package]]
name = "derive_more"
version = "2.1.0"
@ -257,10 +374,19 @@ dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"syn",
"syn 2.0.111",
"unicode-xid",
]
[[package]]
name = "document-features"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
dependencies = [
"litrs",
]
[[package]]
name = "efo"
version = "0.1.0"
@ -269,16 +395,36 @@ dependencies = [
"colored",
"derive_more",
"env_logger",
"insta",
"lib_efo",
"log",
"miette",
"rand",
"serde",
"serde_json",
"thiserror",
"uuid",
]
[[package]]
name = "efo-tui"
version = "0.1.0"
dependencies = [
"clap",
"crossterm",
"lib_efo",
"ratatui",
"serde_json",
"tempfile",
"thiserror",
"uuid",
]
[[package]]
name = "either"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
[[package]]
name = "encode_unicode"
version = "1.0.0"
@ -308,6 +454,12 @@ dependencies = [
"log",
]
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.14"
@ -324,6 +476,12 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "getrandom"
version = "0.3.4"
@ -342,12 +500,49 @@ version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indoc"
version = "2.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
dependencies = [
"rustversion",
]
[[package]]
name = "insta"
version = "1.44.3"
@ -359,6 +554,19 @@ dependencies = [
"similar",
]
[[package]]
name = "instability"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf84e73fa6f27f299dec58e13223cf70db80da872eb921d4f6138342a0eabc8"
dependencies = [
"darling",
"indoc",
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "is_ci"
version = "1.2.0"
@ -371,6 +579,15 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.15"
@ -398,7 +615,7 @@ checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
]
[[package]]
@ -411,6 +628,17 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "kasuari"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899"
dependencies = [
"hashbrown 0.16.1",
"portable-atomic",
"thiserror",
]
[[package]]
name = "lib_efo"
version = "0.1.0"
@ -419,7 +647,6 @@ dependencies = [
"cli-table",
"colored",
"derive_more",
"env_logger",
"insta",
"log",
"miette",
@ -434,9 +661,24 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.178"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "line-clipping"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e"
dependencies = [
"bitflags",
]
[[package]]
name = "linux-raw-sys"
@ -444,12 +686,36 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
[[package]]
name = "litrs"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lru"
version = "0.18.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff9840bcc50b71349309900da0ce7279aa336ae71d73250b07998932c7d97c25"
dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "memchr"
version = "2.7.6"
@ -483,7 +749,7 @@ checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
]
[[package]]
@ -495,6 +761,42 @@ dependencies = [
"adler2",
]
[[package]]
name = "mio"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.61.2",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "num_threads"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"
dependencies = [
"libc",
]
[[package]]
name = "object"
version = "0.37.3"
@ -523,10 +825,66 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52"
[[package]]
name = "portable-atomic"
version = "1.11.1"
name = "palette"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64"
dependencies = [
"approx",
"libm",
"palette_derive",
"palette_math",
]
[[package]]
name = "palette_derive"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be"
dependencies = [
"by_address",
"proc-macro2",
"quote",
"syn 2.0.111",
]
[[package]]
name = "palette_math"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12"
dependencies = [
"libm",
]
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "portable-atomic"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
[[package]]
name = "portable-atomic-util"
@ -537,6 +895,12 @@ dependencies = [
"portable-atomic",
]
[[package]]
name = "powerfmt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@ -599,6 +963,81 @@ dependencies = [
"getrandom",
]
[[package]]
name = "ratatui"
version = "0.30.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d"
dependencies = [
"instability",
"ratatui-core",
"ratatui-crossterm",
"ratatui-widgets",
"serde",
]
[[package]]
name = "ratatui-core"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c"
dependencies = [
"bitflags",
"compact_str",
"hashbrown 0.17.1",
"itertools",
"kasuari",
"lru",
"palette",
"serde",
"strum",
"thiserror",
"unicode-segmentation",
"unicode-truncate",
"unicode-width 0.2.2",
]
[[package]]
name = "ratatui-crossterm"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0"
dependencies = [
"cfg-if",
"crossterm",
"instability",
"ratatui-core",
]
[[package]]
name = "ratatui-widgets"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1"
dependencies = [
"bitflags",
"hashbrown 0.17.1",
"indoc",
"instability",
"itertools",
"line-clipping",
"ratatui-core",
"serde",
"strum",
"time",
"unicode-segmentation",
"unicode-width 0.2.2",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "regex"
version = "1.12.2"
@ -668,6 +1107,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "semver"
version = "1.0.27"
@ -701,7 +1146,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
]
[[package]]
@ -717,18 +1162,82 @@ dependencies = [
"serde_core",
]
[[package]]
name = "signal-hook"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-mio"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "similar"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
[[package]]
name = "smallvec"
version = "1.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.111",
]
[[package]]
name = "supports-color"
version = "3.0.2"
@ -761,6 +1270,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.23.0"
@ -820,9 +1340,30 @@ checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
]
[[package]]
name = "time"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
dependencies = [
"deranged",
"libc",
"num-conv",
"num_threads",
"powerfmt",
"serde_core",
"time-core",
]
[[package]]
name = "time-core"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "unicode-ident"
version = "1.0.22"
@ -841,6 +1382,17 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
[[package]]
name = "unicode-truncate"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"
dependencies = [
"itertools",
"unicode-segmentation",
"unicode-width 0.2.2",
]
[[package]]
name = "unicode-width"
version = "0.1.14"
@ -877,6 +1429,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasip2"
version = "1.0.1+wasi-0.2.4"
@ -918,7 +1476,7 @@ dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
"wasm-bindgen-shared",
]
@ -931,6 +1489,22 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
@ -940,6 +1514,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
@ -1125,5 +1705,5 @@ checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.111",
]

View File

@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["bin_efo", "lib_efo"]
members = ["bin_efo", "lib_efo", "tui_efo"]
[workspace.dependencies]
serde = { version = "1.0.228", features = ["derive"] }
@ -14,3 +14,5 @@ derive_more = { version = "2.0.1", features = ["display", "add", "mul"] }
uuid = { version = "1.18.1", features = ["serde", "v4"] }
colored = "3.0.0"
insta = "1.44.3"
ratatui = { version = "0.30.2", default-features = false, features = ["crossterm"] }
crossterm = "0.29.0"

208
README.md
View File

@ -1,138 +1,138 @@
# 📦 Epoch Forge (`epoch_forge`) – *early alpha*
![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg)
# Epoch Forge
![📚 Online Documentation](https://books.dandaedre.com/rust_doc/efo/bin_efo/index.html)
![coverage](badges/coverage.svg) ![version](badges/version.svg) ![tests](badges/test.svg)
> **A Rust-powered CLI for managing fantasy organisations across time.**
> *Think of it as a living, breathing world-state engine that lets you “rewind”, “fast-forward”, and **alter** the history of guilds, towns, wars, and characters.*
Epoch Forge (`efo`) is an early-alpha command-line tool for managing a game's
world or organisation across a sequence of snapshots called **epochs**. It is
designed for people who are comfortable with Git-like concepts: inspect the
current state, advance it, compare it with history, and deliberately discard a
future timeline when needed.
> **Epoch Forge** is a Rust‑powered command‑line tool that lets you build and manipulate a living fantasy world.
> It is **in early alpha** – the API is subject to change, some features are missing, and stability is **not guaranteed**.
The current release manages organisations, characters, towns, events,
calamities, and blockers with statistics and relationships. Repository format
1.0 provides worktree/index staging, immutable commits, restore, conflict-safe
revert, switching, and recoverable future pruning from initialisation. A separate
TUI searches entities across HEAD, staged, and working state, and offers
previewed entity creation/editing with one-step undo. Custom fields and TUI
staging/commit workflows remain planned. There is no GUI or web interface.
> **Stats & analytics are not yet implemented** – most commands operate only on the raw data model.
> Epoch Forge is not yet suitable as the only copy of important campaign data.
> Keep the repository in Git or make a directory backup before destructive
> operations. See [Safety and recovery](docs/repository.md#safety-and-recovery).
## ✨ Quick start
## Install
The project currently requires Rust 1.92 or newer:
```bash
# Clone the repository
git clone https://proxy.dandaedre.com/gitea/idle-org/epoch_forge.git
cd epoch_forge
# Build & install the binary
cargo install --locked --path bin_efo
cargo install --locked --path tui_efo
```
# Initialise an empty world (epoch 0)
Nerd Font icons are enabled by default. Build a portable-Unicode variant for
terminals without a Nerd Font with:
```bash
cargo install --locked --path bin_efo --no-default-features
```
## Quick start
Start in an empty directory. Epoch Forge stores `.epoch` and `epoch/` in the
current working directory.
```bash
mkdir my-world
cd my-world
efo init
# Add an organisation
efo org add "The Iron Horde"
efo chr add "Aria" --stats strength:12 food:8
efo town add "Durn" --position 12,5
efo status
efo chr show Aria
# Add a town
efo town add "Durn" --stat pop:32
# Inspect the current world state
efo show > world.json
cat world.json
# Show the epoch timeline
efo epoch log
# Create the next scheduled epoch
# Snapshot the current state as the next epoch.
efo epoch summary "The expedition begins"
efo epoch tag beginning
efo epoch next
# Switch back to epoch 5 (if it exists)
efo epoch switch 5
# Tag the current epoch
efo epoch tag milestone1
# Add a short-lived event
efo event add "Storm" \
--duration Duration(1) \
--effect permanent-effect-to-apply \
--stats damage=20
# Compare an entity after editing it in epoch 1.
efo chr edit Aria --prestige-add 2
efo chr diff Aria --epoch-id beginning
efo epoch log
```
> **Tip:** The `show` command can print JSON, which you can pipe to `jq` or any other tooling.
Run `efo --help`, `efo <command> --help`, or see the
[command reference](docs/commands.md) for the complete current interface.
## 🏆 Project Highlights
## Capabilities
| Feature | Description | Where to find it |
|---------|-------------|-----------------|
| **Epoch management** | Switch, advance, or rewind the global timeline | `core::epoch` |
| **Persistence** | JSON/YAML stores, pluggable back-ends | `core::epoch` |
| **Event handling** | Add/remove world-shaping events (storms, festivals, wars) | `core::entities` |
| **Organisation CRUD** | Guilds, factions, corporations | `core::entities` |
| **Character CRUD** | Heroes, villains, NPCs | `core::entities` |
| **Town CRUD** | Villages, cities, trade hubs | `core::entities` |
| **Link network** | Alliances, wars, roads, trade routes | `core::link` |
| **CLI** | `efo` binary with sub-commands | `efo` crate |
| Area | Available now | Not available yet |
|---|---|---|
| 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; 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) |
> *Statistics, analytics, and the `act` feature are still a work in progress.*
`efo show all` gives a world overview; per-type commands such as
`efo chr show Aria` provide targeted or detailed inspection.
## Unimplemented / WIP
Run `efo-tui` in a repository root (or use `--repository PATH`). Press `/` to
search, `1`/`2`/`3` to browse HEAD/index/worktree, and `v` to toggle formatted
details and raw JSON. Use `a` to add to the current collection, `e` to edit,
`Ctrl-S` to preview, and `y` to save to the worktree. Press `u` to preview undo
of the last TUI save. Narrow terminals show one
focused panel; Tab cycles panels. Use `--no-color` for monochrome output and
`?` for the scrollable keyboard reference. No Nerd Font is required.
| Feature | Status | Where it lives |
|---------|--------|----------------|
| **Act** | Planned, not yet implemented | `core::act` |
| **Stats** | Missing – no aggregated data | – |
## Documentation
## Quick reference table
- [Documentation index](docs/README.md)
- [Commands](docs/commands.md)
- [Repository, persistence, and recovery](docs/repository.md)
- [Reversing changes](docs/recovery.md)
- [Architecture and development](docs/architecture.md)
- [TUI scope and keyboard guide](docs/tui-design.md)
- [Roadmap and proposed stretch goals](docs/roadmap.md)
- [Ready-to-use Draän example world](examples/ravenous-draan/README.md)
- [Contributor/agent rules](AGENTS.md) and [working task list](AGENTS-TASKS.md)
| Sub‑command | Usage example | What it changes |
|-------------|---------------|-----------------|
| **`init`** | `efo init`<br>`efo init --force` | Creates an empty epoch repository (epoch 0) in the current directory. |
| **`epoch log`** | `efo epoch log --limit 20` | Prints a chronological list of epochs up to the current one. |
| **`epoch switch`** | `efo epoch switch 5` | Sets the current epoch to the specified `<id>` (must already exist). |
| **`epoch next`** | `efo epoch next` | Generates the next scheduled epoch and inserts it. |
| **`epoch reset`** | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. |
| **`epoch diff`** | `efo epoch diff 2 4` | *Unimplemented* – placeholder for future diffing logic. |
| **`epoch tag`** | `efo epoch tag milestone1` | Adds a unique tag to the current epoch, updating the global tag map. |
| **`epoch fsck`** | `efo epoch fsck` | *Unimplemented* – intended to run a consistency check. |
| **`epoch summary`** | `efo epoch summary "Reached the new frontier"` | Replaces the `summary` field of the current epoch with `<text>`. |
| **`show`** | `efo show` | Prints the current world state (JSON). |
| **`gen`** | `efo gen character -n 5 --short`<br>`efo gen town -n 2`<br>`efo gen event -n 3 --name` | Prints generated names/ideas; useful for scripting. |
| **`chr add`** | `efo chr add "Aria" --pos 5,12 --stats strength=12 agility=9` | Creates a new entity (character, town, event, etc.) and writes the epoch. |
| **`chr del`** | `efo chr del "Aria"` | Removes the matching entity from the epoch. |
| **`chr edit`** | `efo chr edit "Storm" --duration Duration(2)` | Modifies an existing entity’s stats, position, duration, etc. |
| **`chr find`** | `efo chr find "Aria"` | Prints full details of a single entity. |
| **`chr show`** | `efo chr show` | Lists all entities, or `efo chr show "Aria"` shows one in full detail. |
| **`chr diff`** | `efo chr diff "Aria"` | Prints the difference between the current and previous epoch for that entity. |
| **`event add` / `event remove`** | `efo event add ...`<br>`efo event remove ...` | Adds or removes an event. |
| **`org add` / `org remove`** | `efo org add ...`<br>`efo org remove ...` | Manages organisations (guilds, factions). |
| **`town add` / `town remove`** | `efo town add ...`<br>`efo town remove ...` | CRUD for towns. |
| **`monster add` / `monster remove`** | `efo monster add ...`<br>`efo monster remove ...` | CRUD for monsters. |
| **`act`** | *Not yet implemented* | Planned for future action handling. |
## Development
> All changes are persisted immediately to the epoch file after the command finishes.
### Library example
## Contributions & Feedback
Because the project is in early alpha, any feedback, bug reports, or pull requests are welcome.
Please remember that **stability is not guaranteed**, so use it in a versionned environnement.
Happy forging! ✨
## Binary releases
The CLI package is `efo`, in the `bin_efo` workspace member. Release tags follow
its Cargo version (for example, `v0.1.0`). The publisher is invoked from its own
checkout with:
`lib_efo` exposes repository initialization and the complete HEAD/index/worktree
model without going through the CLI. To create a repository in an existing
empty directory and inspect its initial epoch:
```bash
./release.sh /path/to/epoch_forge --package efo --tag v0.1.0
mkdir /tmp/epoch-forge-example
cargo run -p lib_efo --example repository -- /tmp/epoch-forge-example
```
The workspace lockfile is tracked. `Cross.toml` selects the tested cross images
for x86-64 musl Linux, AArch64 musl Linux, and x86-64 GNU Windows. The build scripts
work with rustc alone inside cross containers; rustup is not required there.
Release archives use `efo-{target}-v{version}.tgz` and contain the matching root
directory with `efo` (or `efo.exe`). `SHA256SUMS` accompanies the archives. The
selected package manifest carries cargo-binstall metadata for the Gitea URLs.
After the matching release has been published, install from the local manifest:
See [`lib_efo/examples/repository.rs`](lib_efo/examples/repository.rs) for the
complete program. Mutations should use `Workspace` methods so they retain the
same transactional guarantees as `efo`.
```bash
cargo binstall efo --manifest-path bin_efo/Cargo.toml
cargo fmt --all -- --check
cargo test --workspace --all-targets --all-features --locked
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
```
Tarpaulin and `rust_autobadges` are intentionally release-only. They do not run
in routine CI because of their cost; badge files are refreshed for significant
releases. The Tarpaulin configuration excludes the thin CLI adapters because
their subprocess integration tests cannot be attributed reliably by its ptrace
backend; library and TUI code remain directly measured.
## Release archives
The CLI package is `efo` in `bin_efo`. Release tags follow the Cargo version
(for example `v0.1.0`). Cross-built archives are named
`efo-{target}-v{version}.tgz` and are accompanied by `SHA256SUMS`.
Epoch Forge is licensed under the terms in [LICENSE](LICENSE).

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 49%"><title>test-coverage: 49%</title><linearGradient id="bms-8b2d5b6821598c64" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-8b2d5b6821598c64"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-8b2d5b6821598c64)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#97ca00"/><rect width="122" height="18" fill="url(#bms-8b2d5b6821598c64)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">49%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">49%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 78%"><title>test-coverage: 78%</title><linearGradient id="bms-45525ec477e25d94" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-45525ec477e25d94"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-45525ec477e25d94)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#97ca00"/><rect width="122" height="18" fill="url(#bms-45525ec477e25d94)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">78%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">78%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -4,12 +4,16 @@ version = "0.1.0"
edition = "2024"
repository = "https://proxy.dandaedre.com/gitea/idle-org/epoch_forge"
[features]
default = ["nerd-fonts"]
nerd-fonts = ["lib_efo/nerd-fonts"]
[package.metadata.binstall]
pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ target }-v{ version }.tgz"
pkg-fmt = "tgz"
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
[dependencies]
lib_efo = { path = "../lib_efo" }
lib_efo = { path = "../lib_efo", default-features = false }
serde = {workspace = true}
clap = {workspace = true}
thiserror = {workspace = true}
@ -20,6 +24,4 @@ log = {workspace = true}
derive_more = {workspace = true}
colored = {workspace = true}
uuid = {workspace = true}
[dev-dependencies]
insta = {workspace = true}
rand = "0.9.2"

View File

@ -8,12 +8,19 @@
#![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;
pub mod generate;
pub mod history;
pub mod init;
pub mod safety;
// pub mod roll;
pub mod show;
pub mod state;
pub mod status;
pub mod travel;
// pub mod diff;
// pub mod utils;

View File

@ -0,0 +1,290 @@
//! Record and apply player-rolled, game-master-authored resolutions.
use std::{path::Path, str::FromStr};
use clap::{Args, Subcommand};
use lib_efo::{
adjudication::{
AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec,
ChosenEffect, StatName, apply_to_world, preview_at_potency,
},
entity::EntityIdentifier,
stats::EntityType,
workspace::Workspace,
};
use crate::error::AppError;
/// Adjudication operations (also available as `influx`).
#[derive(Debug, Subcommand)]
pub enum AdjudicateCmd {
/// Preview a ruling without changing the worktree.
Preview(AdjudicateArgs),
/// Apply a ruling and record it in the worktree.
Apply(AdjudicateArgs),
/// List recorded rulings, optionally restricted to one event.
List(AdjudicateListArgs),
}
/// One external roll and the game master's explicit ruling.
#[derive(Debug, Args)]
#[command(
after_long_help = "EXAMPLES:\n efo adjudicate preview Plague --target town:Haven --level bad --result 'd20=4' --disposition dampened --effect health:-8\n efo influx apply Plague --target character:Aria --level good --result '2d6=11' --disposition applied --effect happiness:3"
)]
pub struct AdjudicateArgs {
/// Source event name/prefix or @UUID.
source: EntityIdentifier,
/// Target as KIND:IDENTIFIER (character, town, org, calamity, blocker, or event).
#[arg(long, value_name = "KIND:IDENTIFIER")]
target: String,
/// Game-master interpretation of the external result.
#[arg(long, value_enum)]
level: AdjudicationLevel,
/// External result retained verbatim (Epoch Forge never rolls it).
#[arg(long, default_value = "not recorded")]
result: String,
/// How the game master says the source affects this target.
#[arg(long, value_enum, default_value = "applied")]
disposition: AdjudicationDisposition,
/// Explicit STAT:DELTA chosen by the game master; repeat for multiple stats.
#[arg(long, value_name = "STAT:DELTA")]
effect: Vec<String>,
/// Optional explanation retained in the audit record.
#[arg(long, default_value = "")]
note: String,
/// Complete replacement policy JSON.
#[arg(long)]
config: Option<std::path::PathBuf>,
}
/// Filters for recorded adjudications.
#[derive(Debug, Args)]
pub struct AdjudicateListArgs {
/// Event name/prefix or @UUID. Omit to show all records.
source: Option<EntityIdentifier>,
}
/// Dispatch an adjudication operation.
pub fn handle(command: &AdjudicateCmd) -> Result<(), AppError> {
match command {
AdjudicateCmd::Preview(args) => resolve(args, false),
AdjudicateCmd::Apply(args) => resolve(args, true),
AdjudicateCmd::List(args) => list(args),
}
}
/// Preview and optionally persist one ruling.
fn resolve(args: &AdjudicateArgs, apply: bool) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let config = match &args.config {
Some(path) => AdjudicationConfig::load(path)?,
None => AdjudicationConfig::embedded()?,
};
let source = workspace
.worktree
.world
.find_entity_of_type(&Some(args.source.clone()), &EntityType::Event)?
.id;
let (target_type, target_identifier) = parse_target(&args.target)?;
let target = workspace
.worktree
.world
.find_entity_of_type(&Some(target_identifier), &target_type)?;
let spec = AdjudicationSpec {
level: args.level,
disposition: args.disposition,
source,
external_result: args.result.clone(),
note: args.note.clone(),
effects: args
.effect
.iter()
.map(|raw| parse_effect(raw))
.collect::<Result<_, _>>()?,
policy_id: config.policy_id.clone(),
};
let source_potency = workspace
.worktree
.world
.event_adjudications
.get(&source)
.map_or(10_000, |state| state.potency_basis_points);
let report = preview_at_potency(&config, &spec, target, 0, source_potency)?;
let mut output = format!(
"Adjudication preview · {} · {} · {}\n├─ External result: {}\n├─ Target: {} (@{})\n",
level_label(report.level),
disposition_label(report.disposition),
target_type_label(target_type),
report.external_result,
target.name,
target.id
);
if report.changes.is_empty() {
output.push_str("├─ Effects: none\n");
} else {
if report.effects_were_defaulted {
output.push_str("├─ Effects (policy defaults)\n");
} else {
output.push_str("├─ Effects (game-master supplied)\n");
}
for change in &report.changes {
output.push_str(&format!(
"│ • {:?}: {} → {} ({:+})\n",
change.stat, change.before, change.after, change.applied_delta
));
}
}
output.push_str(&format!("└─ Record: @{}\n", report.id));
output.push_str(&format!(
" Source potency: {}% → {}%{}\n",
report.source_potency_before / 100,
report.source_potency_after / 100,
if report.disposition == AdjudicationDisposition::Destroyed {
" (destroyed)"
} else {
""
}
));
if !apply {
output.push_str("Nothing changed. Use `efo adjudicate apply …` to update the worktree.\n");
print!("{output}");
return Ok(());
}
workspace.worktree.world =
apply_to_world(&workspace.worktree.world, &config, &report, target_type)?;
workspace.save_worktree("apply adjudication")?;
output.push_str("✓ Ruling recorded in the worktree. Undo: efo restore --worktree --all\n");
print!("{output}");
Ok(())
}
/// List audit records in stable key order.
fn list(args: &AdjudicateListArgs) -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
let source = args
.source
.as_ref()
.map(|identifier| {
workspace
.worktree
.world
.find_entity_of_type(&Some(identifier.clone()), &EntityType::Event)
.map(|entity| entity.id)
})
.transpose()?;
let records = workspace
.worktree
.world
.adjudications
.values()
.filter(|record| source.is_none_or(|id| record.source == id))
.collect::<Vec<_>>();
let mut output = format!("Adjudications · {} record(s)\n", records.len());
if let Some(source) = source
&& let Some(state) = workspace.worktree.world.event_adjudications.get(&source)
{
output.push_str(&format!(
"Source event · potency {}%{} · last @{}\n",
state.potency_basis_points / 100,
if state.destroyed { " · destroyed" } else { "" },
state.last_record
));
}
for record in records {
output.push_str(&format!(
"• @{} · event @{} → @{} · {} · {} · {}\n",
record.id,
record.source,
record.target,
level_label(record.level),
disposition_label(record.disposition),
record.external_result
));
}
print!("{output}");
Ok(())
}
/// Parse `kind:identifier` without making colons illegal in entity names.
fn parse_target(raw: &str) -> Result<(EntityType, EntityIdentifier), AppError> {
let (kind, identifier) = raw.split_once(':').ok_or_else(|| {
lib_efo::adjudication::AdjudicationError::Invalid(
"target must use KIND:IDENTIFIER, for example town:Haven".into(),
)
})?;
if identifier.is_empty() {
return Err(lib_efo::adjudication::AdjudicationError::Invalid(
"target identifier cannot be empty".into(),
)
.into());
}
let kind = match kind.to_ascii_lowercase().as_str() {
"character" | "chr" => EntityType::Character,
"town" => EntityType::Town,
"org" | "organization" | "organisation" => EntityType::Organization,
"calamity" => EntityType::Calamity,
"blocker" => EntityType::Blocker,
"event" => EntityType::Event,
_ => return Err(lib_efo::adjudication::AdjudicationError::Invalid(format!(
"unknown target kind `{kind}`; use character, town, org, calamity, blocker, or event"
))
.into()),
};
let identifier = if let Some(id) = identifier.strip_prefix('@') {
EntityIdentifier::Id(id.into())
} else {
EntityIdentifier::Name(identifier.into())
};
Ok((kind, identifier))
}
/// Parse one explicit effect.
pub(crate) fn parse_effect(raw: &str) -> Result<ChosenEffect, AppError> {
let (stat, delta) = raw.split_once(':').ok_or_else(|| {
lib_efo::adjudication::AdjudicationError::Invalid(format!(
"effect `{raw}` must use STAT:DELTA, for example health:-8"
))
})?;
let delta = isize::from_str(delta).map_err(|_| {
lib_efo::adjudication::AdjudicationError::Invalid(format!(
"effect `{raw}` has an invalid signed integer delta"
))
})?;
Ok(ChosenEffect {
stat: StatName::from_str(stat)?,
delta,
})
}
/// Stable lowercase label for a master-assigned level.
fn level_label(level: AdjudicationLevel) -> &'static str {
match level {
AdjudicationLevel::Excellent => "excellent",
AdjudicationLevel::Good => "good",
AdjudicationLevel::Mid => "mid",
AdjudicationLevel::Bad => "bad",
AdjudicationLevel::Worsen => "worsen",
AdjudicationLevel::Apocalypse => "apocalypse",
}
}
/// Stable lowercase label for a target disposition.
fn disposition_label(value: AdjudicationDisposition) -> &'static str {
match value {
AdjudicationDisposition::Applied => "applied",
AdjudicationDisposition::Dampened => "dampened",
AdjudicationDisposition::Avoided => "avoided",
AdjudicationDisposition::Destroyed => "destroyed",
}
}
/// Human-readable target-kind label.
fn target_type_label(value: EntityType) -> &'static str {
match value {
EntityType::Character => "character",
EntityType::Town => "town",
EntityType::Organization => "organisation",
EntityType::Calamity => "calamity",
EntityType::Blocker => "blocker",
EntityType::Event => "event",
EntityType::Player => "player",
}
}

View File

@ -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}"),
}
}

View File

@ -0,0 +1,365 @@
//! Preview-first spatial event diffusion.
use std::path::Path;
use clap::{Args, Subcommand, ValueEnum};
use lib_efo::{
adjudication::{
AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec,
apply_to_world, preview_at_potency,
},
entity::EntityIdentifier,
simulation::{MobilityState, begin_diffusion, plan_diffusion, tick_diffusion},
stats::EntityType,
workspace::Workspace,
};
use crate::{commands::adjudicate::parse_effect, error::AppError};
/// Event diffusion operations.
#[derive(Debug, Subcommand)]
pub enum DiffuseCmd {
/// Preview or start spatial propagation for an event.
Start(DiffuseStartArgs),
/// Preview or advance every active event frontier.
Tick(DiffuseTickArgs),
/// Resolve one pending town arrival and its selected characters.
Resolve(DiffuseResolveArgs),
}
/// Which characters share a town arrival resolution.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum CharacterPolicy {
/// Do not target characters.
None,
/// Target characters whose mobility state makes them town residents.
Residents,
/// Target non-travelling characters at the town's exact position.
Positioned,
/// Combine resident and positioned characters.
Both,
}
/// Game-master ruling for one pending arrival.
#[derive(Debug, Args)]
#[command(
after_long_help = "EXAMPLE:\n efo diffuse resolve Plague Haven --level good --characters both\n efo diffuse resolve Plague Haven --level bad --disposition dampened --effect health:-8 --apply"
)]
pub struct DiffuseResolveArgs {
/// Source event name/prefix or @UUID.
event: EntityIdentifier,
/// Pending town name/prefix or @UUID.
town: EntityIdentifier,
/// Game-master interpretation of the external roll.
#[arg(long, value_enum)]
level: AdjudicationLevel,
/// External result retained verbatim.
#[arg(long, default_value = "not recorded")]
result: String,
/// Applied, dampened, avoided, or destroyed.
#[arg(long, value_enum, default_value = "applied")]
disposition: AdjudicationDisposition,
/// Explicit STAT:DELTA; omit to use progressive policy defaults.
#[arg(long, value_name = "STAT:DELTA")]
effect: Vec<String>,
/// Optional game-master explanation.
#[arg(long, default_value = "")]
note: String,
/// Characters included in the same ruling. Travellers are always excluded.
#[arg(long, value_enum, default_value = "residents")]
characters: CharacterPolicy,
/// Complete replacement adjudication policy JSON.
#[arg(long)]
config: Option<std::path::PathBuf>,
/// Apply effects and record the resolution; preview is the default.
#[arg(long)]
apply: bool,
}
/// New diffusion configuration.
#[derive(Debug, Args)]
#[command(
after_long_help = "EXAMPLES:\n efo diffuse start Plague\n efo diffuse start Plague --road-speed 120 --direct-speed 25 --expires-after 20 --apply"
)]
pub struct DiffuseStartArgs {
/// Event name/prefix or @UUID.
event: EntityIdentifier,
/// Additional percentage applied to each road's speed.
#[arg(long, default_value_t = 100)]
road_speed: u32,
/// Off-road propagation speed percentage.
#[arg(long, default_value_t = 25)]
direct_speed: u32,
/// Stop propagation at this relative tick.
#[arg(long)]
expires_after: Option<u64>,
/// Store the frontier in the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Diffusion tick options.
#[derive(Debug, Args)]
pub struct DiffuseTickArgs {
/// Number of ticks to advance.
#[arg(default_value_t = 1)]
amount: u64,
/// Update the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Dispatch one diffusion operation.
pub fn handle(command: &DiffuseCmd) -> Result<(), AppError> {
match command {
DiffuseCmd::Start(args) => start(args),
DiffuseCmd::Tick(args) => tick(args),
DiffuseCmd::Resolve(args) => resolve(args),
}
}
/// Preview and optionally apply one pending arrival as a single transaction.
fn resolve(args: &DiffuseResolveArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let event = workspace
.worktree
.world
.find_entity_of_type(&Some(args.event.clone()), &EntityType::Event)?
.id;
let town = workspace
.worktree
.world
.find_entity_of_type(&Some(args.town.clone()), &EntityType::Town)?
.clone();
let diffusion = workspace
.worktree
.world
.diffusions
.get(&event)
.ok_or_else(|| {
lib_efo::adjudication::AdjudicationError::Invalid(format!(
"event @{} has no active diffusion; run `efo diffuse start … --apply` first",
event
))
})?;
if !diffusion.pending.contains(&town.id) {
return Err(lib_efo::adjudication::AdjudicationError::Invalid(format!(
"{} is not awaiting resolution for this event; advance with `efo diffuse tick … --apply`",
town.name
)).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 spec = AdjudicationSpec {
level: args.level,
disposition: args.disposition,
source: event,
external_result: args.result.clone(),
note: args.note.clone(),
effects,
policy_id: config.policy_id.clone(),
};
let potency = workspace
.worktree
.world
.event_adjudications
.get(&event)
.map_or(10_000, |state| state.potency_basis_points);
let mut targets = vec![(EntityType::Town, town.id, town.name.clone())];
for character in selected_characters(&workspace.worktree.world, &town, args.characters) {
targets.push((EntityType::Character, character.id, character.name.clone()));
}
targets[1..].sort_unstable_by_key(|target| target.1);
let blockers = workspace
.worktree
.world
.blockers
.iter()
.filter(|blocker| {
blocker.position() == town.position()
|| blocker.links().iter().any(|link| link.other_id == town.id)
|| town.links().iter().any(|link| link.other_id == blocker.id)
})
.map(|blocker| blocker.name.as_str())
.collect::<Vec<_>>();
let mut reports = Vec::new();
let mut output = format!(
"Arrival resolution preview · {} → {}\n",
workspace
.worktree
.world
.find_entity_strict(event, Some(EntityType::Event))?
.name,
town.name
);
output.push_str(&format!("├─ Source potency: {}%\n", potency / 100));
if blockers.is_empty() {
output.push_str("├─ Protection context: none\n");
} else {
output.push_str(&format!("├─ Protection context: {}\n", blockers.join(", ")));
}
output.push_str(&format!(
"├─ Targets: {} (travellers excluded)\n",
targets.len()
));
for (kind, id, name) in &targets {
let target = workspace
.worktree
.world
.find_entity_strict(*id, Some(*kind))?;
let report = preview_at_potency(&config, &spec, target, diffusion.elapsed_ticks, potency)?;
output.push_str(&format!("│ • {name} ({kind:?})"));
if report.changes.is_empty() {
output.push_str(" · no stat changes\n");
} else {
for change in &report.changes {
output.push_str(&format!(
" · {:?} {} → {}",
change.stat, change.before, change.after
));
}
output.push('\n');
}
reports.push((*kind, report));
}
output.push_str(&format!("└─ Disposition: {:?}\n", args.disposition));
if !args.apply {
output.push_str("Nothing changed. Re-run with `--apply` to resolve this arrival.\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)?;
}
let state = updated.diffusions.get_mut(&event).ok_or_else(|| {
lib_efo::adjudication::AdjudicationError::Invalid(
"diffusion disappeared during resolution".into(),
)
})?;
state.pending.remove(&town.id);
for (_, report) in &reports {
state.resolved.insert(report.target, report.id);
}
workspace.worktree.world = updated;
workspace.save_worktree("resolve diffusion arrival")?;
output.push_str("✓ Arrival resolved in the worktree. Undo: efo restore --worktree --all\n");
print!("{output}");
Ok(())
}
/// Select stable character targets; in-transit characters are conservative exclusions.
fn selected_characters<'a>(
world: &'a lib_efo::epoch::EpochInfo,
town: &lib_efo::entity::Entity,
policy: CharacterPolicy,
) -> Vec<&'a lib_efo::entity::Entity> {
if matches!(policy, CharacterPolicy::None) {
return Vec::new();
}
world
.characters
.iter()
.filter(|character| match world.mobility.get(&character.id) {
Some(MobilityState::Travelling { .. }) => false,
Some(MobilityState::Resident { place }) => {
matches!(policy, CharacterPolicy::Residents | CharacterPolicy::Both)
&& *place == town.id
}
Some(MobilityState::Roaming { position }) => {
matches!(policy, CharacterPolicy::Positioned | CharacterPolicy::Both)
&& position == town.position()
}
None => {
matches!(policy, CharacterPolicy::Positioned | CharacterPolicy::Both)
&& character.position() == town.position()
}
})
.collect()
}
/// Render and optionally persist a new frontier.
fn start(args: &DiffuseStartArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let event = workspace
.worktree
.world
.find_entity_of_type(&Some(args.event.clone()), &EntityType::Event)?
.id;
let state = plan_diffusion(
&workspace.worktree.world,
event,
args.road_speed,
args.direct_speed,
args.expires_after,
)?;
println!(
"Diffusion preview · {} destination(s)",
state.frontier.len()
);
let potency = workspace
.worktree
.world
.event_adjudications
.get(&event)
.map_or(10_000, |state| state.potency_basis_points);
println!(" Source potency · {}%", potency / 100);
for target in &state.frontier {
let town = workspace
.worktree
.world
.towns
.iter()
.find(|town| town.id == target.town)
.map_or("unknown", |town| town.name.as_str());
let reason = if target.route.is_empty() {
"direct"
} else {
"road"
};
println!(" • tick {:>4} · {town} · {reason}", target.arrival_tick);
}
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
begin_diffusion(&mut workspace.worktree.world, event, state);
workspace.save_worktree("begin event diffusion")?;
println!("✓ Diffusion stored in the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally apply frontier progress.
fn tick(args: &DiffuseTickArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let mut preview = workspace.worktree.world.clone();
let report = tick_diffusion(&mut preview, args.amount);
println!("Diffusion tick preview · {} tick(s)", args.amount);
println!("├─ Newly reached {}", report.reached.len());
for (event, town) in &report.reached {
let potency = preview
.event_adjudications
.get(event)
.map_or(10_000, |state| state.potency_basis_points);
println!(
"│ • event @{event} → town @{town} · potency {}%",
potency / 100
);
}
println!("└─ Expired {}", report.expired.len());
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world = preview;
workspace.save_worktree("advance event diffusion")?;
println!("✓ Diffusion advanced in the worktree. Undo: efo restore --worktree --all");
Ok(())
}

View File

@ -73,15 +73,13 @@ use lib_efo::stats::{GenericStat, PositionIdentifier, Symbols};
use lib_efo::{
Displayable,
entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier},
epoch::{
EpochConfig, EpochIdentifier,
epoch_traits::{ConfigWritable, Diffable},
},
epoch::{EpochConfig, EpochIdentifier, epoch_traits::Diffable},
error::EpochError,
stats,
utils::RngLevel,
};
use log::{info, trace};
use std::collections::HashMap;
use crate::error::AppError;
use crate::success::{SuccessMessages, display_success};
@ -141,6 +139,9 @@ pub(crate) struct ShowArgs {
/// Common arguments used for *add* and *edit* operations.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo chr add Aria --stats strength:12 food:8\n efo town add Durn --position 12,5\n efo org add \"Iron Council\" --capital Durn --governor Aria\n\nSTATS: demographics, population, growthrate, crime, happiness, economy, food, industry, science, trade, military, army, strength, fortification, threat, infrastructure, bureaucracy, transportation, sprawl, health"
)]
pub struct AddArgs {
/// The desired name of the new entity. If omitted a random
/// name will be generated unless `--rng-name` is set.
@ -163,6 +164,10 @@ pub struct AddArgs {
}
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo chr edit Aria --stats strength:14\n efo chr edit Aria --delta --stats strength:2\n efo org edit \"Iron Council\" --capital Durn --governor Aria\n\nCreate an epoch with `efo epoch next` before risky edits so the previous snapshot remains available."
)]
/// Arguments for modifying an existing entity.
pub struct EditArgs {
/// Identifier (name or `@tag`) of the entity to edit
pub identifier: EntityIdentifier,
@ -182,6 +187,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)]
@ -208,7 +214,7 @@ pub struct CommonArgs {
pub faction: Option<stats::FactionId>,
#[arg(short = 'N', long, action = clap::ArgAction::SetTrue, default_value_t = false, group="faction_group")]
/// The entity doens't belong to any faction.
/// The entity does not belong to any faction.
pub no_faction: bool,
/// Updates the reach of the entity
@ -224,47 +230,51 @@ pub struct CommonArgs {
pub governor: Option<EntityIdentifier>,
#[arg(long, action = clap::ArgAction::SetTrue, default_value_t = false, group="governor_group")]
/// The entity doens't belong to any faction.
/// The entity does not have a governor.
pub no_governor: bool,
/// Link to a town to set as capital
#[arg(long, short = 'c', group = "capital_group")]
pub capital: Option<EntityIdentifier>,
/// The entity doens't have a capital.
/// The entity does not have a capital.
#[arg(long, action = clap::ArgAction::SetTrue, default_value_t = false, group="capital_group")]
pub no_capital: bool,
/// Change the prestige
#[arg(long, group = "capital_group")]
#[arg(long, conflicts_with = "prestige_add")]
pub prestige: Option<GenericStat>,
/// Change the prestige by a delta
#[arg(long, group = "capital_group", allow_negative_numbers = true)]
#[arg(long, conflicts_with = "prestige", allow_negative_numbers = true)]
pub prestige_add: Option<GenericStat>,
}
impl CommonArgs {
/// Validate the parser usage
fn validate(&self, e_type: &stats::EntityType) -> Result<(), EpochError> {
if (self.capital.is_some() || self.no_capital) && !matches!(e_type, stats::EntityType::Town)
if (self.capital.is_some() || self.no_capital)
&& !matches!(e_type, stats::EntityType::Organization)
{
Err(EpochError::IncorrectArgumentCombinaison {
category: "Capital",
e_type: *e_type,
advice: Some(
"Capitals are reserved to town, maybe you used the wrong subcommand?"
"Only organisations can own a capital. Use `efo org edit ... --capital <town>`."
.to_string(),
),
})
} else if (self.governor.is_some() || self.no_governor)
&& !matches!(e_type, stats::EntityType::Town)
&& !matches!(
e_type,
stats::EntityType::Town | stats::EntityType::Organization
)
{
Err(EpochError::IncorrectArgumentCombinaison {
category: "Governor",
e_type: *e_type,
advice: Some(
"Governors are reserved to towns, maybe you used the wrong subcommand?"
"Governors can lead towns or organisations. Use the `town` or `org` command."
.to_owned(),
),
})
@ -290,7 +300,31 @@ pub fn handle_entity_commands(
entity_sub_commands: &EntitySubCommands,
e_type: &stats::EntityType,
) -> Result<(), AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
let mut workspace = lib_efo::workspace::Workspace::open(std::path::Path::new("."))?;
let mut main_epoch = {
let state = &workspace;
let mut epochs = HashMap::new();
for entry in std::fs::read_dir("epoch")? {
let entry = entry?;
if entry.file_type()?.is_dir()
&& let Ok(id) = entry.file_name().to_string_lossy().parse()
{
epochs.insert(id, None);
}
}
epochs.insert(state.manifest.epoch_id, Some(state.worktree.world.clone()));
EpochConfig {
epoch_id: state.manifest.epoch_id,
version: state.manifest.version.clone(),
tags: state.manifest.tags.clone().into_iter().collect(),
list_existing_epochs: epochs,
preloaded_current: true,
}
};
let mutates = matches!(
entity_sub_commands,
EntitySubCommands::Add(_) | EntitySubCommands::Del(_) | EntitySubCommands::Edit(_)
);
match entity_sub_commands {
EntitySubCommands::Add(entity_args) => {
handle_create_entity(entity_args, e_type, &mut main_epoch)
@ -311,6 +345,11 @@ pub fn handle_entity_commands(
handle_diff_entity(entity_args, e_type, &mut main_epoch)
}
}?;
if mutates {
let changed = main_epoch.loaded_epoch(main_epoch.epoch_id)?.clone();
workspace.worktree.world = changed;
workspace.save_worktree("entity edit")?;
}
Ok(())
}
@ -370,8 +409,6 @@ pub(crate) fn handle_create_entity(
vec_entities.push(entity.clone());
entity.print_full(epoch_info);
// Save changes
epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(message);
Ok(())
@ -394,14 +431,13 @@ fn handle_delete_entity(
let entity = vec_entities.swap_remove(index);
entity.remove_all_links(epoch_info)?;
// TODO: Clean all the links from it's presence
// TODO: Clean every bidirectional link referencing the removed entity.
// for l in entity.links(){
// // Figure out what the link is
// // Delete either a governor or capital
// }
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(&crate::success::SuccessMessages::DeletedEntity(
entity.name,
entity.entity_type.to_shortest(),
@ -426,8 +462,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 =
@ -500,8 +536,6 @@ fn handle_edit_entity(
entity.print_full(epoch_info);
// Only swap if a swap is needed
epoch_info.swap_entity(entity)?;
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(&edited_entity);
Ok(())
}

View File

@ -50,12 +50,18 @@ pub(crate) fn update_defaults(entity_args: &AddArgs, e: &mut Entity) {
EffectBounds { min: 20, max: 60 },
NAMING.generate_town_name(),
),
EntityType::Monster => (
EntityType::Calamity => (
lib_efo::entity::EntityDuration::Permanent,
lib_efo::entity::EffectApplication::WhenPresent,
EffectBounds { min: 20, max: 80 },
NAMING.generate_calamity_name(),
),
EntityType::Organization => (
lib_efo::entity::EntityDuration::Permanent,
lib_efo::entity::EffectApplication::WhenPresent,
EffectBounds { min: 0, max: 120 },
"Unnamed Organisation".to_string(),
),
EntityType::Blocker => (
lib_efo::entity::EntityDuration::Permanent,
lib_efo::entity::EffectApplication::WhenPresent,
@ -311,7 +317,8 @@ pub(crate) fn default_rng_for(e_type: &stats::EntityType) -> RngLevel {
stats::EntityType::Character => RngLevel::Med,
stats::EntityType::Player => RngLevel::High,
stats::EntityType::Town => RngLevel::Med,
stats::EntityType::Monster => RngLevel::Legendary,
stats::EntityType::Calamity => RngLevel::Legendary,
stats::EntityType::Organization => RngLevel::Med,
stats::EntityType::Blocker => RngLevel::Apocaliptic,
stats::EntityType::Event => RngLevel::Doom,
}

View File

@ -1,326 +1,122 @@
//! # `epoch` sub-command
//!
//! The `epoch` sub-command is the single entry point for all epoch-related
//! operations in **efo**.
//! An *epoch* represents a point in the simulated world's history.
//! The command lets you inspect, advance, modify and sanity-check the epoch
//! timeline.
//!
//! ### Usage
//!
//! ```bash
//! # Show log of epochs (last 20 by default)
//! efo epoch log --limit 20
//!
//! # Switch to an existing epoch
//! efo epoch switch 5
//!
//! # Create the next epoch if none exist in the future
//! efo epoch next
//!
//! # Delete all future epochs, returning to the present
//! efo epoch reset
//!
//! # Add a unique tag to the current epoch
//! efo epoch tag milestone1
//!
//! # Replace the current epoch's summary
//! efo epoch summary "Reached the new frontier"
//!
//! # (Future) Check consistency
//! efo epoch fsck
//! ```
//!
//! ### Summary
//!
//! | Sub-command | Usage | What it changes |
//! |-------------|------------------------------|----------------------------------------------------------------------|
//! | `log` | `efo epoch log [--limit N]` | Prints the chronological list of epochs up to the current one. |
//! | `switch` | `efo epoch switch <id>` | Sets the current epoch to the specified `<id>` (must already exist). |
//! | `next` | `efo epoch next` | Generates the next scheduled epoch and inserts it. |
//! | `reset` | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. |
//! | `diff` | `efo epoch diff <id1> <id2>` | *Unimplemented* - placeholder for future diffing logic. |
//! | `tag` | `efo epoch tag <TAG>` | Adds a unique tag to the current epoch, updating the global tag map. |
//! | `fsck` | `efo epoch fsck` | *Unimplemented* - intended to run a consistency check. |
//! | `summary` | `efo epoch summary <text>` | Replaces the `summary` field of the current epoch with `<text>`. |
//!
//! Epoch annotations, inspection, and compatibility command aliases.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use std::path::Path;
use crate::{
error::AppError,
success::{SuccessMessages, display_success},
};
use lib_efo::{
epoch::{EpochConfig, EpochId, epoch_traits::ConfigWritable},
epoch::{EpochId, EpochIdentifier},
error::EpochError,
workspace::Workspace,
};
use log::{debug, info};
use crate::error::AppError;
pub mod cli_epoch;
/// **Public entry point used by `efo::main`** - dispatches to the real
/// handler that lives in `crate::world::EpochManager`.
///
/// # Arguments
/// * `cmd` - The command to execute. This is an enum that represents
/// one of the possible sub-commands for the `epoch` feature.
///
/// # Returns
/// * `Ok(())` on success.
/// * `Err(AppError)` if any step of the command handling fails.
///
/// # Examples
/// ```no_run
/// // Create a command to switch to epoch 3.
/// let cmd = cli_epoch::EpochCmd::Switch(cli_epoch::Switch { target: 3 });
/// // Execute the command.
/// let result = handle_cmd(cmd);
/// assert!(result.is_ok());
/// ```
///
/// The function never panics under normal operation. All errors are
/// reported via the returned `Result`.
/// Dispatch an `efo epoch` subcommand through the current workspace model.
pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
// TODO(2): Remove this debug
debug!("The main epoch befor any action is {:#?}", main_epoch);
let mut workspace = Workspace::open(Path::new("."))?;
match cmd {
cli_epoch::EpochCmd::Log(args) => handle_log(args, &mut main_epoch),
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::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),
}?;
info!("The main epoch after all actions is {:#?}", main_epoch);
Ok(())
}
/// Edits the summary for the current epoch.
///
/// The function loads the epoch that is currently active in
/// `main_epoch`, then replaces its `summary` field with the value
/// supplied in `args.summary`. The epoch map in `main_epoch` is
/// modified in place.
///
/// This helper is internal to the `epoch` sub-command and is not part
/// of the public API.
fn handle_summary(args: &cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let epoch_id = main_epoch.epoch_id;
main_epoch.try_load(&epoch_id)?;
#[allow(clippy::unwrap_used)] // The epoch_id must exists at this point
if let Some(epoch) = main_epoch
.list_existing_epochs
.get_mut(&epoch_id)
.ok_or(EpochError::EpochHashingImpossible(file!(), line!()))?
{
epoch.summary = args.summary.clone();
epoch.save_with_context("Saving new summary", &lib_efo::epoch::SaveMode::Erase)?;
display_success(&SuccessMessages::ChangedSummary(
epoch_id,
args.summary.clone(),
));
cli_epoch::EpochCmd::Summary(args) => {
workspace.worktree.world.summary = args.summary.clone();
workspace.save_worktree("edit summary")?;
println!("✓ Updated the worktree summary. Stage it with `efo stage --world`.");
}
cli_epoch::EpochCmd::Tag(args) => {
if workspace.worktree.world.tags.contains(&args.tag)
|| workspace.manifest.tags.contains_key(&args.tag)
{
return Err(EpochError::TagAlreadyExists(
workspace.manifest.epoch_id,
args.tag.clone(),
)
.into());
}
workspace.worktree.world.tags.push(args.tag.clone());
workspace.save_worktree("edit tags")?;
println!(
"✓ Added tag `{}` to the worktree. Stage it with `efo stage --world`.",
args.tag
);
}
cli_epoch::EpochCmd::Reset(_) => {
return Err(EpochError::Unknown(
"`epoch reset` is removed; use recoverable `efo prune-future`, or explicit `efo reset --hard <epoch>` for permanent deletion"
.into(),
)
.into());
}
cli_epoch::EpochCmd::Next(_) => {
let id = workspace.advance_and_commit()?;
println!("✓ Advanced time and committed epoch {id}.");
}
cli_epoch::EpochCmd::Fsck(_) => {
let mut checked = 0;
for entry in std::fs::read_dir("epoch")? {
let entry = entry?;
if entry.file_type()?.is_dir()
&& let Ok(id) = entry.file_name().to_string_lossy().parse()
{
workspace.check_epoch(id)?;
checked += 1;
}
}
println!("✓ Repository format 1.0 is consistent ({checked} epoch(s) checked).");
}
cli_epoch::EpochCmd::Switch(args) => {
let target = resolve_epoch(&workspace, &args.target)?;
workspace.switch(target)?;
println!("✓ Switched to epoch {target}.");
}
cli_epoch::EpochCmd::Diff(args) => {
let start_id = resolve_epoch(&workspace, &args.start)?;
let end_id = args
.end
.as_ref()
.map(|id| resolve_epoch(&workspace, id))
.transpose()?
.unwrap_or(workspace.manifest.epoch_id);
println!("Epoch {start_id} → {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);
let mut shown = 0;
while let Some(current) = id.filter(|_| shown < args.context) {
let epoch = workspace.load_epoch(current)?;
let message = if epoch.commit_message.is_empty() {
"(initial snapshot)"
} else {
&epoch.commit_message
};
println!(
"{} epoch {} {}",
if shown == 0 { "*" } else { " " },
current,
message
);
id = epoch.parent_epoch;
shown += 1;
}
}
}
Ok(())
}
/// 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")
}
/// Show a log of all epochs up to the current one.
///
/// The function collects the identifiers of all epochs that are
/// less than or equal to the currently active epoch (`main_epoch.epoch_id`),
/// sorts them, and then asks the configuration to log the elements
/// up to the supplied limit. The log is written by the
/// underlying `EpochConfig::log_elements` implementation.
///
/// This helper is internal to the `epoch` sub-command.
fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let context = args.context;
let start_id = &main_epoch.epoch_id;
let mut list_id: Vec<EpochId> = main_epoch.list_existing_epochs.keys().copied().collect();
list_id.sort();
// list_id.reverse();
let pos = **list_id
.iter()
.find(|id| id == &start_id)
.ok_or(EpochError::EpochNotFound(start_id.to_string()))? as usize;
main_epoch.log_elements(
&list_id[(pos.saturating_sub(context))..std::cmp::min(pos + context + 1, list_id.len())],
)?;
Ok(())
}
/// Switches the current epoch to the one specified by the user.
///
/// The function loads the target epoch, updates the epoch identifier
/// in the configuration, and persists the change. It also prints a
/// success message via `display_success`.
///
/// This helper is internal to the `epoch` sub-command.
fn handle_switch(args: &cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let target = main_epoch.get_epoch_id(&args.target)?;
main_epoch.try_load(&target)?;
let message = &SuccessMessages::EpochSwitchSuccess(target, main_epoch.epoch_id);
main_epoch.epoch_id = target;
main_epoch.save_with_context(
"Saving modified epoch config",
&lib_efo::epoch::SaveMode::Erase,
)?;
display_success(message);
Ok(())
}
/// Handle the `next` sub-command.
///
/// Advances the epoch to the next scheduled event. If the current
/// configuration contains any epochs with an identifier larger than
/// the current one, an error is returned - otherwise the next epoch
/// is computed.
///
/// # Arguments
/// * `main_epoch` - mutable reference to the current `EpochConfig`
/// (the `cli_epoch::Next` argument is unused).
///
/// # Returns
/// * `Ok(())` if the next epoch was successfully computed.
/// * `Err(AppError::Epoch(EpochError::FutureEpochExist))` if there are
/// no future epochs to advance to.
fn handle_next(_args: &cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let current_id = main_epoch.epoch_id;
// Check that there are no future epochs
if main_epoch
.list_existing_epochs
.keys()
.any(|id| id > &current_id)
{
Err(AppError::Epoch(EpochError::FutureEpochExist))
} else {
let new_epoch = main_epoch.compute_next()?;
let new_id = new_epoch.epoch_id;
// Insert new epoch
main_epoch.insert_and_save(new_epoch, &lib_efo::epoch::SaveMode::DoNotErase)?;
display_success(&SuccessMessages::EpochNextSuccess(current_id, new_id));
Ok(())
}
}
/// Handle the `reset` sub-command.
///
/// Deletes all epochs whose identifier is greater than the current one,
/// effectively rolling back to the present epoch.
///
/// # Arguments
/// * `main_epoch` - mutable reference to the current `EpochConfig`
/// (the `cli_epoch::Reset` argument is unused).
///
/// # Returns
/// * `Ok(())` if all future epochs were successfully removed.
/// * `Err(AppError)` if any deletion fails.
fn handle_reset(args: &cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let _ = args;
let current_id = main_epoch.epoch_id;
// for id in main_epoch
for id in main_epoch
.list_existing_epochs
.keys()
.filter(|&k| k > &current_id)
.copied()
// Middle step necessary for borrowing purposes
.collect::<Vec<_>>()
{
main_epoch.delete_id(id)?
}
display_success(&SuccessMessages::DeletedAllFutureEvents(current_id));
Ok(())
}
/// Handle the `tag` sub-command.
///
/// Adds a tag to the current epoch. The tag must not already exist
/// elsewhere in the configuration; otherwise an error is returned.
///
/// # Arguments
/// * `args` - `cli_epoch::Tag` containing the tag to add.
/// * `main_epoch` - mutable reference to the current `EpochConfig`.
///
/// # Returns
/// * `Ok(())` if the tag was successfully added.
/// * `Err(AppError::Epoch(EpochError::TagAlreadyExists))` if the tag
/// already exists in another epoch.
/// * `Err(AppError::Epoch(EpochError::Unknown))` if the epoch cannot
/// be found or saved.
fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
// Load into memory the current epoch
main_epoch.try_load(&main_epoch.epoch_id.clone())?;
// Check if the tag doens't exists
if main_epoch.tags.contains_key(&args.tag) {
Err(AppError::Epoch(EpochError::TagAlreadyExists(
main_epoch.epoch_id,
args.tag.clone(),
)))?;
}
// Modify the epoch to add the tag inside
#[allow(clippy::unwrap_used)]
if let Some(current_epoch_info) = main_epoch
.list_existing_epochs
.get_mut(&main_epoch.epoch_id)
.ok_or(EpochError::EpochHashingImpossible(file!(), line!()))?
{
let message = &SuccessMessages::TagAdded(args.tag.clone(), current_epoch_info.epoch_id);
current_epoch_info.tags.push(args.tag.clone());
current_epoch_info
.save_with_context("Saving modified epoch", &lib_efo::epoch::SaveMode::Erase)?;
main_epoch
/// Resolve an epoch ID or exact manifest tag.
fn resolve_epoch(workspace: &Workspace, identifier: &EpochIdentifier) -> Result<EpochId, AppError> {
match identifier {
EpochIdentifier::Id(id) => Ok(*id),
EpochIdentifier::Tag(tag) => workspace
.manifest
.tags
.insert(args.tag.clone(), main_epoch.epoch_id);
main_epoch.save_with_context(
"Saving modified main config",
&lib_efo::epoch::SaveMode::Erase,
)?;
display_success(message);
Ok(())
} else {
Err(AppError::Epoch(lib_efo::error::EpochError::Unknown(
format!("Couldn't add the tag {}", args.tag),
)))
.get(tag)
.copied()
.ok_or_else(|| EpochError::EpochNotFound(tag.clone()).into()),
}
}
/// Perform a filesystem consistency check on the epoch data.
///
/// The function invokes the internal consistency-check logic of
/// `EpochConfig`. It is intended for use from the `fsck` sub-command
/// and does **not** modify the current epoch. Any problems that
/// are detected are reported through the returned `Result`; the
/// command may also print a diagnostic message to the user.
///
/// 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!()
}

View File

@ -8,7 +8,7 @@
//! * **`log`** - list epochs in a git-log style.
//! * **`switch`** - switch to a specific epoch (by id, name or tag).
//! * **`next`** - compute the next epoch from the current one.
//! * **`reset`** - delete all future events after the current epoch.
//! * **`reset`** - compatibility diagnostic for the removed spelling.
//! * **`diff`** - show differences between two epochs.
//! * **`tag`** - add a tag to the current epoch.
//! * **`fsck`** - perform basic filesystem level maintenance.
@ -33,7 +33,7 @@ pub enum EpochCmd {
/// Compute the next epoch from the current one
Next(Next),
/// Delete *all* future events after the current epoch
/// Removed destructive spelling; use recoverable `prune-future`.
Reset(Reset),
/// Show the differences between two epochs
@ -66,24 +66,22 @@ pub struct Log {
///
/// # Arguments
/// * `target` - The epoch to switch to.
/// * `force` - If set, drops all pending work and forces the switch.
#[derive(Args, Debug)]
pub struct Switch {
/// The epoch to switch to - can be an integer, a name, or a tag.
#[arg(required = true)]
pub target: EpochIdentifier,
/// Optional confirmation flag (if you ever want to force-switch)
#[arg(long, short, help = "Force-switch dropping all the pending work")]
pub force: bool,
}
/// Computes the next epoch from the current one.
#[derive(Args, Debug)]
pub struct Next;
/// Deletes all future events after the current epoch.
/// Reports the replacement commands for the removed spelling.
#[derive(Args, Debug)]
#[command(
after_long_help = "REMOVED: use `efo prune-future` for recoverable removal, or `efo reset --hard <epoch>` for permanent deletion."
)]
pub struct Reset;
/// Shows the differences between two epochs.

View File

@ -61,6 +61,8 @@
//!
//! *All sub-commands simply output the generated data; they do not alter any files or state.*
use std::path::PathBuf;
use clap::{Args, Subcommand};
use lib_efo::{Displayable, error::EpochError, naming::NAMING};
@ -82,6 +84,25 @@ pub enum GenCmd {
Calamity(Qty),
/// Blocker
Blocker(Qty),
/// Generate a deterministic world from embedded or external configuration.
World(WorldArgs),
}
/// Deterministic world-generation options.
#[derive(Args, Debug)]
pub struct WorldArgs {
/// Amount of state to generate.
#[arg(long, value_enum, default_value_t = lib_efo::worldgen::GenerationLevel::World)]
level: lib_efo::worldgen::GenerationLevel,
/// Reproducible random seed; generated and printed when omitted.
#[arg(long)]
seed: Option<u64>,
/// JSON configuration override; embedded defaults are used when omitted.
#[arg(long, value_name = "PATH")]
config: Option<PathBuf>,
/// Replace the repository worktree; preview is the default.
#[arg(long)]
apply: bool,
}
#[derive(Args, Debug)]
@ -125,10 +146,41 @@ pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> {
GenCmd::Exotic(args) => handle_exotic(args)?,
GenCmd::Calamity(args) => handle_calamity(args)?,
GenCmd::Blocker(args) => handle_blocker(args)?,
GenCmd::World(args) => handle_world(args)?,
}
Ok(())
}
/// Preview or apply a deterministic generated world.
fn handle_world(args: &WorldArgs) -> Result<(), AppError> {
let config = args.config.as_deref().map_or_else(
lib_efo::worldgen::WorldGenConfig::embedded,
lib_efo::worldgen::WorldGenConfig::load,
)?;
let seed = args.seed.unwrap_or_else(rand::random);
let mut world = lib_efo::worldgen::generate(&config, seed, args.level);
println!("World generation preview · {:?} · seed {seed}", args.level);
println!("├─ Characters {}", world.characters.len());
println!("├─ Towns {}", world.towns.len());
println!("├─ Events {}", world.events.len());
println!("├─ Calamities {}", world.calamities.len());
println!("├─ Organisations {}", world.organizations.len());
println!("└─ Blockers {}", world.blockers.len());
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to replace the worktree.");
return Ok(());
}
let mut workspace = lib_efo::workspace::Workspace::open(std::path::Path::new("."))?;
world.epoch_id = workspace.worktree.world.epoch_id;
world.parent_epoch = workspace.worktree.world.parent_epoch;
world.commit_message = workspace.worktree.world.commit_message.clone();
workspace.worktree.world = world;
workspace.save_worktree("generate world")?;
println!("✓ Replaced the worktree with generated state using seed {seed}.");
println!(" Undo: efo restore --worktree --all");
Ok(())
}
/// Print a calamity name
fn handle_calamity(args: &Qty) -> Result<(), EpochError> {
for _ in 0..args.number {

View File

@ -0,0 +1,221 @@
//! Immutable commit and log commands.
use std::{
fs,
path::{Path, PathBuf},
};
use clap::Args;
use lib_efo::{
epoch::{EpochId, EpochIdentifier, EpochInfo},
workspace::Workspace,
};
use crate::error::AppError;
/// Create an immutable epoch from the index.
#[derive(Args, Debug)]
pub struct CommitCmd {
/// Required explanation stored with the new epoch.
#[arg(short, long, required = true)]
message: String,
}
/// Options for displaying immutable history.
#[derive(Args, Debug)]
pub struct LogCmd {
/// Maximum number of newest entries to display.
#[arg(short, long, default_value_t = 20)]
limit: usize,
}
/// Select an existing immutable epoch.
#[derive(Args, Debug)]
pub struct SwitchCmd {
/// Epoch ID or tag to check out.
target: EpochIdentifier,
}
/// Create a new commit that inverses one historical epoch.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo revert 4\n efo diff\n efo stage --all\n efo commit -m 'Revert epoch 4'\n efo revert 4 --commit\n\nThe default is reviewable and changes only the worktree. --commit creates a new epoch; it does not move HEAD backward."
)]
pub struct RevertCmd {
/// Epoch ID or tag whose introduced changes should be inverted.
target: EpochIdentifier,
/// Immediately stage and commit the inverse instead of leaving it in the worktree.
#[arg(long)]
commit: bool,
}
/// Options for permanently rewinding repository history.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo reset --hard 3\n efo reset --hard 3 --yes\n\nWithout --yes, this command is a read-only preview. For recoverable removal, use `efo switch 3` followed by `efo prune-future --yes`."
)]
pub struct ResetCmd {
/// Required acknowledgement that worktree changes and newer commits will be destroyed.
#[arg(long, required = true)]
hard: bool,
/// Epoch ID or tag to retain as the new HEAD.
target: EpochIdentifier,
/// Perform the reset after displaying its destructive scope.
#[arg(long)]
yes: bool,
}
/// Preview, apply, or restore backed-up future-history pruning.
#[derive(Args, Debug)]
pub struct PruneFutureCmd {
/// Restore a backup directory previously printed by this command.
#[arg(long, value_name = "BACKUP")]
restore: Option<PathBuf>,
/// Confirm moving history or restoring a backup.
#[arg(long)]
yes: bool,
}
/// Commit staged state through a manifest-last transaction.
pub fn commit(command: &CommitCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let id = workspace.commit(command.message.clone())?;
println!("✓ Committed epoch {id}: {}", command.message);
println!(" HEAD, index, and worktree are now aligned.");
Ok(())
}
/// Display history newest first.
pub fn log(command: &LogCmd) -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
let mut id = Some(workspace.manifest.epoch_id);
let mut shown = 0;
while let Some(current) = id.filter(|_| shown < command.limit) {
let path = Path::new("epoch")
.join(current.to_string())
.join("epochinfo.json");
let epoch: EpochInfo = serde_json::from_slice(&fs::read(&path)?)
.map_err(lib_efo::error::StorageError::from)?;
let message = if epoch.commit_message.is_empty() {
"(initial snapshot)"
} else {
&epoch.commit_message
};
println!(
"{} epoch {} {}",
if shown == 0 { "*" } else { " " },
current,
message
);
id = epoch
.parent_epoch
.or_else(|| (current.id > 0).then(|| lib_efo::epoch::EpochId::new(current.id - 1)));
shown += 1;
}
Ok(())
}
/// Switch all clean state layers to an immutable epoch.
pub fn switch(command: &SwitchCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let previous = workspace.manifest.epoch_id;
let target = resolve(&workspace, &command.target)?;
workspace.switch(target)?;
println!("✓ Switched HEAD from epoch {previous} to epoch {target}.");
Ok(())
}
/// Revert a historical change by creating a new immutable epoch.
pub fn revert(command: &RevertCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let target = resolve(&workspace, &command.target)?;
if command.commit {
println!("Warning: `revert --commit` creates a new epoch; it does not move HEAD backward.");
let new_id = workspace.revert(target)?;
println!("✓ Reverted epoch {target} in new epoch {new_id}.");
} else {
workspace.revert_to_worktree(target)?;
println!("✓ Applied the inverse of epoch {target} to the worktree.");
println!(
" Review with `efo diff`, then stage and commit it—or undo with `efo restore --worktree --all`."
);
}
Ok(())
}
/// Preview or perform an unrecoverable history reset.
pub fn reset(command: &ResetCmd) -> Result<(), AppError> {
debug_assert!(command.hard, "clap requires --hard");
let mut workspace = Workspace::open(Path::new("."))?;
let target = resolve(&workspace, &command.target)?;
workspace.load_epoch(target)?;
let removed = workspace.epochs_after(target)?;
println!("Hard-reset preview: HEAD, index, and worktree → epoch {target}");
println!("Uncommitted changes will be permanently discarded.");
println!("Newer epochs to destroy: {}", removed.len());
for id in &removed {
println!(" epoch {id}");
}
if !command.yes {
println!("Nothing changed. Run again with `--yes` to permanently destroy this state.");
println!("Safer alternative: switch to the epoch, then use `efo prune-future --yes`.");
return Ok(());
}
let removed = workspace.hard_reset(target)?;
println!(
"✓ Hard-reset to epoch {target}; destroyed {} newer epoch(s).",
removed.len()
);
println!(
" This operation has no Epoch Forge undo; recovery requires an external backup or Git."
);
Ok(())
}
/// Resolve a numeric ID or exact tag against the manifest.
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()),
}
}
/// Move future epochs into a recoverable backup, or restore that backup.
pub fn prune_future(command: &PruneFutureCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
if let Some(backup) = &command.restore {
if !command.yes {
println!("Restore preview: {}", backup.display());
println!("Run again with `--yes` to restore this history.");
return Ok(());
}
let count = workspace.restore_pruned(backup)?;
println!("✓ Restored {count} epoch(s) from {}.", backup.display());
return Ok(());
}
let future = workspace.future_epochs()?;
println!("Future-history prune preview: {} epoch(s)", future.len());
for id in &future {
println!(" epoch {id}");
}
if !command.yes {
println!("Nothing changed. Run again with `--yes` to move these epochs into a backup.");
return Ok(());
}
let backup = workspace.prune_future()?;
println!(
"✓ Moved {} epoch(s) into {}.",
future.len(),
backup.display()
);
println!(
" Undo: efo prune-future --restore '{}' --yes",
backup.display()
);
Ok(())
}

View File

@ -33,11 +33,8 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use clap::Args;
use lib_efo::{
epoch::{EpochConfig, EpochInfo, epoch_traits::ConfigWritable},
error::EpochError,
};
use std::fs::read_dir;
use lib_efo::error::EpochError;
use std::{fs::read_dir, path::Path};
use crate::{
error::AppError,
@ -59,44 +56,28 @@ pub struct InitCmd {
///
/// Creates the default `EpochConfig`, verifies that the target directory
/// is empty, and writes the initial configuration and epoch data.
//TODO(5): Upholster the logic behind force and empty detection
pub fn init(args: &InitCmd) -> Result<(), AppError> {
let epoch_config = EpochConfig::default();
let root = epoch_config.save_folder();
let root = ".";
let config_path = ".epoch";
let initial_epoch_path = "epoch/0/epochinfo.json";
if read_dir(&root)?.count() != 0 {
Err(EpochError::FolderNotEmpty {
name: root,
show_label: None,
})?;
}
init_epoch(args)?;
epoch_config
.save_with_context(
"Creatig initial config",
&lib_efo::epoch::SaveMode::DoNotErase,
)
.map_err(|_| EpochError::AlreadyInitialized {
if Path::new(&config_path).exists() || Path::new(&initial_epoch_path).exists() {
Err(EpochError::AlreadyInitialized {
advice: Some(
"You must remove the .epoch configuration file manually or pick another folder"
"Use `efo status` to inspect this repository; existing Epoch Forge data was not changed."
.to_string(),
),
})?;
}
if !args.force && read_dir(root)?.next().is_some() {
Err(EpochError::FolderNotEmpty {
name: root.to_owned(),
show_label: None,
})?;
}
lib_efo::workspace::Workspace::initialize(Path::new("."), env!("CARGO_PKG_VERSION"))?;
display_success(&SuccessMessages::FolderInitializedSuccessfully("."));
Ok(())
}
/// Helper that creates the initial epoch (epoch 0).
///
/// This function is not part of the public API; it is kept internal
/// to `init`. It creates an empty `EpochInfo`, crea
fn init_epoch(_args: &InitCmd) -> Result<(), AppError> {
let empty = EpochInfo::default();
_ = empty.create_subfolders();
empty.save_with_context(
"Creating empty epoch file 0",
&lib_efo::epoch::SaveMode::DoNotErase,
)?;
Ok(())
}

View File

@ -0,0 +1,71 @@
//! Recovery and writer-lock inspection commands.
use std::path::Path;
use clap::{Args, Subcommand};
use lib_efo::transaction::{RecoveryOutcome, break_lock, inspect_lock, recover};
use crate::error::AppError;
/// Arguments for deterministic transaction recovery.
#[derive(Args, Debug)]
pub struct RecoverCmd {}
/// Writer-lock administration.
#[derive(Subcommand, Debug)]
pub enum LockCmd {
/// Show which process owns the writer lock.
Inspect,
/// Remove a lock after independently confirming its owner is gone.
Break(BreakLockCmd),
}
/// Explicit confirmation required to remove a writer lock.
#[derive(Args, Debug)]
pub struct BreakLockCmd {
/// Confirm that the recorded writer is no longer operating.
#[arg(long, required = true)]
yes: bool,
}
/// Recover or clean an interrupted repository transaction.
pub fn handle_recover(_command: &RecoverCmd) -> Result<(), AppError> {
match recover(Path::new("."))? {
RecoveryOutcome::Clean => println!("Repository is clean — no recovery is needed."),
RecoveryOutcome::RolledBack => {
println!("✓ Rolled back an uncommitted replacement; prior data is unchanged.")
}
RecoveryOutcome::Completed => {
println!("✓ Verified the committed replacement and completed recovery.")
}
}
Ok(())
}
/// Inspect or explicitly remove the repository writer lock.
pub fn handle_lock(command: &LockCmd) -> Result<(), AppError> {
match command {
LockCmd::Inspect => {
let owner = inspect_lock(Path::new("."))?;
println!("Writer lock");
if let Some(repository_id) = owner.repository_id {
println!("├─ Repository {repository_id}");
}
println!("├─ PID {}", owner.pid);
println!("├─ Started {}", owner.process_start);
println!("├─ Host {}", owner.hostname);
println!("├─ Command {}", owner.command);
println!("└─ Created {} (Unix time)", owner.created_at);
}
LockCmd::Break(arguments) => {
debug_assert!(arguments.yes);
let owner = break_lock(Path::new("."))?;
println!(
"✓ Removed lock for PID {} on {} (`{}`).",
owner.pid, owner.hostname, owner.command
);
println!(" Run `efo recover` before the next mutation.");
}
}
Ok(())
}

View File

@ -1,51 +1,255 @@
//! The show commands
//! Used to display structures with various degree of verbosity
//! Unified entity and epoch inspection.
use clap::Subcommand;
use lib_efo::{Displayable, entity::Entity, epoch::EpochInfo, naming::NAMING};
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;
#[derive(Subcommand, Debug)]
/// Show command
pub enum ShowCmd {
/// Show an event
/// Collection selected by `efo show`.
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum ShowKind {
/// Every entity collection.
#[default]
All,
/// Events.
Event,
/// Show an event
/// Characters.
#[value(alias = "chr")]
Character,
/// Show an event
/// Towns.
Town,
/// Calamities.
Calamity,
/// Organisations.
#[value(aliases = ["org", "organisation"])]
Organization,
/// Blockers.
Blocker,
/// Committed epoch summaries.
Epoch,
}
// #[derive(Args)]
// struct Specifics {
// name: String,
// }
/// 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,
}
/// Handle all show cmds
pub fn handle_show_cmd(cmd: &ShowCmd) -> Result<(), AppError> {
let _ = cmd;
let mut e = Entity::default();
e.name = NAMING.generate_long_character_name();
println!("Original Struct: \n{e:#?}");
println!("\n\n\nONELINES");
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("\n\n\n SHORT");
e.short_display(&EpochInfo::default());
println!("\n\n\n LONG");
e.print_full(&EpochInfo::default());
println!("\n\n\n TREE");
println!("{}", e.to_pretty_tree(&EpochInfo::default()));
/// 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) {
print!("{}", render_epochs(args, &workspace)?);
return Ok(());
}
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());
print!("{}", render_entities(args, &world));
Ok(())
}
// Show event
// Show diff (char/town)
// Show ....
/// Render selected entity collections and filters.
fn render_entities(args: &ShowArgs, world: &EpochInfo) -> String {
let mut output = String::new();
let selected: &[(&str, EntityType)] = match args.kind {
ShowKind::All => &[
("Characters", EntityType::Character),
("Towns", EntityType::Town),
("Events", EntityType::Event),
("Calamities", EntityType::Calamity),
("Organisations", EntityType::Organization),
("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 (section, (title, entity_type)) in selected.iter().enumerate() {
if section > 0 {
output.push('\n');
}
let matches = world
.vec_entities(entity_type)
.iter()
.filter(|entity| matches_filters(entity, args))
.collect::<Vec<_>>();
output.push_str(&format!("{title} ({})\n", matches.len()));
if matches.is_empty() {
output.push_str(" — none\n");
continue;
}
for entity in matches {
match args.detail {
ShowDetail::Short => {
output.push_str(&entity.short_display(world));
output.push('\n');
}
ShowDetail::Long => {
output.push_str(&entity.short_display(world));
output.push('\n');
if !entity.description.trim().is_empty() {
output.push_str(&format!(" {}\n", entity.description));
}
}
ShowDetail::Full => {
output.push_str(&entity.full_display(world));
output.push('\n');
}
}
}
}
output
}
/// 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<String, AppError> {
let mut output = String::new();
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 {
" "
};
match args.detail {
ShowDetail::Short => {
output.push_str(&format!("{head} epoch {id} — {}\n", message(&epoch)));
}
ShowDetail::Long => {
output.push_str(&format!("{head} epoch {id} — {}\n", message(&epoch)));
output.push_str(&format!(
" parent: {} · entities: {} · tags: {}\n",
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() {
output.push_str(&format!(" summary: {}\n", epoch.summary));
}
}
ShowDetail::Full => {
output.push_str(
&serde_json::to_string_pretty(&epoch)
.map_err(lib_efo::error::StorageError::from)?,
);
output.push('\n');
}
}
}
Ok(output)
}
/// 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

@ -0,0 +1,246 @@
//! Status, diff, staging, and restoration.
use std::path::Path;
use clap::{Args, ValueEnum};
use lib_efo::{
diff::{ChangeKind, WorldDiff},
entity::EntityIdentifier,
epoch::EpochInfo,
stats::EntityType,
workspace::Workspace,
};
use crate::error::AppError;
/// CLI-safe names for persisted entity collections.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum EntityKind {
/// Characters.
Character,
/// Towns.
Town,
/// Events.
Event,
/// Calamities.
Calamity,
/// Organisations.
Organization,
/// Blockers.
Blocker,
}
impl From<EntityKind> for EntityType {
fn from(value: EntityKind) -> Self {
match value {
EntityKind::Character => Self::Character,
EntityKind::Town => Self::Town,
EntityKind::Event => Self::Event,
EntityKind::Calamity => Self::Calamity,
EntityKind::Organization => Self::Organization,
EntityKind::Blocker => Self::Blocker,
}
}
}
/// Select all state or named entities of one kind.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo stage --all\n efo stage --kind character Aria @UUID"
)]
pub struct StageCmd {
/// Stage the complete worktree.
#[arg(long, conflicts_with_all = ["kind", "world"])]
all: bool,
/// Stage only world-level metadata such as summary and tags.
#[arg(long, conflicts_with_all = ["all", "kind"])]
world: bool,
/// Stage only matching entities of this kind.
#[arg(long, value_enum, required_unless_present_any = ["all", "world"])]
kind: Option<EntityKind>,
/// Names or stable `@UUID` identifiers selected with `--kind`.
#[arg(required_unless_present_any = ["all", "world"])]
identifiers: Vec<EntityIdentifier>,
}
/// Select a source layer and state to restore.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo restore --staged --all\n efo restore --worktree --kind town Durn"
)]
pub struct RestoreCmd {
/// Copy HEAD into the index (unstage).
#[arg(long, group = "layer", required = true)]
staged: bool,
/// Copy the index into the editable worktree.
#[arg(long, group = "layer", required = true)]
worktree: bool,
/// Restore the complete selected layer.
#[arg(long, conflicts_with_all = ["kind", "world"])]
all: bool,
/// Restore only world-level metadata.
#[arg(long, conflicts_with_all = ["all", "kind"])]
world: bool,
/// Restore only matching entities of this kind.
#[arg(long, value_enum, required_unless_present_any = ["all", "world"])]
kind: Option<EntityKind>,
/// Names or stable `@UUID` identifiers selected with `--kind`.
#[arg(required_unless_present_any = ["all", "world"])]
identifiers: Vec<EntityIdentifier>,
}
/// Choose the diff boundary.
#[derive(Args, Debug)]
pub struct StateDiffCmd {
/// Compare HEAD to index instead of index to worktree.
#[arg(long)]
staged: bool,
}
/// Print repository state status.
pub fn status() -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
println!("Epoch {} (HEAD)", workspace.manifest.epoch_id);
println!(
"├─ Staged {}",
label(workspace.has_staged_changes(), "changes", "clean")
);
println!(
"├─ Worktree {}",
label(workspace.has_unstaged_changes(), "changes", "clean")
);
println!("└─ Next epoch {}", workspace.manifest.next_epoch_id);
if workspace.has_staged_changes() {
println!("\nStaged changes");
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!(
"{}",
render_diff(&workspace.index.world, &workspace.worktree.world)
);
println!("Use `efo diff` to review edits, then `efo stage ...`.");
}
Ok(())
}
/// Stage selected state.
pub fn stage(command: &StageCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
if command.all {
workspace.stage_all()?;
println!("✓ Staged the complete worktree.");
} else if command.world {
workspace.stage_world()?;
println!("✓ Staged world metadata.");
} else if let Some(kind) = command.kind {
workspace.stage_entities(kind.into(), &command.identifiers)?;
println!(
"✓ Staged {} selected entity/ies.",
command.identifiers.len()
);
}
Ok(())
}
/// Restore selected state from the explicitly named source layer.
pub fn restore(command: &RestoreCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
match (
command.staged,
command.worktree,
command.all,
command.world,
command.kind,
) {
(true, false, true, false, _) => workspace.restore_index()?,
(false, true, true, false, _) => workspace.restore_worktree()?,
(true, false, false, true, _) => workspace.restore_index_world()?,
(false, true, false, true, _) => workspace.restore_worktree_world()?,
(true, false, false, false, Some(kind)) => {
workspace.restore_index_entities(kind.into(), &command.identifiers)?
}
(false, true, false, false, Some(kind)) => {
workspace.restore_worktree_entities(kind.into(), &command.identifiers)?
}
_ => unreachable!("clap enforces layer and selection groups"),
}
println!("✓ Restored the selected state.");
println!(" Run `efo status` to review what remains.");
Ok(())
}
/// Display deterministic entity-level differences between state layers.
pub fn diff(command: &StateDiffCmd) -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
let (from, to, title) = if command.staged {
(&workspace.head, &workspace.index.world, "HEAD → index")
} else {
(
&workspace.index.world,
&workspace.worktree.world,
"index → worktree",
)
};
println!("{title}");
print!("{}", render_diff(from, to));
Ok(())
}
/// Render added, removed, and modified entities deterministically.
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 let Some((before, after)) = &diff.summary {
output.push_str(&format!(" ~ world summary: {before:?} → {after:?}\n"));
}
if let Some((before, after)) = &diff.tags {
output.push_str(&format!(" ~ world tags: {before:?} → {after:?}\n"));
}
if diff.is_empty() {
output.push_str(" No changes.\n");
} else {
output.push_str(&format!("{} change(s)\n", diff.len()));
}
output
}
/// 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.
fn label(changed: bool, changed_label: &'static str, clean_label: &'static str) -> &'static str {
if changed { changed_label } else { clean_label }
}

View File

@ -1,74 +1,31 @@
//! A very succint status display
//! Concise repository and current-epoch status.
use clap::Args;
use colored::Colorize;
use lib_efo::epoch::{EpochConfig, EpochId};
use lib_efo::epoch::EpochId;
/// Arguments for the `status` subcommand.
#[derive(Args, Debug)]
pub struct StatusCmd {
/// An optionnal EpochId showing another epoch
/// Show a numeric epoch instead of the currently checked-out epoch.
custom_id: Option<EpochId>,
}
/// Print a short status
/// Print the selected epoch's annotations, timeline state, and entity totals.
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)? }
} else {
main_epoch.try_load_current()?
};
let mut out = String::new();
out.push_str(
&format!(
"[{}{} {}]\n",
"󰬌 ".bright_blue(),
"Epoch".blue(),
current_epoch.epoch_id
)
.blue(),
);
if !current_epoch.summary.is_empty() {
out.push_str(&format!(
" ├─ {:12} {}\n",
"Summary".green(),
current_epoch.summary
));
if let Some(id) = cmd.custom_id {
let workspace = lib_efo::workspace::Workspace::open(std::path::Path::new("."))?;
let epoch = workspace.load_epoch(id)?;
println!("Epoch {}", epoch.epoch_id);
println!(
"└─ Entities: {}",
epoch.characters.len()
+ epoch.towns.len()
+ epoch.events.len()
+ epoch.calamities.len()
+ epoch.organizations.len()
+ epoch.blockers.len()
);
return Ok(());
}
if !current_epoch.tags.is_empty() {
out.push_str(&format!(
" ├─ {:12} {}\n",
"Tags".green(),
current_epoch.tags.join(",")
));
}
out.push_str(&format!(" └─ {}\n", "Stats".green()));
out.push_str(&format!(
" ├ {:11} {}\n",
"Events".bright_green(),
current_epoch.events.len()
));
out.push_str(&format!(
" ├ {:11} {}\n",
"Characters".bright_green(),
current_epoch.characters.len()
));
out.push_str(&format!(
" ├ {:11} {}\n",
"Towns".bright_green(),
current_epoch.towns.len()
));
out.push_str(&format!(
" └ {:11} {}",
"Blockers".bright_green(),
current_epoch.blockers.len()
));
println!("{}", out);
Ok(())
crate::commands::state::status()
}

View File

@ -0,0 +1,253 @@
//! Preview-first character travel commands.
use std::path::Path;
use clap::{Args, Subcommand};
use lib_efo::{
entity::EntityIdentifier,
simulation::{Road, begin_travel, plan_travel, tick_travel, validate_roads},
stats::EntityType,
workspace::Workspace,
};
use crate::error::AppError;
/// Spatial travel operations.
#[derive(Debug, Subcommand)]
pub enum TravelCmd {
/// List configured roads.
Roads,
/// Preview or add a road between two towns.
RoadAdd(RoadAddArgs),
/// Preview or remove a road by @UUID.
RoadRemove(RoadRemoveArgs),
/// Preview or begin a journey to a town.
Plan(TravelPlanArgs),
/// Preview or advance every active journey.
Tick(TravelTickArgs),
}
/// New-road arguments.
#[derive(Debug, Args)]
pub struct RoadAddArgs {
/// First town name/prefix or @UUID.
from: EntityIdentifier,
/// Second town name/prefix or @UUID.
to: EntityIdentifier,
/// Road travel speed percentage.
#[arg(long, default_value_t = 150)]
speed: u32,
/// Add the road to the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Road-removal arguments.
#[derive(Debug, Args)]
pub struct RoadRemoveArgs {
/// Exact road UUID, with or without `@`.
id: String,
/// Remove the road from the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Route-planning arguments.
#[derive(Debug, Args)]
#[command(
after_long_help = "EXAMPLES:\n efo travel plan Aria Haven\n efo travel plan @CHARACTER @TOWN --offroad-speed 50 --apply"
)]
pub struct TravelPlanArgs {
/// Character name/prefix or @UUID.
character: EntityIdentifier,
/// Destination town name/prefix or @UUID.
destination: EntityIdentifier,
/// Direct-travel speed percentage; roads carry their own speed.
#[arg(long, default_value_t = 50)]
offroad_speed: u32,
/// Store this plan in the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Simulation-tick arguments.
#[derive(Debug, Args)]
pub struct TravelTickArgs {
/// Number of ticks to advance.
#[arg(default_value_t = 1)]
amount: u64,
/// Update the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Dispatch one travel operation.
pub fn handle(cmd: &TravelCmd) -> Result<(), AppError> {
match cmd {
TravelCmd::Roads => roads(),
TravelCmd::RoadAdd(args) => road_add(args),
TravelCmd::RoadRemove(args) => road_remove(args),
TravelCmd::Plan(args) => plan(args),
TravelCmd::Tick(args) => tick(args),
}
}
/// List the stable travel topology.
fn roads() -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
validate_roads(&workspace.worktree.world)?;
println!("Roads ({})", workspace.worktree.world.roads.len());
for road in &workspace.worktree.world.roads {
let name = |id| {
workspace
.worktree
.world
.towns
.iter()
.find(|town| town.id == id)
.map_or("unknown", |town| town.name.as_str())
};
println!(
" • {} ↔ {} · {}% · @{}",
name(road.from),
name(road.to),
road.speed_percent,
road.id
);
}
Ok(())
}
/// Preview and optionally add one validated road.
fn road_add(args: &RoadAddArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let from = workspace
.worktree
.world
.find_entity_of_type(&Some(args.from.clone()), &EntityType::Town)?
.id;
let to = workspace
.worktree
.world
.find_entity_of_type(&Some(args.to.clone()), &EntityType::Town)?
.id;
println!("Road preview · @{from} ↔ @{to} · {}%", args.speed);
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world.roads.push(Road {
id: uuid::Uuid::new_v4(),
from,
to,
speed_percent: args.speed,
tags: Vec::new(),
});
validate_roads(&workspace.worktree.world)?;
workspace.save_worktree("add road")?;
println!("✓ Road added to the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally remove one road.
fn road_remove(args: &RoadRemoveArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let raw = args.id.strip_prefix('@').unwrap_or(&args.id);
let id =
uuid::Uuid::parse_str(raw).map_err(|_| lib_efo::error::EpochError::ParsingArgument {
argument_parsed: args.id.clone(),
while_parsing: "road UUID",
})?;
if !workspace
.worktree
.world
.roads
.iter()
.any(|road| road.id == id)
{
return Err(lib_efo::simulation::SimulationError::InvalidRoad {
id,
reason: "road does not exist".into(),
}
.into());
}
println!("Road removal preview · @{id}");
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world.roads.retain(|road| road.id != id);
workspace.save_worktree("remove road")?;
println!("✓ Road removed from the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally persist a selected route.
fn plan(args: &TravelPlanArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let character = workspace
.worktree
.world
.find_entity_of_type(&Some(args.character.clone()), &EntityType::Character)?
.id;
let destination = workspace
.worktree
.world
.find_entity_of_type(&Some(args.destination.clone()), &EntityType::Town)?
.id;
let plan = plan_travel(
&workspace.worktree.world,
character,
destination,
args.offroad_speed,
)?;
println!(
"Travel preview · {} · {} tick(s)",
if plan.uses_roads { "roads" } else { "direct" },
plan.total_ticks
);
if plan.route.is_empty() {
println!("└─ Direct off-road fallback");
} else {
for (index, place) in plan.route.iter().enumerate() {
let marker = if index + 1 == plan.route.len() {
"└─"
} else {
"├─"
};
let name = workspace
.worktree
.world
.towns
.iter()
.find(|town| town.id == *place)
.map_or("unknown", |town| town.name.as_str());
println!("{marker} {name} @{place}");
}
}
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
begin_travel(&mut workspace.worktree.world, character, destination, &plan)?;
workspace.save_worktree("begin travel")?;
println!("✓ Journey stored in the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally persist travel progress.
fn tick(args: &TravelTickArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let mut preview = workspace.worktree.world.clone();
let arrived = tick_travel(&mut preview, args.amount);
println!("Travel tick preview · {} tick(s)", args.amount);
println!("└─ {} arrival(s)", arrived.len());
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world = preview;
workspace.save_worktree("advance travel")?;
println!("✓ Travel advanced in the worktree. Undo: efo restore --worktree --all");
Ok(())
}

View File

@ -5,13 +5,28 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use lib_efo::error::{EpochError, StorageError};
use lib_efo::{
adjudication::AdjudicationError,
conflict::ConflictError,
error::{EpochError, StorageError},
repository_format::FormatError,
simulation::SimulationError,
transaction::TransactionError,
workspace::WorkspaceError,
worldgen::WorldGenError,
};
use miette::Diagnostic;
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),
/// Generic “invalid command / missing flag” - emitted by clap.
#[error("Command-line error: {0}")]
// #[diagnostic(transparent)]
@ -31,6 +46,26 @@ pub enum AppError {
#[error("Storage error: {0}")]
// #[diagnostic(transparent)]
Storage(#[from] StorageError),
/// Exclusive locking or interrupted-write recovery failed safely.
#[error("Repository safety check stopped: {0}")]
Transaction(#[from] TransactionError),
/// Format-2 state is missing, inconsistent, or unsafe to change.
#[error("Repository state error: {0}")]
Workspace(#[from] WorkspaceError),
/// Repository manifest format detection failed.
#[error("Repository format error: {0}")]
Format(#[from] FormatError),
/// World-generation configuration or validation failed.
#[error("World generation stopped: {0}")]
WorldGen(#[from] WorldGenError),
/// Spatial topology or travel planning failed.
#[error("Simulation stopped: {0}")]
Simulation(#[from] SimulationError),
// /// Anything else we didn't anticipate.
// #[error("Unknown error: {0}")]
// Other(String),

View File

@ -29,8 +29,19 @@ use clap::{Parser, Subcommand};
use crate::{
commands::{
entity_generic::EntitySubCommands, epoch::cli_epoch::EpochCmd, generate::GenCmd,
init::InitCmd, show::ShowCmd, status::StatusCmd,
adjudicate::AdjudicateCmd,
conflict::ConflictCmd,
diffuse::DiffuseCmd,
entity_generic::EntitySubCommands,
epoch::cli_epoch::EpochCmd,
generate::GenCmd,
history::{CommitCmd, LogCmd, PruneFutureCmd, ResetCmd, RevertCmd, SwitchCmd},
init::InitCmd,
safety::{LockCmd, RecoverCmd},
show::ShowArgs,
state::{RestoreCmd, StageCmd, StateDiffCmd},
status::StatusCmd,
travel::TravelCmd,
},
error::AppError,
};
@ -46,6 +57,9 @@ mod success;
#[command(version = env!("EFO_SHORT_VERSION"))]
#[command(name = "efo")]
#[command(about = "Epoch Forge - manage organisations over time")]
#[command(
after_long_help = "EXAMPLES:\n efo init\n efo org add \"Iron Council\"\n efo chr add Aria --stats strength:12\n efo epoch next\n efo status\n\nRun `efo <command> --help` for command-specific examples."
)]
struct Cli {
// /// The level of verbosity
// #[arg(short, long, action = ArgAction::Count, global = true)]
@ -61,19 +75,52 @@ 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),
/// Initialise a new epoch folder.
Init(InitCmd),
/// Recover an interrupted repository write.
Recover(RecoverCmd),
/// Inspect or explicitly break the repository writer lock.
#[command(subcommand)]
Lock(LockCmd),
/// Show unstaged changes, or staged changes with `--staged`.
Diff(StateDiffCmd),
/// Copy worktree changes into the index.
Stage(StageCmd),
/// Restore index or worktree state from its prior layer.
Restore(RestoreCmd),
/// Create an immutable epoch from staged state.
Commit(CommitCmd),
/// Show immutable history newest first.
Log(LogCmd),
/// Switch clean state to an existing epoch.
Switch(SwitchCmd),
/// Apply the inverse of a historical change to the worktree.
Revert(RevertCmd),
/// Permanently move HEAD backward and destroy newer state.
Reset(ResetCmd),
/// Preview or safely back up future history; restore with `--restore`.
PruneFuture(PruneFutureCmd),
/// Gives a very simple status.
Status(StatusCmd),
/// Advance or query the current epoch.
#[command(subcommand)]
Epoch(EpochCmd),
/// Display some elements
#[command(subcommand)]
Show(ShowCmd),
/// Inspect and filter entities or committed epochs.
Show(ShowArgs),
/// Handle characters
#[command(subcommand)]
#[command(visible_alias = "character")]
Chr(EntitySubCommands),
/// Handle organisations and factions
#[command(subcommand)]
#[command(visible_aliases = ["organization", "organisation"])]
Org(EntitySubCommands),
/// Handle events
#[command(subcommand)]
Event(EntitySubCommands),
@ -92,6 +139,12 @@ enum TopLevelCmd {
/// Generate random structures and display them
#[command(subcommand)]
Gen(GenCmd),
/// Plan or advance deterministic spatial travel.
#[command(subcommand)]
Travel(TravelCmd),
/// Preview or advance spatial event diffusion.
#[command(subcommand)]
Diffuse(DiffuseCmd),
}
/// Program entry point.
@ -103,9 +156,11 @@ fn main() -> miette::Result<()> {
env_logger::init();
log::trace!(
"System version: {} ({}{}) {} {}",
"System version: {} ({}{}{}{}) {} {}",
env!("CARGO_PKG_VERSION"),
lib_efo::output::symbol("", "branch:"),
env!("GIT_BRANCH"),
lib_efo::output::symbol("", "@"),
env!("GIT_HASH"),
env!("TOOLCHAIN"),
env!("RUSTC_VERSION"),
@ -134,14 +189,33 @@ 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),
TopLevelCmd::Lock(cmd) => commands::safety::handle_lock(&cmd),
TopLevelCmd::Diff(cmd) => commands::state::diff(&cmd),
TopLevelCmd::Stage(cmd) => commands::state::stage(&cmd),
TopLevelCmd::Restore(cmd) => commands::state::restore(&cmd),
TopLevelCmd::Commit(cmd) => commands::history::commit(&cmd),
TopLevelCmd::Log(cmd) => commands::history::log(&cmd),
TopLevelCmd::Switch(cmd) => commands::history::switch(&cmd),
TopLevelCmd::Revert(cmd) => commands::history::revert(&cmd),
TopLevelCmd::Reset(cmd) => commands::history::reset(&cmd),
TopLevelCmd::PruneFuture(cmd) => commands::history::prune_future(&cmd),
TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd),
TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd),
TopLevelCmd::Gen(cmd) => commands::generate::gen_handler(&cmd),
TopLevelCmd::Travel(cmd) => commands::travel::handle(&cmd),
TopLevelCmd::Diffuse(cmd) => commands::diffuse::handle(&cmd),
TopLevelCmd::Chr(cmd) => commands::entity_generic::handle_entity_commands(
&cmd,
&lib_efo::stats::EntityType::Character,
),
TopLevelCmd::Org(cmd) => commands::entity_generic::handle_entity_commands(
&cmd,
&lib_efo::stats::EntityType::Organization,
),
TopLevelCmd::Event(cmd) => commands::entity_generic::handle_entity_commands(
&cmd,
&lib_efo::stats::EntityType::Event,
@ -152,7 +226,7 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
),
TopLevelCmd::Calamity(cmd) => commands::entity_generic::handle_entity_commands(
&cmd,
&lib_efo::stats::EntityType::Monster,
&lib_efo::stats::EntityType::Calamity,
),
TopLevelCmd::Blocker(cmd) => commands::entity_generic::handle_entity_commands(
&cmd,

View File

@ -8,33 +8,19 @@ use lib_efo::stats::{EntityType, Symbols};
#[derive(Display, Clone, Debug)]
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
pub enum SuccessMessages {
#[display("Switched to epoch {_0} (was {_1})")]
EpochSwitchSuccess(EpochId, EpochId),
#[display("All future events deleted - back to epoch {_0}")]
DeletedAllFutureEvents(EpochId),
#[display("The folder was initialized as an epoch folder")]
FolderInitializedSuccessfully(&'static str),
#[display("Changed the summary of epoch {_0} with: '{_1}'")]
ChangedSummary(EpochId, String),
#[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")]
EpochNextSuccess(EpochId, EpochId),
#[display("Successfully deleted the entity {_0} ({_1} 󰻾[{_2}])")]
#[display("Successfully deleted entity {_0} ({_1} @[{_2}])")]
DeletedEntity(String, String, String),
#[display("Successfully created the entity {_0} ({_1} 󰻾[{_2}])")]
#[display("Successfully created entity {_0} ({_1} @[{_2}])")]
CreatedEntity(String, String, String),
#[display("Successfully edited the entity {_0} ({_1} 󰻾[{_2}])")]
#[display("Successfully edited entity {_0} ({_1} @[{_2}])")]
EditedEntity(String, String, String),
#[display("Showing delta between Epoch ({_0} & {_1})")]
DiffBetweenEpoch(lib_efo::epoch::EpochId, EpochId),
#[display("Added tag {_0} to epoch {_1}")]
TagAdded(String, EpochId),
}
/// Display the success message to stdout

File diff suppressed because it is too large Load Diff

25
docs/README.md Normal file
View File

@ -0,0 +1,25 @@
# Epoch Forge documentation
This documentation describes current executable behavior and labels planned
behavior clearly.
- [Commands](commands.md): verified CLI surface and examples.
- [Repository format](repository.md): files, epochs, compatibility, backup, and recovery.
- [Reversing changes](recovery.md): checkpoints and recovery for every mutation.
- [Architecture](architecture.md): crate responsibilities, data flow, and quality gates.
- [Staging design](staging-design.md): approved Phase 4 state, command, transaction,
and migration contract.
- [TUI design](tui-design.md): approved first-pass scope, interaction, safety,
and accessibility contract.
- [Simulation and world generation](simulation-worldgen-design.md): seeded
fuzzing, roads, movement, diffusion, map rendering, and config packaging.
- [Adjudication/influx, diffusion resolution, and conflict](resolution-conflict-design.md):
implementation contract for tracker issues #9, #8, and #12.
- [Presentation and export](presentation-design.md): remaining buffered,
coherent, saveable output contract for tracker issue #10.
- [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).

41
docs/architecture.md Normal file
View File

@ -0,0 +1,41 @@
# Architecture and development
```text
CLI (`bin_efo`) TUI (`tui_efo`)
│ │
└─────┬──────┘
▼
domain and persistence (`lib_efo`)
│
▼
`.epoch` and `epoch/*`
```
`bin_efo` defines the Clap command tree and presentation. `tui_efo` owns only
its input loop, view state, and terminal presentation. `lib_efo` owns entities,
statistics, identifiers, epochs, naming, and JSON persistence. New behavior
should be a testable library operation with thin CLI and TUI adapters.
The design direction is to make repository paths explicit; replace truncating
writes with temporary-file plus rename; add locking; remove unsafe cache
accessors; separate styling from semantic output; and retain unknown custom
metadata as the model becomes organisation-agnostic.
Phase 4's approved persistence boundary is specified in the
[staging, history, and recovery design](staging-design.md). It separates HEAD,
the index, and the editable worktree, and defines the atomic transaction rules
that implementation must preserve. The sole pre-release repository format is
version 1.0; its structured major/minor discriminator leaves room for explicit
1.x migrations without retaining an unreleased prototype reader.
The [TUI contract](tui-design.md) covers browsing and previewed entity editing.
`EntityDraft` validates forms in the library; `Workspace::apply_entity_change`
checks the editor snapshot and writes the worktree under one transaction lock.
The TUI retains the prior entity for one-step, conflict-checked undo.
Library tests cover parsing, statistics, display snapshots, entity/epoch
behavior, and repository transactions. CLI behavior is covered by subprocess
integration workflows; Tarpaulin excludes those thin adapters because its
ptrace backend cannot reliably attribute child-process execution. Routine CI
should run formatting, all-target workspace tests, strict Clippy, and a release
build. Tarpaulin and `rust_autobadges` remain local significant-release-only
tools. See [AGENTS.md](../AGENTS.md) for contributor rules.

223
docs/commands.md Normal file
View File

@ -0,0 +1,223 @@
# Command reference
Epoch Forge operates on the current working directory; it does not yet search
parent directories. `efo <command> --help` is the authoritative syntax.
## Repository and timeline
- `efo init [--force]` creates the format-1.0 manifest, HEAD, index, worktree,
and `epoch/0/epochinfo.json`. The normal
form requires an empty directory; `--force` permits unrelated existing files
but never overwrites `.epoch` or epoch 0.
- `efo recover` deterministically rolls back a prepared replacement or verifies
a committed one. It is safe to repeat.
- `efo lock inspect` reports writer ownership. `efo lock break --yes` removes
an abandoned lock only after explicit confirmation; run `efo recover` next.
- `efo status [EPOCH_ID]` shows an epoch summary, tags, and entity counts.
- `efo epoch log [-c N]` shows epochs around the current epoch.
- `efo epoch next` creates and checks out the next snapshot. It refuses while
later snapshots exist.
- `efo epoch switch ID_OR_TAG` checks out an existing snapshot without deleting
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.
- `efo prune-future` previews later history; `--yes` moves it to a restorable
backup, removes tags into that future, and makes the next commit use the ID
immediately after HEAD. Restoring the backup restores its allocator and tags.
- `efo reset --hard ID_OR_TAG` previews a destructive rewind. Add `--yes` to
align HEAD, index, and worktree to the target and permanently delete every
newer epoch. This has no built-in undo; prefer `switch` plus `prune-future`
when recovery may be needed.
## Entities
The built-in nouns are `org`, `chr`, `town`, `event`, `calamity`, and `blocker`.
`character` aliases `chr`; `organization` and `organisation` alias `org`:
```text
efo <noun> add [NAME | --rng-name] [OPTIONS]
efo <noun> edit <NAME|@UUID> [OPTIONS]
efo <noun> show [NAME|@UUID]
efo <noun> diff <NAME|@UUID> [--epoch-id ID_OR_TAG]
efo <noun> del <NAME|@UUID>
```
Names match by prefix. `@UUID` is the stable form printed in detailed output;
short UUID prefixes are accepted. Avoid ambiguous prefixes.
Common add/edit options include `--stats key:value ...`, `--position x,y`,
`--duration`, `--bounds`, `--effect`, faction/reach/description/relationship
options, and prestige controls. `edit --delta` adds supplied stats rather than
replacing them. See nested help (for example `efo chr add --help`) for exact
syntax and values. Persistent normalized stats are clamped to `0..=120`;
growth and event/blocker modifiers use `-120..=120`; population remains an
unbounded non-negative count for persistent entities. Entity mutations edit
only the worktree. Use `efo diff`,
`efo stage --all`, `efo stage --world`, or
`efo stage --kind KIND ID...`,
and `efo diff --staged` to prepare history. `efo restore --staged ...` copies
HEAD into the index; `efo restore --worktree ...` copies the index into the
worktree. Both restore modes require either `--all` or an entity kind and IDs.
`efo commit -m MESSAGE` refuses unstaged or empty commits, creates an immutable
epoch using a manifest-last transaction, and realigns all three layers.
`efo log` shows the resulting parent-linked history newest first.
`efo switch ID` requires clean state and changes all layers without reusing
epoch IDs. `efo revert ID` applies that epoch's inverse to the worktree for
review; it can be undone with `restore --worktree --all`. `revert ID --commit`
prints a warning and immediately creates the inverse commit. Overlap with later
changes aborts without mutation. `efo prune-future` previews future epochs,
while `--yes` moves them into a backup. Restore using the exact command printed
after pruning; this also restores the former next-epoch allocator and tags.
After pruning, the next epoch allocator remains monotonic, so removed IDs are
not reused. `efo reset --hard ID --yes` is the explicitly destructive
alternative: it discards transient changes, removes newer epochs without a
backup, removes tags that point to them, and restarts the epoch allocator after
the retained target.
`efo epoch summary` and `efo epoch tag` edit worktree metadata;
`stage --world` selects it. `efo epoch next` requires a clean worktree, includes
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` 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.
## Roads and travel
Spatial changes are preview-first and affect only the worktree with `--apply`:
```text
efo travel road-add Haven Northwatch --speed 180
efo travel road-add Haven Northwatch --speed 180 --apply
efo travel roads
efo travel plan Aria Northwatch --offroad-speed 50
efo travel plan Aria Northwatch --offroad-speed 50 --apply
efo travel tick 3 --apply
```
Routing minimizes integer travel ticks with deterministic tie-breaking. Roads
carry their own speed; disconnected characters fall back to slower direct
travel. Characters have explicit resident, roaming, or travelling state. Use
`efo restore --worktree --all` to discard applied simulation changes.
## Event diffusion
Events propagate from their map position over the same topology. Roads use
their configured speed and direct spatial propagation remains a slower
fallback:
```text
efo diffuse start Plague --road-speed 100 --direct-speed 25 --expires-after 20
efo diffuse start Plague --road-speed 100 --direct-speed 25 --expires-after 20 --apply
efo diffuse tick 3
efo diffuse tick 3 --apply
efo diffuse resolve Plague Haven --level good --characters residents
efo diffuse resolve Plague Haven --level good --characters residents --apply
```
The preview reports each destination's arrival tick and whether it is reached
by road or directly. Persisted frontiers retain an affected set, so applying or
previewing the same tick again cannot reach a town twice. Expired state remains
inspectable and can be restored, staged, or committed like any other worktree
change.
Applied ticks leave newly reached towns pending until the game master resolves
them. `diffuse resolve` shows colocated or linked blockers as protection
context, then previews the town and characters selected by `--characters
none|residents|positioned|both`. Protection never silently chooses an outcome:
use `--disposition applied|dampened|avoided|destroyed`. Avoided targets are
still recorded and cannot be resolved twice. Travelling characters are
conservatively excluded because interpolated route positions are not yet
stored. One `--apply` writes all target effects and resolution records
atomically; normal worktree restore undoes the batch.
## External rolls and game-master adjudication
Epoch Forge does not roll or infer an outcome. The player rolls outside the
tool, then the game master records the result, interpretation, disposition,
and exact stat effects:
```text
efo adjudicate preview Plague --target town:Haven --level bad \
--result "d20=4" --disposition dampened --effect health:-8
efo adjudicate apply Plague --target town:Haven --level bad \
--result "d20=4" --disposition dampened --effect health:-8
efo adjudicate list Plague
```
For the common case, omit result, disposition, and effects:
```text
efo adjudicate apply Plague --target town:Haven --level bad
```
This uses the configured default effects. The embedded policy progressively
dampens its `health:-20` baseline: excellent 0%, good 25%, mid 50%, bad 75%,
worsen 90%, and apocalypse 100%. An external `--config` can replace both the
baseline and scale. Supplying one or more `--effect` options replaces the
defaults completely.
`influx` is a visible alias for `adjudicate`. `applied` uses the supplied
effects in full, `dampened` applies the configured attenuation, and `avoided`
or `destroyed` records zero stat change. Applied rulings are audit records in
the worktree. Use `efo restore --worktree --all` to undo the ruling and its
effects together; audit records cannot be cleared independently from effects.
Each ruling also marks the source event with remaining potency. Later default
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
without creating or changing repository files.
`efo gen world --level event|settlement|region|world --seed N` previews a
deterministic generated world using embedded configuration. `--config PATH`
selects an editable JSON override. `--apply` explicitly replaces only the
worktree; undo it with `efo restore --worktree --all`, or stage and commit it
through the ordinary workflow.
Output is human-readable Unicode, with Nerd Font icons enabled by default. A
portable build replaces those icons with textual/standard-Unicode labels; use
`cargo install --path bin_efo --no-default-features`. Stable JSON output is
planned. A panic is always a bug.

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-22. 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) | 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) | 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. |
| [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Functionally complete: deterministic spread creates pending arrivals; `diffuse resolve` uses adjudication potency, protection context, explicit avoidance/destruction, and stable resident/positioned character selection with atomic restoreable application. | Close the live tracker issue after review; interpolated in-transit positions remain a separate travel enhancement. |
| [#6 HashMap/HashSet](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/6) | Addressed without format churn: `EntityIndex` provides ephemeral UUID/name hash indexes and duplicate-ID detection over the stable vector representation. Repository validation uses the index and hash lookup for relationships. | Rebuild indexes after mutation; never persist them. |
Implementation order is #9's shared resolution engine, the remaining #8
outcomes, then #12 conflicts. #10 presentation work accompanies each slice and
finishes with a complete direct-output migration. Issue #13 remains deferred.

163
docs/presentation-design.md Normal file
View File

@ -0,0 +1,163 @@
# Presentation and export design
This is the remaining implementation contract for tracker issue
[#10](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/10).
`show`, full entity display, and world diff already build strings before the
CLI writes them. The issue is not complete until every command follows one
coherent output boundary and useful reports can be saved without scraping ANSI
terminal output.
## Goals
- Domain/library operations return typed data and never print.
- Command handlers resolve input and choose presentation; renderers never
mutate repositories.
- Each invocation performs at most one stdout write and, when needed, one
stderr write after successful rendering.
- Essential meaning survives `NO_COLOR`, `--no-default-features`, redirection,
narrow terminals, and UTF-8 terminals without Nerd Fonts.
- The same typed report can target terminal text, plain text, or a stable
machine representation without parsing a decorated string.
- `--output PATH` writes atomically and refuses to overwrite unless explicitly
requested. It never changes repository state.
## Layering
```text
lib_efo domain operation
↓ typed result/report
bin_efo presentation model
↓ renderer selected by OutputOptions
String / serializable value
↓ one stdout write or atomic output-file replacement
```
Introduce a small `presentation` module in `bin_efo`; do not make `lib_efo`
depend on terminal crates.
```text
OutputOptions {
format: Human | Plain | Json,
output: Option<PathBuf>,
force: bool,
color: Auto | Always | Never
}
Document {
title: Option<String>,
blocks: Vec<Block>
}
Block = Paragraph | KeyValues | Table | Tree | Changes | Warning | Recovery
```
The document model carries semantics (added/removed/warning/success), not ANSI
codes or Nerd Font glyphs. Human rendering may choose colour and decorative
glyphs; plain rendering uses accessible ASCII/Unicode labels; JSON serializes
the original typed report rather than the human `Document` where possible.
JSON is included here because “printing or saving depending on need” requires
a non-lossy format. Its schema is versioned per report (`schema_version`,
`kind`) and tested. JSON output disables colour and decorative glyphs and emits
no success prose. JSONL remains a later extension for streaming lists.
## CLI contract
Global or consistently flattened options:
```text
--format human|plain|json
--output PATH
--force
--color auto|always|never
```
Defaults preserve today's human terminal experience. When stdout is not a TTY,
`human` automatically suppresses colour but keeps UTF-8 structure. `plain`
avoids decorative icons and ANSI regardless of terminal. Existing
`NO_COLOR` remains honored and wins over `auto`; `--color always` is the only
explicit override.
Writing rules:
- render fully before opening the output path;
- reject repository control paths and an input path used by the command;
- use sibling temporary file, flush, sync when repository-grade durability is
needed, then rename;
- without `--force`, an existing target is an actionable error;
- success/recovery messages go to stderr only when structured output occupies
stdout, otherwise remain part of the human document;
- errors never create or truncate the output file.
## Migration inventory
Priority is determined by risk and reuse, not file order:
1. Safety/destructive previews: `reset`, `prune-future`, recovery, locks.
2. Simulation previews: generation, travel, diffusion, influx, conflict.
3. State/history: status, stage/restore/commit/log/switch/revert, epoch.
4. Entity mutation confirmations and generated-name commands.
5. Legacy library printing (`Displayable::print_full`, `Prettiable` print
helpers, old epoch config helpers) replaced with returned strings or writers.
Tests and debug-only `println!` calls are outside the production inventory.
After migration, CI runs a source check that rejects production
`print!/println!/eprint!/eprintln!` outside the single output sink and process
entry error boundary.
## Information loading
Renderers receive a `ViewContext` assembled once per command:
```text
ViewContext {
repository_summary,
selected_layer,
entity_index,
optional_epoch_metadata,
terminal_capabilities
}
```
This avoids renderers reopening the repository or repeatedly scanning vectors.
It also satisfies the issue's “load many info” goal: entity tables can resolve
links/names, simulation reports can name sources and targets, and historical
views can attach epoch metadata without domain objects performing I/O.
## Coherence rules
- Titles use sentence case; stable IDs always retain an `@` prefix.
- Added/removed/modified markers remain `+`, `-`, `~`; `!` means important.
- Counts and empty states are always explicit.
- Preview documents start with `Preview` and finish with exactly what will or
will not change plus the recovery command.
- Successful mutation documents state the layer changed (`worktree`, `index`,
or committed epoch) and the next useful command.
- Warnings and errors never rely on colour or glyph shape.
- Tables have deterministic column order and rows have stable sort keys.
- Human wrapping is Unicode-width-aware; machine formats never wrap.
## Acceptance gates
- every production command returns/render-writes through one output sink;
- no library production function prints;
- golden tests cover human, portable/plain, and JSON for each report family;
- redirected output contains no ANSI escapes;
- `NO_COLOR` and portable builds retain all semantic labels;
- `--output` success, collision, permission failure, and atomicity are tested;
- JSON schemas round-trip and do not contain rendered terminal strings;
- large lists are bounded or paginated without partial writes;
- display tests use returned buffers, not global stdout capture;
- help documents formats, output files, overwrite behavior, and examples;
- both existing CLI behavior and new simulation previews migrate before #10 is
closed.
## Delivery slices
1. Add `OutputOptions`, the single sink, atomic file writer, and renderer tests.
2. Move safety and simulation previews to typed reports/documents.
3. Move state/history commands and expose plain/JSON formats.
4. Move entity and generation commands; retire production library printing.
5. Add the source-policy check, output-path failure tests, docs, and help
snapshots; close #10 only when the production inventory is empty.

41
docs/recovery.md Normal file
View File

@ -0,0 +1,41 @@
# Reversing changes
Epoch Forge keeps committed HEAD, a staging index, and an editable worktree.
Inspect each recovery operation before choosing the destructive one:
```bash
efo diff # worktree versus index
efo diff --staged # index versus HEAD
efo restore --worktree --all # discard only unstaged changes
efo restore --staged --all # unstage everything
```
## Recovery matrix
| Mutation | Built-in recovery | After `reset --hard` |
|---|---|---|
| Unstaged entity or metadata edit | `restore --worktree` | Restore the complete repository from Git/backup |
| Staged change | `restore --staged`, then optionally restore the worktree | Restore from Git/backup |
| Commit or `epoch next` | `revert`, or switch to an older epoch | Restore from Git/backup if its epoch was destroyed |
| `revert ID` | `restore --worktree --all` | Restore from Git/backup |
| `revert ID --commit` | Revert the inverse commit | Restore from Git/backup |
| `switch` | Switch back to the previous ID/tag | Not applicable |
| `prune-future --yes` | Use the printed `prune-future --restore … --yes` command; epochs, tags, and allocator are restored | Not applicable |
| `reset --hard ID --yes` | None | Restore the complete repository from Git/backup |
Before a hard reset, preserve the complete repository—not only the current
snapshot. Run the preview first:
```bash
efo reset --hard <target>
git add .epoch .efo/ epoch/
git commit -m "checkpoint before abandoning future epochs"
efo reset --hard <target> --yes
```
Never reconstruct UUIDs or tag maps manually when a known-good backup exists.
`efo epoch fsck` is read-only and can identify damage, but deliberately does not
guess repairs.
For a recoverable history rewrite, use `efo switch <target>` followed by
`efo prune-future --yes`; the latter prints the exact restoration command.

69
docs/repository.md Normal file
View File

@ -0,0 +1,69 @@
# Repository, persistence, and recovery
## Layout
```text
.
├── .epoch format version, repository ID, HEAD, allocator, tags
├── .efo/
│ ├── index.json complete staged snapshot
│ ├── worktree.json complete editable snapshot
│ ├── lock present only while a writer owns the repository
│ └── transaction.json present only during/recovering a transaction
└── epoch/
├── 0/epochinfo.json immutable initial world
├── 1/epochinfo.json immutable committed world
└── …
```
`efo init` creates this layout directly. There is no earlier supported format:
Epoch Forge has not made a stable release, so the former prototype layout and
its temporary migration path were removed rather than carried as compatibility
debt.
The manifest currently records format `1.0` as a structured major/minor value.
The application version is separate. Minor format releases (`1.1`, `1.2`, …)
may use explicit migrations while preserving the major compatibility family;
a future breaking layout would increment the major version. Newer minor or
major formats are rejected instead of guessed.
## State and history
Entity and annotation commands edit `.efo/worktree.json`. `efo stage` copies
selected state into `.efo/index.json`; `efo commit` creates a new immutable
epoch from the index and aligns all three layers. `efo restore` always names
which layer it replaces. IDs are monotonic and never reused.
`efo switch` requires clean state and never deletes later history. `efo revert`
places an inverse change in the worktree by default; `--commit` explicitly
creates a new inverse commit and warns before doing so. `efo prune-future`
previews later epochs and, with confirmation, moves them into a restorable
backup rather than deleting them. Pruning removes future-pointing tags and
preserves the monotonic allocator; its backup records both so restoration
reconstructs the original timeline metadata without reusing removed IDs.
`efo reset --hard TARGET --yes` is the exceptional destructive path. It resets
HEAD, index, and worktree, permanently deletes all newer epoch directories,
removes tags that point to them, and permits their numeric IDs to be reused.
There is deliberately no Epoch Forge undo. Run it without `--yes` first to see
the exact scope, and keep important repositories under external version
control or backup.
## Transaction safety and recovery
Writes use an exclusive repository lock and a durable manifest-last
transaction. If a command is interrupted, stop other writers and run:
```bash
efo lock inspect
efo recover
```
Only use `efo lock break --yes` after verifying that the recorded process no
longer owns the repository, then immediately run `efo recover`. Recovery either
rolls back a prepared operation or verifies a committed one and is safe to
repeat.
Keep important repositories in Git or another backup system. For corruption,
copy the complete directory before investigation and run the read-only
`efo epoch fsck`; it reports damage but never guesses a repair.

View File

@ -0,0 +1,303 @@
# Adjudication (“influx”), diffusion resolution, and conflict design
This is the implementation contract for tracker issues
[#9](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9),
[#8](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8), and
[#12](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/12).
It distinguishes the spatial propagation already implemented from the outcome
resolution still required. No command described here is implemented merely by
appearing in this document.
## Product contract
An **adjudication** (formerly called an “influx”) is a player-made roll outside
Epoch Forge. The game master interprets that result, chooses its level,
disposition, targets, and exact effects, then uses Epoch Forge to preview and
record the ruling. Epoch Forge must never invent, reroll, or reinterpret it.
Adjudication is inspectable and subordinate to the Git-like workflow:
- preview is the default and never writes;
- `--apply` changes only the complete worktree snapshot under the repository
writer lock;
- staging and committing remain explicit separate operations;
- previews state the external result, master note, selected targets,
disposition, policy, and exact projected changes;
- replaying the same explicit ruling against the same state produces the same
report and semantic world;
- applying an already-recorded resolution is idempotent;
- users can discard applied work with `efo restore --worktree --all`, or retain
it through `stage` and `commit`;
- adjudication never deletes a target entity. A master-selected `Destroyed`
disposition marks the source event/conflict exhausted; entity deletion is a
separate explicit operation.
The model remains setting-agnostic. “War”, “plague”, “merger”, “strike”, and
“market shock” are labels over the same participant, explicit ruling, and
effect primitives. Fantasy-specific unit classes or damage types do not belong
in the core.
## Shared adjudication recorder
### Influx levels
`AdjudicationLevel` is a stable serialized enum and a Clap value enum. It is
assigned by the master; it does not imply a numeric roll or automatic effect:
| Level | Intent |
|---|---|
| `excellent` | exceptional beneficial ruling |
| `good` | beneficial ruling |
| `mid` | weak, neutral, or mixed ruling |
| `bad` | harmful ruling |
| `worsen` | strongly harmful/escalating ruling |
| `apocalypse` | extreme harmful ruling |
The names are compatibility vocabulary from the issue, not hard-coded story
meaning. Parsed aliases include `medium` for `mid` and `worse` for `worsen`,
while serialized values remain canonical.
### Inputs and stable records
The library owns serializable types; CLI code only resolves selectors and
renders reports:
```text
AdjudicationSpec {
level, disposition, source_event,
external_result, note, chosen_effects, policy_id
}
AdjudicationRecord {
id, source, target, tick_or_round,
level, disposition, external_result, note,
before_and_after_changes, policy_id
}
Disposition = Applied | Dampened | Avoided | Destroyed
```
Records use stable content-derived UUIDs and are ordered by
`(tick_or_round, source, target, id)`. Identical adjudications therefore cannot
be accidentally applied twice. No RNG exists in this subsystem.
Chosen effects are typed field/stat deltas, not formatted text. Every previewed
change carries before/applied-delta/projected-after values and the normal
clamping policy.
Application verifies the target still has the recorded before value; stale
state aborts the whole transaction with recovery guidance.
### Disposition and attenuation
The game master explicitly chooses the disposition:
- `Applied`: apply every chosen effect in full;
- `Dampened`: apply chosen effects using the configured attenuation;
- `Avoided`: record the target's avoidance and apply no effects;
- `Destroyed`: stop/exhaust the source and apply no target effects.
Epoch Forge applies no hidden inference. Protection and blockers are context
shown to the master, not an automatic roll. Invalid stat names, duplicate
effects, excessive effect counts, stale targets, and unknown policies fail
before mutation.
Interpretation of `Destroyed` depends on the source:
- for an incoming event, propagation stops and the event is marked exhausted;
- for a conflict participant, it means removed from that conflict, not deleted
from the repository;
- for a target, entity deletion is never implicit.
`Dampened` writes an attenuation mark to the event/conflict state. It does not
edit the source's base stats.
### Configuration
`lib_efo/assets/simulation/default.json` contains a versioned
`AdjudicationConfig` independent of repository and worldgen versions. It owns
only policy and safety—not game-master decisions:
- dampened attenuation;
- maximum effects, records, and text sizes;
- a stable policy identifier.
The binary embeds canonical offline defaults and accepts `--config PATH`.
External config is a complete replacement, not a partially merged surprise.
Errors identify the file and JSON field. Release packaging should add this file
beside the existing worldgen configuration.
## Issue #9: adjudication surface
Proposed CLI:
```text
efo adjudicate preview EVENT --target town:Haven --level bad \
--result "d20=4" --disposition dampened --effect health:-20
efo adjudicate apply EVENT ...
efo adjudicate list [EVENT]
efo influx ... # visible legacy/domain alias
```
The concise common case needs only the source, target, and level:
```text
efo adjudicate apply Plague --target town:Haven --level bad
```
`preview` and `apply` are intentionally separate words; `apply` still prints
the complete preview before its success line. `--result` is descriptive text,
not a value the program interprets. Both it and `--disposition applied` have
safe defaults. `--effect` is repeatable; when omitted, the policy's base
effects are scaled progressively from excellent (most dampened) through
apocalypse (full effect). Any explicit effect list replaces that fallback.
Audit records are not independently clearable: removing a record while leaving
its effects would make the world misleading. Restore the worktree before a
commit, or use the normal historical revert workflow after a commit.
The implemented single-target form supports stable IDs and unambiguous name
prefixes for every stored entity kind. Semantic groups (`towns`, `characters`,
`organisations`, `reached`) remain part of the diffusion-integration slice;
`reached` will consume the affected set of an event's diffusion state.
Acceptance gates:
- all six levels parse, serialize, and appear in help;
- the same explicit ruling/policy/state yields byte-equivalent typed reports;
- applied, dampened, avoided, and destroyed dispositions are covered;
- records prevent accidental reapplication and stale application is atomic;
- invalid config and excessive scope fail before allocation/mutation;
- preview leaves repository bytes unchanged; apply is restoreable;
- source attenuation persists without corrupting source entity statistics;
- tests prove that the program never generates a roll or an unrequested effect.
Implemented source behavior: every applied adjudication stores the event's
remaining potency separately from ordinary entity statistics. The configured
level multiplier can only maintain or reduce that potency. Later policy-default
effects include the remaining potency in their attenuation, while explicit GM
effects remain exact overrides. A `destroyed` ruling sets potency to zero,
expires an existing frontier, and prevents a new diffusion from starting.
`adjudicate list EVENT` and diffusion output expose the current percentage.
## Issue #8: finish diffusion resolution
The implemented `DiffusionState` stores origin, elapsed ticks, expiry, ordered
town frontier, affected towns, pending arrivals, and target-to-adjudication
resolution records. The character policy is selected per resolution. Destroyed
source state and diffusion expiry together provide the stop reason; the full
adjudication remains in its durable audit record instead of being duplicated.
When a tick reaches a town, `diffuse resolve` now:
1. derive town and character targets according to `character_policy`;
2. show blockers/protection as context for the master's ruling;
3. apply the explicit adjudication to each selected stable target;
4. record `Avoided` targets as resolved, preventing repeated application;
5. stop the event if its resolution is `Destroyed`;
6. include route, protection source, external result, master note, and projected effects in
the tick report.
Protection is explicit and generic. Positioned `Blocker` entities and typed
links are shown to the master as context. A protected town is not silently
omitted: the report says which blocker/link is relevant and records whether
the master ruled that the result was avoided or dampened.
Characters are resolved in stable UUID order. Residents use mobility state;
positioned characters use exact position/town association. The implemented
policy conservatively excludes in-transit characters until interpolated travel
positions exist; help and reports say so.
Acceptance gates add tests for protected and unprotected towns, resident and
roaming characters, destroyed propagation, expiry before arrival, zero-tick
replay, large tick convergence, and deterministic output under shuffled vector
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 {
id, name, kind, sides, round, status,
location, ruleset_id, objectives, records
}
ConflictKind = Fight | War
ConflictStatus = Planned | Active | Stalemate | Won { side } | Ended
ParticipantRef { entity_type, id, side, committed_weight }
```
Any stored entity type may participate. Duplicate participants, empty sides,
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, single-resolution conflict. A war is persistent
and advances in explicit rounds. Neither automatically creates/deletes normal
entities. Resolution applies explicit or configured-default stat effects;
rulesets that generate ordinary Event entities remain a future extension.
Implemented CLI:
```text
efo conflict start NAME --kind fight --side red:town:Haven --side blue:org:Guild
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
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. 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,
identical-ruling replay, insertion-order independence, clamping, stale-state refusal,
restore/stage/commit/revert, and malformed persisted conflict state.
## Persistence and compatibility
Additive state belongs in `EpochInfo` with `#[serde(default)]`, as roads,
mobility, and diffusion already do:
```text
resolution_records: BTreeMap<Uuid, ResolutionRecord>
conflicts: BTreeMap<Uuid, ConflictState>
```
Never persist RNG objects, hash maps with unstable iteration, display strings,
or pathfinder caches. Workspace validation checks all cross-references,
record uniqueness, monotonic conflict rounds, resolved-target links, ruleset
IDs, and configured safety limits. `fsck` exercises the same validation for
every historical epoch.
These additions remain backward-readable through defaults while the project is
unreleased. Freeze the exact format before the first release; after that point,
any semantic reinterpretation requires a 1.x migration fixture and previewed
upgrade path under issue #17.
## Delivery slices
1. **Corrected and complete:** add and validate `AdjudicationConfig`, all six
master-assigned levels, explicit dispositions/effects, stale-checkable typed
reports, and reproducible release packaging; no commands or mutation.
2. **Complete:** add pure adjudication preview/application tests for every
disposition and prove no roll/effect is invented.
3. **Complete:** persist idempotent adjudication records and expose
preview/apply/list, with `influx` as a visible alias.
4. **Complete:** ticks create pending arrivals; source attenuation affects
future defaults; resolution atomically covers towns and selected
resident/positioned characters, explains positioned/linked protection,
records avoided targets, and stops diffusion when destroyed.
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.

61
docs/roadmap.md Normal file
View File

@ -0,0 +1,61 @@
# Roadmap
The detailed backlog is [AGENTS-TASKS.md](../AGENTS-TASKS.md).
## Implemented foundation
- Local CLI repository with full-world epoch snapshots.
- Five entity collections with add/edit/show/diff/delete operations.
- Statistics, positions, duration/effects, selected relationships, and random
generation.
- Timeline advance, switch, log, tags, summaries, and explicit future deletion.
## Current release target
The trustworthy-foundation milestone is complete: documentation now reflects
the executable, user-triggerable panic paths found in the audit are guarded,
initialisation is safe, `show`, read-only `fsck`, and world diff are real,
individual files are persisted atomically, and CLI workflows are covered.
The dependable-daily-CLI milestone is complete: naming and aliases are
consistent, organisations are managed directly, help includes examples,
Nerd Font output has a portable build option, relationships are type-validated,
and every mutation has documented and tested recovery guidance.
The [Phase 4 format contract](staging-design.md) is implemented. Native format
1.0 initialization, locking, recovery, staging, immutable commits, revert, and
recoverable pruning are implemented. The unreleased prototype reader and its
temporary migration were removed before the first release. Future compatible
changes use 1.x versions and regain explicit migration tooling when needed.
Organisation-agnostic custom fields and types follow, with unknown-field
retention designed before that format change.
The [TUI browser](tui-design.md) now includes search, layer browsing, responsive
layouts, and guarded terminal handling. Its entity editor supports previewed
worktree creation/edits and conflict-checked one-step undo through the library.
Interactive staging, commits, relationships, and general deletion remain later
workflows.
The simulation track has deterministic world generation, road topology,
character travel, and spatial event frontiers. The next approved work is the
[shared adjudication and conflict design](resolution-conflict-design.md):
player-roll adjudication first, then protected-town/character diffusion
outcomes, then fight/war. The
[presentation design](presentation-design.md) is implemented alongside those
slices so every new preview is buffered and exportable rather than adding more
direct terminal printing. PNG map rendering follows those tracker issues.
## Proposed stretch goals
1. Shell completions and generated man pages.
2. Stable JSON/JSONL output and query/filter expressions.
3. Extend the TUI entity editor with previewed staging and commit workflows.
4. Named timeline branches with merge/conflict handling.
5. Setting templates for empires, companies, guilds, and nations.
6. Validation/simulation hooks before committing an epoch.
7. Optional signed snapshots and append-only audit records.
8. Deterministic seeded generation/simulation.
9. A scripting/plugin boundary after persistence is stable.
Completions and structured output are the best first stretch investments. A TUI
and branching should wait until staging, revert, and locking are reliable.

View File

@ -0,0 +1,120 @@
# Simulation, world generation, and map design
This design connects four related capabilities: spatial event diffusion,
character travel, visual maps, and data-driven fuzz/world generation. They
share coordinates and topology but remain separate library modules so testing,
simulation, and rendering do not become one irreversible command.
## Delivery order
1. **Deterministic world generation.** Add a versioned configuration, embedded
defaults, external overrides, seeded generation from one event through a
complete world, validation, previews, and explicit worktree application.
2. **Road and mobility topology.** Add stable road edges between positioned
places. Characters are either resident at a place or travelling. A route
uses roads when available and can fall back to slower straight-line travel.
3. **Event diffusion.** Each tick derives an event frontier from its origin,
reach, speed, remaining duration, and configured terrain/road multipliers.
Roads accelerate diffusion; direct spatial diffusion remains possible and
slower. A seeded tick must be reproducible and previewable before commit.
4. **PNG rendering.** Render roads, places, characters, events, and diffusion
fronts onto an optional user-supplied PNG. Without a base image, create a
configured blank canvas. Rendering is read-only and writes to a named output
path atomically.
## World-generation configuration
The canonical default lives at `lib_efo/assets/worldgen/default.json` and is
compiled into `lib_efo`. This guarantees that tests and installed binaries work
offline. `--config PATH` loads an editable replacement; configuration errors
name the JSON path and never silently fall back to defaults.
The configuration owns generation ranges, name/template pools, map dimensions,
road density, mobility ratios, and simulation coefficients. It has its own
schema version, separate from repository format and application version.
Unknown future fields should be retained or rejected deliberately once custom
metadata lands; they must never be silently misinterpreted.
Generation levels are cumulative:
- `event`: one positioned event;
- `settlement`: a town, residents, and local events;
- `region`: several connected settlements, roads, organisations, and events;
- `world`: the complete configured population and topology.
Every generation accepts and prints a `u64` seed. The same binary,
configuration bytes, level, and seed must produce byte-equivalent semantic
world state. Generated UUIDs come from the seeded generator rather than the OS.
Preview is the default; `--apply` replaces only the worktree through the normal
transaction layer. Staging and committing remain separate user decisions.
## Spatial model
Places and events have Cartesian positions. A road is an undirected edge with
a stable ID, two place IDs, distance/cost, and optional tags. Duplicate,
self-referential, dangling, and non-place edges are invalid.
A character has an explicit mobility state:
- `Resident { place }` is tied to a positioned place;
- `Roaming { position }` can travel directly;
- `Travelling { from, to, progress, route }` records recoverable progress.
Route selection minimizes configured travel time. Road segments use their
speed multiplier; a direct fallback uses Euclidean distance and the slower
off-road speed. Simulation stores intent/progress, not transient pathfinder
caches, so old state remains interpretable.
Event diffusion uses the same weighted graph plus direct distance. It records
which entities/places have already been affected to avoid accidental repeated
application. Preview output explains why a target is reached and which route
or direct distance was used.
Spatial arrival is implemented. Influx-aware outcomes, protection, character
targeting, and fight/war share the follow-on contract in
[Influx, diffusion resolution, and conflict](resolution-conflict-design.md).
## Map rendering
The repository may reference a base map path plus coordinate bounds, but never
embeds arbitrary image bytes into snapshots. `efo map render --base map.png
--output world.png` overrides the configured base. With no base, the renderer
creates a blank RGBA canvas using configured dimensions and background colour.
Essential meaning must not depend on colour: markers differ by shape and have
optional labels. Roads and diffusion fronts use distinct line patterns. The
renderer validates coordinate bounds and image limits before allocation and
writes to a temporary sibling before rename.
## Packaging and releases
Embedded defaults are authoritative for a binary. Tagged releases may also
attach `epoch-forge-worldgen-config-vX.Y.zip` containing the editable JSON,
schema notes, and checksum. Runtime fetching is opt-in only; local embedded
operation remains the default.
The public Gitea API exposes release asset uploads at
`/api/v1/repos/idle-org/epoch_forge/releases/{id}/assets`. The existing
`v0.1.0` release already has binary assets and `SHA256SUMS`, so the config zip
can follow that mechanism once the Jenkins credential ID used by the release
job is known. Routine CI must validate/package the config but must not publish
or run release-only badge tooling.
The repository provides `scripts/package-worldgen-config.sh VERSION` and
`scripts/package-simulation-config.sh VERSION`; both create reproducible
archives from embedded defaults. The explicit
`scripts/upload-worldgen-config.sh TAG ZIP` helper can upload either archive.
It requires `GITEA_TOKEN`; Jenkins should bind its existing release credential
to that environment variable only inside a tag-release stage. It is never
invoked by the routine Jenkinsfile.
## Safety and test gates
- Property tests generate many seeds and validate IDs, links, bounds, roads,
and deterministic replay; failures print the seed and config checksum.
- Fuzz targets parse configurations and exercise generation, route finding,
diffusion, and rendering with strict size limits.
- Simulation and generation never write unless explicitly applied.
- Applying generated state uses the workspace transaction and is reversible
with `efo restore --worktree --all` until staged.
- PNG rendering cannot mutate repository state or overwrite input maps.

152
docs/staging-design.md Normal file
View File

@ -0,0 +1,152 @@
# Staging, history, and recovery design
Status: **implemented on 2026-09-21** after approval on 2026-09-20. This is the
Phase 4 persistence and recovery contract.
The goal is a familiar Git-like workflow without pretending that Epoch Forge
is Git. A repository has one editable timeline, every meaningful change can be
inspected before it becomes history, and ordinary mistakes are reversible from
the CLI.
## State model
Version 2 repositories have three intentionally separate states:
1. **HEAD** is the immutable committed snapshot at
`epoch/<id>/epochinfo.json`.
2. **Index** is the complete proposed next snapshot in `.efo/index.json`.
3. **Worktree** is the complete editable snapshot in `.efo/worktree.json`.
Complete snapshots keep recovery understandable and avoid reconstructing state
from a fragile chain of patches. Entity-level staging copies selected entities
between snapshots; it does not change the on-disk representation into partial
patches. Every snapshot carries a schema version and repository identity.
The root `.epoch` manifest remains the small source of repository identity and
HEAD selection. Version 2 adds `format_version: 2` and a monotonic
`next_epoch_id`; existing identity, current epoch, version, and tag information
is retained. Epoch IDs are never reused, including after old future history is
pruned.
Transient state lives under `.efo/`:
```text
.epoch repository manifest and commit point
.efo/index.json staged complete snapshot
.efo/worktree.json editable complete snapshot
.efo/lock exclusive writer ownership
.efo/transaction.json recoverable in-progress operation journal
epoch/<id>/epochinfo.json immutable committed snapshots
```
## Command contract
Commands use both plain text and decorative symbols: symbols and colour may
reinforce meaning, but never carry meaning alone.
- `efo status` reports HEAD plus staged and unstaged changes separately. It
names entity kind and ID and gives the next useful command.
- `efo diff` compares index to worktree. `efo diff --staged` compares HEAD to
index. Output is deterministic and field-oriented; `--no-color` remains
readable and scriptable.
- `efo stage --all` copies the complete worktree to the index. Entity selectors
(`--kind <kind> <id>...`) copy only those entities, including deletion.
`efo stage --world` selects world-level metadata. Invalid or ambiguous
selectors change nothing.
- `efo restore --staged ...` copies selected state from HEAD to the index.
`efo restore --worktree ...` copies from the index to the worktree. One layer
flag is mandatory, and the same entity selectors and `--all` are supported.
This explicitness prevents accidental data loss. `unstage` may exist only as
a documented alias for `restore --staged`.
- `efo commit -m <message>` validates the index, creates one immutable epoch,
advances HEAD, then makes index and worktree equal to the new HEAD. An empty
commit is rejected with guidance. Commit messages are required and stored as
snapshot metadata.
- `efo epoch next` remains the simulation-oriented convenience operation. It
requires no unstaged changes, advances time in the index, validates it, and
commits it as one transaction. Already staged changes are included and shown
in the confirmation summary.
- `efo log` displays newest-first immutable history with epoch ID, in-world
date, message, and tags. Stable plain output is available independently of
Nerd Fonts and colour.
- `efo switch <epoch>` changes HEAD only when index and worktree are clean, then
resets both transient snapshots to the selected commit. `--force` is not a
shortcut; users must explicitly restore or commit first.
- `efo revert <epoch>` computes the inverse of that epoch relative to its
predecessor and applies it to the current worktree for review. `--commit`
explicitly stages and commits that inverse, after warning that HEAD is not
being moved backward. It never deletes history. Conflicts abort without
changing any layer and list affected fields.
- `efo prune-future` is the recoverable history-removal operation. It always
shows a dry-run, requires `--yes`, preserves the monotonic ID allocator, and
leaves a backup containing the epochs, allocator, and removed tags so the
complete future can be restored without reusing removed IDs.
- `efo reset --hard <epoch>` is a separate, deliberately destructive escape
hatch modelled after Git. It previews by default and requires `--yes` to
discard transient state, move HEAD, delete newer epochs and their tags, and
rewind the allocator. Recovery requires Git or another external backup.
Mutating commands refuse to proceed with an invalid layer. Errors state what
happened, what was left unchanged, and the safest recovery command.
## Atomicity and crash recovery
All mutations use one repository transaction:
1. Create the writer lock exclusively.
2. Resolve the repository once, read all inputs, and validate preconditions.
3. Write replacement files into a transaction directory on the same
filesystem, flush them, and record old/new hashes plus ordered renames in
`.efo/transaction.json`.
4. Rename immutable epoch data first, transient snapshots second, and `.epoch`
last. The manifest rename is the commit point.
5. Flush affected directories, verify hashes and invariants, remove the journal,
then release the lock.
Before the commit point, recovery rolls back transient replacements. After it,
recovery finishes the recorded operation. `efo recover` performs that decision
deterministically and explains it before changing files; normal commands refuse
to mutate a repository with an unfinished journal. Re-running recovery is safe.
Readers may operate while no journal exists. Only one writer is allowed. The
lock records repository UUID, PID plus process-start token, hostname, command,
and creation time. A lock is never considered stale from age alone. `efo lock
inspect` explains ownership; `efo lock break` requires proof that the local
process is gone or an explicit confirmation for a remote/unverifiable owner.
## Format evolution
This layout is the initial pre-release format `1.0`; the discarded prototype
layout has no compatibility reader. The manifest stores separate major and
minor numbers. When a later `1.x` format needs conversion, migration must be
explicit, previewable, validated, backed up, transactionally committed, and
tested with fixtures before that release ships. No migration command is
advertised while there is only one supported format.
## Compatibility invariants
- Existing epoch contents, IDs, tags, dates, entity IDs, and relationships must
not change during a future migration.
- Unknown fields survive load/save and future migration once the custom-field model is
introduced; Phase 4 must not reserve a representation that prevents this.
- Repository discovery remains independent of the current working directory.
- Every selector is stable by entity ID; display names are never identity.
- Machine-readable output will be versioned separately from human presentation.
- Branching, merging, and remote synchronization are deferred. The format may
gain parent references now, but the CLI remains a single linear timeline.
## Approval checklist
Approval of this design confirms these product choices:
- direct entity edits modify the worktree;
- the index is a complete snapshot with entity-level selection;
- commits are immutable, linear, and use never-reused monotonic IDs;
- restore always names the layer it may overwrite;
- revert creates new history and aborts on conflicts;
- destructive pruning requires a preview, confirmation, and backup;
- future 1.x migrations are explicit, validated, backed up, and reversible.
Implementation proceeded in small commits: format types, transaction/locking
infrastructure, state/diff/staging, commit/log/revert, compatibility cleanup,
and full validation.

189
docs/tui-design.md Normal file
View File

@ -0,0 +1,189 @@
# TUI browser, editor, and release contract
`efo-tui` is a separate terminal interface over `lib_efo`. It browses
all six entity collections in HEAD, index (staged), and worktree (editable)
state and creates/edits entities in the worktree with explicit save previews.
The CLI remains the complete interface for staging, commits, history,
relationships, comparison, and recovery. No repository format changes are introduced by the browser.
## Running
```bash
cargo install --locked --path tui_efo
efo-tui --repository /path/to/world
# From a repository root:
efo-tui
# Monochrome (NO_COLOR also works):
efo-tui --no-color
```
The path must identify a repository root; parent-directory discovery is not
performed. Both stdin and stdout must be interactive terminals. `--help` and
`--version` also work when redirected. For scripts use `efo status` and
`efo show`.
## Browsing
The header reports HEAD, staged and unstaged changes, writer-lock state, the
viewed layer, and its world summary. Start in the worktree. Press `1`, `2`, or
`3` to browse HEAD, index, or worktree. Collection counts reflect the viewed
layer. Entities sort by lowercase name, then stable UUID, and show a shortened
UUID beside their name. Details default to a formatted view with the full UUID,
description, properties, metadata, and statistics. Bold headings, aligned
labels, and indented nested fields make events and other entities readable.
Press `v` to switch between formatted details and the complete, indented raw
JSON. The panel title identifies the mode. Switching resets detail scrolling to
the top, preserves the selected entity and layer, and keeps the chosen mode
while navigating or reloading during the session. Both modes wrap and scroll.
Switch to an earlier layer to inspect an entity removed from the worktree.
Use `efo diff` or `efo diff --staged` for a complete change comparison.
Search applies to the current collection in every layer. It matches name and
description using Unicode lowercase matching, or any substring of the UUID
(with or without `@`). This is literal substring matching, not a query language
or accent-insensitive search. Press `/`, edit the query, and press Enter to
keep it. An empty query clears the filter; Escape restores the previous query.
While editing, ordinary character keys enter text instead of invoking commands.
| Key | Action |
| --- | --- |
| `Tab`, `Shift-Tab`, `h`/`l`, left/right | Cycle focus: collections, entities, details |
| up/down, `j`/`k` | Select a row or scroll details/help |
| `Home`, `End` | First/last row or start/end of details/help |
| `PageUp`, `PageDown` | Move by approximately one visible page |
| `/` | Edit the search filter; Backspace removes a character |
| `Enter`, `Esc` during search | Keep filter / restore previous filter |
| `1`, `2`, `3` | View HEAD / index / worktree |
| `v` | Toggle formatted / raw JSON details |
| `a`, `e` | Add to the current collection / edit the selected entity (worktree only) |
| `u` | Preview undo of the last TUI save in this session |
| `r` | Reload from disk, preserving selection by UUID when present |
| `?`, `!` | Open help and the last reload diagnostic |
| `?`, `!`, `q`, `Esc` in help | Close help |
| `q`, `Esc` outside help/search | Quit |
| `Ctrl-C` | Quit the browser/help/search; cancel a form or undo confirmation |
At widths of 100 columns and above, the browser shows three panels. Narrower
terminals show the focused panel at full width; Tab cycles between them. The
minimum usable size is 32×10. Smaller sizes show resize advice. Details wrap
within their panel and scrolling stops at the last page, including after a
resize. Help and diagnostics scroll independently.
Focus, selection, and repository state use text and reverse video as well as
optional colour. No Nerd Font is required. `--no-color` or the presence of
`NO_COLOR` disables application colours while retaining these selection cues.
## Snapshot and failure behavior
The browser reads a snapshot on startup and refreshes only on `r`; external
changes never silently move the selection. Successful reload and layer changes
keep the selected UUID when it remains in the filtered collection, otherwise
clamp to an available row. A failed reload keeps the last loaded snapshot and
sets a visible stale-data message. Press `!` and scroll to read the full error,
including its path and recovery advice; fix the problem and retry with `r`.
Unsupported versions, corrupt data, and unfinished transactions fail startup
before raw mode is enabled. A writer lock is displayed, never broken. Use
`efo lock status`, `efo status`, or `efo recover` when appropriate. See
[recovery](recovery.md) for the CLI safety workflows.
## Architecture and verification
The binary owns argument parsing, terminal setup, key mapping, view state, and
Ratatui rendering. `lib_efo::workspace::Workspace` owns repository loading and
validation and entity-draft parsing. No command changes the process working
directory. `Workspace::apply_entity_change` holds the writer lock across a fresh
read, comparison of manifest/index/worktree with the editor snapshot, validation,
and the existing journalled write operation. It writes only the worktree and
updates the browser snapshot only after success. Ratatui's rendered-line measurement bounds wrapped scrolling; its
`unstable-rendered-line-info` feature is enabled against the locked version.
A terminal guard restores raw mode, cursor visibility, and the alternate screen
on normal exit and application errors. The panic hook restores an active
terminal before printing the panic, and does not emit terminal controls before
terminal setup. Ctrl-C takes the same guarded exit path. Forced process kills
cannot run cleanup.
Tests cover search, navigation, layer/reload identity, corrupt reload recovery,
scrolling, responsive layouts, monochrome rendering, and noninteractive startup.
The release gate includes workspace formatting, tests, strict Clippy, default
and portable builds, plus a pseudo-terminal navigation/restoration smoke test. On Unix, run it with:
```bash
cargo build -p efo-tui --locked
python3 tui_efo/tests/terminal_smoke.py
```
The smoke check uses a temporary copy of the curated example. It verifies
read-only browsing, creation, multiline paste, save previews, editing, draft
cancellation, exact entity undo, unchanged HEAD/index, and terminal restoration
on `q` and Ctrl-C.
## Creating and editing entities
Select the collection (characters, towns, events, calamities, organisations, or
blockers), press `3` for the worktree, and press `a` to add. To edit, select an
entity and press `e`. HEAD and index browsing stays read-only: switch to the
worktree explicitly before opening a form.
The form has seven fields: name, multiline description, exact position, duration,
effect mode, bounds, and absolute statistics. Wide terminals show a field list;
narrow terminals show the active field. Newly created entities have zero stats,
a new stable UUID, and type-specific duration/effect/bounds defaults (events
start with one turn and `todo` effects). UUID, type, and existing relationships
are preserved while editing; use the CLI for relationship changes.
| Form key | Action |
| --- | --- |
| `Tab` / `Shift-Tab`, up/down | Next / previous field |
| left/right, `Home` / `End` | Move the text cursor |
| Backspace / Delete | Remove the previous / next character |
| `Ctrl-U` | Clear the active field |
| Enter | New line in description; next field elsewhere |
| Paste | Insert text; multiline descriptions supported |
| `Ctrl-S` | Validate and preview the exact worktree change |
| `y` in preview | Save the previewed change |
| `n` / `Esc` in preview | Return to the draft |
| `Esc` / `Ctrl-C` in form | Cancel; changed drafts require `y` to discard |
Names must be non-empty and unique (case-insensitively) within their collection.
Position uses exact integer `x,y` coordinates, including negative coordinates.
Duration accepts `permanent`, `done`, or a non-negative number of turns. Effect
accepts `recurring`, `when-present`, `todo`, or `done`. Bounds use `min:max`, with
the minimum no greater than the maximum. Statistics use the full field names
shown in the form and whitespace-separated `field:value` pairs. These are
absolute integer values, including aggregates; omitted fields stay unchanged,
and no randomisation or automatic aggregate recalculation occurs.
Preview shows the affected entity/type, worktree layer, and before/after values.
Scroll with arrows, PageUp/PageDown, or Home/End. Saving clears the browser search
so the saved entity remains visible. It does not stage or commit. Use
`efo diff`, `efo stage`, and `efo commit` for the rest of the workflow.
A save failure retains the draft and gives a scrollable error. Locks are never
broken automatically; use `efo lock status`. Interrupted transactions require
`efo recover`; then inspect the worktree before retrying, since recovery can
complete an already-written save. If another process changed manifest, index,
or worktree while the form was open, the save is refused. Cancel the draft,
reload with `r`, and reopen the entity to edit the current state.
## Undo and recovery scope
After a successful save, `u` previews undo and `y` confirms it. Undo restores the
exact previous entity, including any edits that were already unstaged when the
form opened, or removes an entity just created by the TUI. Other entities,
HEAD, and index are unchanged. Any intervening repository change refuses undo;
reloading does not bypass this check. Use `efo status` / `efo diff` to review
such changes.
Undo is **one step, in this TUI session only**. A later successful save replaces
the prior undo record; exiting loses it. For a durable recovery point, stage
and commit valuable work before continuing to edit. The CLI's
`efo restore --worktree --kind KIND @UUID` restores that entity from the index,
which discards all its unstaged edits and is not equivalent to TUI undo.
See [recovery](recovery.md).
Stage/unstage, commit, relationship editing, general deletion, transaction
recovery, and future pruning remain CLI operations. Additional interactive
writes require explicit previews, recovery guidance, and tests through the
library transaction operations.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,15 @@
{
"format_version": {
"major": 1,
"minor": 0
},
"repository_id": "5834208c-09ff-4fe9-b202-034652c3d485",
"epoch_id": {
"id": 1
},
"next_epoch_id": {
"id": 2
},
"version": "0.1.0",
"tags": {}
}

View File

@ -0,0 +1,34 @@
# Draän example world
This is a ready-to-use Epoch Forge repository built from the local Ravenous
development material. It is both a realistic regression fixture and a base
world that can be copied elsewhere and changed freely.
```sh
cp -a examples/ravenous-draan /tmp/my-draan
cd /tmp/my-draan
efo status
efo show
```
The checked-out state contains the known settlements shown on `map.png`, key
organisations, roaming hunters, representative creatures and calamities, and
several active world events. Positions use map percentages (`0..100`) from the
top-left corner, so they remain meaningful at any rendered resolution.
The repository includes a committed baseline and a clean worktree/index. Make
an epoch before experimentation, or edit and use the ordinary `stage`,
`restore`, `commit`, `switch`, and `revert` workflows.
## Source note
Names, descriptions, coordinates, and `map.png` were adapted from the Ravenous
development sources supplied alongside this checkout by Dandaedre. The source
tree is intentionally ignored because it is working material; this curated
fixture is tracked. The supplied Ravenous notice reserves setting lore and the
map and describes artwork as provisional, so this example must not be treated
as independently reusable or redistributable game content without the rights
holder's permission.
The map was inspected when this fixture was assembled: it is a 3840×2160 map
of the known Draän regions, with a 0–500 km scale and labelled settlements.

View File

@ -0,0 +1,18 @@
{
"epoch_id": {
"id": 0
},
"parent_epoch": null,
"commit_message": "",
"rng_seed": 0,
"tags": {
"inner": []
},
"summary": "",
"events": [],
"characters": [],
"organizations": [],
"towns": [],
"calamities": [],
"blockers": []
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 MiB

View File

@ -3,13 +3,16 @@ name = "lib_efo"
version = "0.1.0"
edition = "2024"
[features]
default = ["nerd-fonts"]
nerd-fonts = []
[dependencies]
serde_json = {workspace = true}
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"
@ -17,7 +20,7 @@ colored = {workspace = true}
uuid = {workspace = true}
rand = "0.9.2"
once_cell = "1.21.3"
tempfile = "3.23.0"
[dev-dependencies]
insta = {workspace = true}
tempfile = "3.23.0"

View File

@ -0,0 +1,19 @@
# Epoch Forge simulation configuration
`default.json` is the complete configuration embedded in the corresponding
Epoch Forge release. Pass an edited complete replacement to future simulation
commands with `--config PATH`; unknown fields and invalid ranges are rejected.
The schema version is independent from the repository and application
versions. This policy does not define or perform a roll: the player rolls
outside Epoch Forge and the game master supplies its interpretation. Exact
effects may be supplied for unusual rulings; otherwise the policy supplies a
small baseline effect with progressive level dampening. The configuration defines:
- dampened attenuation in basis points (`10000` means the full chosen effect);
- default effects and ordered level multipliers (`0` means fully dampened and
`10000` means the full default effect);
- defensive limits for explicit effects, durable records, and text.
Keep `policy_id` stable while semantics remain identical. Change it whenever an
edited policy should not be mistaken for the embedded policy.

View File

@ -0,0 +1,19 @@
{
"schema_version": { "major": 1, "minor": 1 },
"policy_id": "epoch-forge/adjudication-default-2",
"dampened_basis_points": 5000,
"default_effects": [
{ "stat": "health", "delta": -20 }
],
"level_basis_points": {
"excellent": 0,
"good": 2500,
"mid": 5000,
"bad": 7500,
"worsen": 9000,
"apocalypse": 10000
},
"max_effects": 64,
"max_records": 100000,
"max_text_bytes": 16384
}

View File

@ -0,0 +1,12 @@
# Epoch Forge worldgen configuration 1.0
`default.json` is embedded in `lib_efo` and is the offline default used by
`efo gen world`. Copy it, edit it, and pass the copy with `--config PATH`.
The schema version is independent from repository and application versions.
This release accepts exactly schema 1.0. Counts are inclusive and capped at
10,000 per entity kind; canvas dimensions are capped at 100,000 per axis.
Every kind with a non-zero maximum needs at least one name.
Given the same application build, exact configuration, generation level, and
seed, generation is deterministic. Preserve those four inputs with bug reports.

View File

@ -0,0 +1,20 @@
{
"schema_version": { "major": 1, "minor": 0 },
"canvas": { "width": 1920, "height": 1080 },
"counts": {
"characters": { "min": 18, "max": 32 },
"towns": { "min": 5, "max": 9 },
"events": { "min": 3, "max": 8 },
"calamities": { "min": 0, "max": 2 },
"organisations": { "min": 2, "max": 5 },
"blockers": { "min": 1, "max": 4 }
},
"names": {
"characters": ["Aria", "Bryn", "Cora", "Dain", "Elian", "Fara"],
"towns": ["Durn", "Highmere", "Oakwatch", "Rill", "Stoneford"],
"events": ["Market Day", "Heavy Rains", "Pilgrim Arrival", "Strange Lights"],
"calamities": ["The Blight", "Ashfall", "Great Flood"],
"organisations": ["Iron Council", "River Guild", "Lantern Compact"],
"blockers": ["North Wall", "Broken Bridge", "Rockslide"]
}
}

View File

@ -0,0 +1,21 @@
//! Initialise a repository and inspect its initial world through `lib_efo`.
use std::{env, error::Error, path::PathBuf};
use lib_efo::workspace::Workspace;
fn main() -> Result<(), Box<dyn Error>> {
let root = env::args_os()
.nth(1)
.map(PathBuf::from)
.ok_or("usage: cargo run -p lib_efo --example repository -- <empty-directory>")?;
let mut workspace = Workspace::initialize(&root, env!("CARGO_PKG_VERSION"))?;
println!("repository: {}", workspace.root().display());
println!("current epoch: {}", workspace.head.epoch_id);
println!(
"entities: {}",
workspace.head.iter_all_entities_mut().count()
);
Ok(())
}

733
lib_efo/src/adjudication.rs Normal file
View File

@ -0,0 +1,733 @@
//! Player-rolled, game-master-adjudicated event resolutions.
//!
//! Epoch Forge never rolls these outcomes. It records an external result and
//! previews/applies only the explicit effects chosen by the game master.
use std::{collections::HashSet, fs, path::Path, str::FromStr};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
entity::Entity,
epoch::EpochInfo,
error::EpochError,
repository_format::FormatVersion,
stats::{EntityType, ListStats, Modification, StatPair},
};
/// Configuration schema understood by this build.
pub const CURRENT_ADJUDICATION_CONFIG_VERSION: FormatVersion = FormatVersion { major: 1, minor: 1 };
/// Offline-safe canonical safety policy.
pub const DEFAULT_ADJUDICATION_CONFIG_JSON: &str =
include_str!("../assets/simulation/default.json");
/// Master-assigned interpretation of the external roll's magnitude.
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Serialize,
Deserialize,
clap::ValueEnum,
)]
#[serde(rename_all = "snake_case")]
pub enum AdjudicationLevel {
/// Exceptionally beneficial result.
Excellent,
/// Beneficial result.
Good,
/// Weak, neutral, or mixed result.
#[value(alias = "medium")]
Mid,
/// Harmful result.
Bad,
/// Strongly harmful or escalating result.
#[value(alias = "worse")]
Worsen,
/// Extreme harmful result.
Apocalypse,
}
/// Master-selected disposition of the source against this target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum AdjudicationDisposition {
/// Apply every chosen effect in full.
Applied,
/// Apply chosen effects with the configured attenuation.
Dampened,
/// Record that this target avoided the event; apply no effects.
Avoided,
/// Record that the external resolution exhausted/destroyed the source.
Destroyed,
}
/// Supported editable statistic names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StatName {
/// Population count or modifier.
Population,
/// Population growth rate.
GrowthRate,
/// Crime.
Crime,
/// Happiness.
Happiness,
/// Food.
Food,
/// Industry.
Industry,
/// Science.
Science,
/// Trade.
Trade,
/// Army.
Army,
/// Strength.
Strength,
/// Fortification.
Fortification,
/// Threat.
Threat,
/// Bureaucracy.
Bureaucracy,
/// Transportation.
Transportation,
/// Sprawl.
Sprawl,
/// Health.
Health,
}
impl StatName {
/// Convert to the existing statistics selector.
pub fn list_stat(self) -> ListStats {
match self {
Self::Population => ListStats::Population,
Self::GrowthRate => ListStats::Growthrate,
Self::Crime => ListStats::Crime,
Self::Happiness => ListStats::Happiness,
Self::Food => ListStats::Food,
Self::Industry => ListStats::Industry,
Self::Science => ListStats::Science,
Self::Trade => ListStats::Trade,
Self::Army => ListStats::Army,
Self::Strength => ListStats::Strength,
Self::Fortification => ListStats::Fortification,
Self::Threat => ListStats::Threat,
Self::Bureaucracy => ListStats::Bureaucracy,
Self::Transportation => ListStats::Transportation,
Self::Sprawl => ListStats::Sprawl,
Self::Health => ListStats::Health,
}
}
}
impl FromStr for StatName {
type Err = AdjudicationError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.trim().to_ascii_lowercase().replace('-', "_").as_str() {
"population" | "pop" => Ok(Self::Population),
"growth_rate" | "growth" => Ok(Self::GrowthRate),
"crime" => Ok(Self::Crime),
"happiness" => Ok(Self::Happiness),
"food" => Ok(Self::Food),
"industry" => Ok(Self::Industry),
"science" => Ok(Self::Science),
"trade" => Ok(Self::Trade),
"army" => Ok(Self::Army),
"strength" => Ok(Self::Strength),
"fortification" => Ok(Self::Fortification),
"threat" => Ok(Self::Threat),
"bureaucracy" => Ok(Self::Bureaucracy),
"transportation" => Ok(Self::Transportation),
"sprawl" => Ok(Self::Sprawl),
"health" => Ok(Self::Health),
_ => Err(AdjudicationError::Invalid(format!(
"unknown effect statistic `{value}`"
))),
}
}
}
/// Safety limits and dampening policy for adjudications.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AdjudicationConfig {
/// Independent configuration schema version.
pub schema_version: FormatVersion,
/// Stable policy identity recorded with each resolution.
pub policy_id: String,
/// Effect multiplier for a dampened disposition, in basis points.
pub dampened_basis_points: isize,
/// Default effects used only when the game master supplies none.
pub default_effects: Vec<ChosenEffect>,
/// Progressive multiplier selected by adjudication level.
pub level_basis_points: LevelBasisPoints,
/// Maximum effects supplied for one target.
pub max_effects: usize,
/// Maximum persisted records in one world.
pub max_records: usize,
/// Maximum UTF-8 byte length for roll descriptions and notes.
pub max_text_bytes: usize,
}
/// Multipliers for policy defaults, expressed in basis points.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LevelBasisPoints {
/// Excellent-result multiplier.
pub excellent: isize,
/// Good-result multiplier.
pub good: isize,
/// Mid-result multiplier.
pub mid: isize,
/// Bad-result multiplier.
pub bad: isize,
/// Worsen-result multiplier.
pub worsen: isize,
/// Apocalypse-result multiplier.
pub apocalypse: isize,
}
impl LevelBasisPoints {
/// Select the multiplier for one adjudication level.
fn for_level(&self, level: AdjudicationLevel) -> isize {
match level {
AdjudicationLevel::Excellent => self.excellent,
AdjudicationLevel::Good => self.good,
AdjudicationLevel::Mid => self.mid,
AdjudicationLevel::Bad => self.bad,
AdjudicationLevel::Worsen => self.worsen,
AdjudicationLevel::Apocalypse => self.apocalypse,
}
}
}
/// Durable attenuation/exhaustion state attached to a source event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventAdjudicationState {
/// Remaining strength used by later policy-default resolutions.
pub potency_basis_points: isize,
/// Whether the game master explicitly destroyed the event.
pub destroyed: bool,
/// Most recent ruling that changed this state.
pub last_record: Uuid,
}
/// Configuration, validation, or stale-application failure.
#[derive(Debug, thiserror::Error)]
pub enum AdjudicationError {
/// An entity referenced by the ruling does not exist.
#[error(transparent)]
Epoch(#[from] EpochError),
/// Reading an external policy failed.
#[error("cannot read adjudication config `{path}`: {source}")]
Io {
/// Affected path.
path: std::path::PathBuf,
/// Filesystem error.
#[source]
source: std::io::Error,
},
/// JSON did not match the policy schema.
#[error("invalid adjudication config `{path}`: {source}")]
Json {
/// Embedded label or external path.
path: std::path::PathBuf,
/// Decode error.
#[source]
source: serde_json::Error,
},
/// Semantic validation failed.
#[error("invalid adjudication: {0}")]
Invalid(String),
/// Target changed after the preview was created.
#[error("target @{target} changed after preview; run the adjudication preview again")]
Stale {
/// Stale target.
target: Uuid,
},
/// The same stable ruling has already been recorded.
#[error("adjudication @{record} is already recorded; nothing was changed")]
Duplicate {
/// Existing record identifier.
record: Uuid,
},
/// The world's record limit was reached.
#[error(
"adjudication record limit ({limit}) reached; commit or remove old records before retrying"
)]
RecordLimit {
/// Configured maximum.
limit: usize,
},
}
impl AdjudicationConfig {
/// Return the configured progressive multiplier for a level.
pub fn level_multiplier(&self, level: AdjudicationLevel) -> isize {
self.level_basis_points.for_level(level)
}
/// Load and validate the embedded policy.
pub fn embedded() -> Result<Self, AdjudicationError> {
Self::decode(
DEFAULT_ADJUDICATION_CONFIG_JSON.as_bytes(),
Path::new("<embedded adjudication config>"),
)
}
/// Load and validate a complete external replacement.
pub fn load(path: &Path) -> Result<Self, AdjudicationError> {
let bytes = fs::read(path).map_err(|source| AdjudicationError::Io {
path: path.to_owned(),
source,
})?;
Self::decode(&bytes, path)
}
/// Decode bytes with source-aware diagnostics.
pub fn decode(bytes: &[u8], path: &Path) -> Result<Self, AdjudicationError> {
let config: Self =
serde_json::from_slice(bytes).map_err(|source| AdjudicationError::Json {
path: path.to_owned(),
source,
})?;
config.validate()?;
Ok(config)
}
/// Validate policy identity, attenuation, and hard allocation limits.
pub fn validate(&self) -> Result<(), AdjudicationError> {
if self.schema_version != CURRENT_ADJUDICATION_CONFIG_VERSION {
return Err(AdjudicationError::Invalid(format!(
"schema {} is unsupported; expected {}",
self.schema_version, CURRENT_ADJUDICATION_CONFIG_VERSION
)));
}
if self.policy_id.trim().is_empty() || self.policy_id.len() > 128 {
return Err(AdjudicationError::Invalid(
"policy_id must contain 1..=128 characters".into(),
));
}
if !(0..=10_000).contains(&self.dampened_basis_points) {
return Err(AdjudicationError::Invalid(
"dampened_basis_points must be within 0..=10000".into(),
));
}
let levels = [
self.level_basis_points.excellent,
self.level_basis_points.good,
self.level_basis_points.mid,
self.level_basis_points.bad,
self.level_basis_points.worsen,
self.level_basis_points.apocalypse,
];
if levels.iter().any(|value| !(0..=10_000).contains(value))
|| levels.windows(2).any(|pair| pair[0] > pair[1])
{
return Err(AdjudicationError::Invalid(
"level_basis_points must progress from excellent to apocalypse within 0..=10000"
.into(),
));
}
if self.max_effects == 0
|| self.max_effects > 1_000
|| self.max_records == 0
|| self.max_records > 10_000_000
|| self.max_text_bytes == 0
|| self.max_text_bytes > 1_000_000
{
return Err(AdjudicationError::Invalid(
"configured limits are zero or exceed hard safety limits".into(),
));
}
validate_effects(&self.default_effects, self.max_effects)?;
Ok(())
}
}
/// One explicit effect chosen by the game master.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChosenEffect {
/// Statistic to modify.
pub stat: StatName,
/// Signed requested delta before dampening and domain clamping.
pub delta: isize,
}
/// Complete player-roll interpretation for one source and target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdjudicationSpec {
/// Master-assigned magnitude category.
pub level: AdjudicationLevel,
/// Master-selected disposition.
pub disposition: AdjudicationDisposition,
/// Event or conflict source.
pub source: Uuid,
/// Human description of the external roll, such as `d20=17`.
pub external_result: String,
/// Optional master explanation.
pub note: String,
/// Explicit effects; Epoch Forge never invents these.
pub effects: Vec<ChosenEffect>,
/// Policy expected by the caller.
pub policy_id: String,
}
/// One projected and stale-checkable statistic change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectedChange {
/// Statistic to modify.
pub stat: StatName,
/// Value observed during preview.
pub before: isize,
/// Requested delta after disposition attenuation.
pub applied_delta: isize,
/// Domain-clamped value that will be written.
pub after: isize,
}
/// Pure preview and durable record payload for one target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdjudicationReport {
/// Stable content-derived identity.
pub id: Uuid,
/// Event or conflict source.
pub source: Uuid,
/// Target entity.
pub target: Uuid,
/// Simulation tick or conflict round.
pub tick_or_round: u64,
/// Master-assigned magnitude.
pub level: AdjudicationLevel,
/// Master-selected disposition.
pub disposition: AdjudicationDisposition,
/// External result retained verbatim.
pub external_result: String,
/// Master explanation retained verbatim.
pub note: String,
/// Whether the configured fallback supplied the effects.
#[serde(default)]
pub effects_were_defaulted: bool,
/// Source potency observed while previewing.
#[serde(default = "full_basis_points")]
pub source_potency_before: isize,
/// Source potency retained after this ruling.
#[serde(default = "full_basis_points")]
pub source_potency_after: isize,
/// Stale-checkable projected changes.
pub changes: Vec<ProjectedChange>,
/// Policy used to interpret dampening and limits.
pub policy_id: String,
}
/// Preview an external result without mutating the supplied target.
pub fn preview(
config: &AdjudicationConfig,
spec: &AdjudicationSpec,
target: &Entity,
tick_or_round: u64,
) -> Result<AdjudicationReport, AdjudicationError> {
preview_at_potency(config, spec, target, tick_or_round, 10_000)
}
/// Preview while accounting for durable attenuation already on the source.
pub fn preview_at_potency(
config: &AdjudicationConfig,
spec: &AdjudicationSpec,
target: &Entity,
tick_or_round: u64,
source_potency: isize,
) -> Result<AdjudicationReport, AdjudicationError> {
config.validate()?;
validate_spec(config, spec)?;
if !(0..=10_000).contains(&source_potency) {
return Err(AdjudicationError::Invalid(
"source potency must be within 0..=10000 basis points".into(),
));
}
let disposition_attenuation = match spec.disposition {
AdjudicationDisposition::Applied => 10_000,
AdjudicationDisposition::Dampened => config.dampened_basis_points,
AdjudicationDisposition::Avoided | AdjudicationDisposition::Destroyed => 0,
};
let effects_were_defaulted = spec.effects.is_empty();
let effects = if effects_were_defaulted {
&config.default_effects
} else {
&spec.effects
};
let level_attenuation = if effects_were_defaulted {
config.level_basis_points.for_level(spec.level)
} else {
10_000
};
let attenuation = scale(
scale(disposition_attenuation, level_attenuation),
if effects_were_defaulted {
source_potency
} else {
10_000
},
);
let source_potency_after = if spec.disposition == AdjudicationDisposition::Destroyed {
0
} else {
source_potency.min(config.level_multiplier(spec.level))
};
let mut projected = target.clone();
let mut changes = Vec::new();
for effect in effects {
let stat = effect.stat.list_stat();
let before = **projected.get_stats().get_field(&stat);
let applied_delta = scale(effect.delta, attenuation);
projected.change_stat_strict(
StatPair {
stat,
value: applied_delta.into(),
},
Modification::Delta,
);
projected.update_metastats();
let after = **projected.get_stats().get_field(&stat);
changes.push(ProjectedChange {
stat: effect.stat,
before,
applied_delta,
after,
});
}
let encoded = serde_json::to_vec(&(
spec,
target.id,
tick_or_round,
effects,
attenuation,
if effects_were_defaulted {
source_potency
} else {
10_000
},
))
.map_err(|error| {
AdjudicationError::Invalid(format!("cannot identify adjudication: {error}"))
})?;
Ok(AdjudicationReport {
id: content_id(&encoded),
source: spec.source,
target: target.id,
tick_or_round,
level: spec.level,
disposition: spec.disposition,
external_result: spec.external_result.clone(),
note: spec.note.clone(),
effects_were_defaulted,
source_potency_before: source_potency,
source_potency_after,
changes,
policy_id: config.policy_id.clone(),
})
}
/// Apply a preview only when the target still matches every recorded input.
pub fn apply_to_target(
report: &AdjudicationReport,
target: &mut Entity,
) -> Result<(), AdjudicationError> {
if target.id != report.target
|| report
.changes
.iter()
.any(|change| **target.get_stats().get_field(&change.stat.list_stat()) != change.before)
{
return Err(AdjudicationError::Stale {
target: report.target,
});
}
for change in &report.changes {
target.change_stat_strict(
StatPair {
stat: change.stat.list_stat(),
value: change.after.into(),
},
Modification::Replace,
);
}
target.update_metastats();
Ok(())
}
/// Atomically apply a preview to a cloned world and retain its audit record.
///
/// Callers should save the returned world through the repository transaction
/// layer. The input is left unchanged on every error.
pub fn apply_to_world(
world: &EpochInfo,
config: &AdjudicationConfig,
report: &AdjudicationReport,
target_type: EntityType,
) -> Result<EpochInfo, AdjudicationError> {
if world.adjudications.contains_key(&report.id) {
return Err(AdjudicationError::Duplicate { record: report.id });
}
if world.adjudications.len() >= config.max_records {
return Err(AdjudicationError::RecordLimit {
limit: config.max_records,
});
}
let source_is_event = world
.find_entity_strict(report.source, Some(EntityType::Event))
.is_ok();
if !source_is_event && !world.conflicts.contains_key(&report.source) {
return Err(AdjudicationError::Invalid(format!(
"source @{} is neither an event nor a conflict",
report.source
)));
}
let mut updated = world.clone();
let target = updated.find_entity_strict_as_mut(report.target, Some(target_type))?;
apply_to_target(report, target)?;
updated.adjudications.insert(report.id, report.clone());
if source_is_event {
updated.event_adjudications.insert(
report.source,
EventAdjudicationState {
potency_basis_points: report.source_potency_after,
destroyed: report.disposition == AdjudicationDisposition::Destroyed,
last_record: report.id,
},
);
if report.disposition == AdjudicationDisposition::Destroyed
&& let Some(diffusion) = updated.diffusions.get_mut(&report.source)
{
diffusion.expired = true;
}
}
Ok(updated)
}
/// Validate persisted audit-record references and structural invariants.
pub fn validate_adjudications(world: &EpochInfo) -> Result<(), AdjudicationError> {
for (event, state) in &world.event_adjudications {
world.find_entity_strict(*event, Some(EntityType::Event))?;
if !(0..=10_000).contains(&state.potency_basis_points)
|| (state.destroyed && state.potency_basis_points != 0)
{
return Err(AdjudicationError::Invalid(format!(
"event @{event} has invalid adjudication state"
)));
}
if !world.adjudications.contains_key(&state.last_record) {
return Err(AdjudicationError::Invalid(format!(
"event @{event} refers to missing adjudication @{}",
state.last_record
)));
}
}
for (key, report) in &world.adjudications {
if key != &report.id {
return Err(AdjudicationError::Invalid(format!(
"adjudication map key @{key} does not match record @{}",
report.id
)));
}
if world
.find_entity_strict(report.source, Some(EntityType::Event))
.is_err()
&& !world.conflicts.contains_key(&report.source)
{
return Err(AdjudicationError::Invalid(format!(
"record @{} refers to missing source @{}",
report.id, report.source
)));
}
world.find_entity_strict(report.target, None)?;
let unique = report
.changes
.iter()
.map(|change| change.stat)
.collect::<HashSet<_>>();
if unique.len() != report.changes.len() {
return Err(AdjudicationError::Invalid(format!(
"record @{} changes one statistic more than once",
report.id
)));
}
if report.policy_id.trim().is_empty() {
return Err(AdjudicationError::Invalid(format!(
"record @{} has no policy identity",
report.id
)));
}
}
Ok(())
}
/// Serde default for records written before source attenuation existed.
const fn full_basis_points() -> isize {
10_000
}
/// Validate a master-authored interpretation before previewing it.
fn validate_spec(
config: &AdjudicationConfig,
spec: &AdjudicationSpec,
) -> Result<(), AdjudicationError> {
if spec.policy_id != config.policy_id {
return Err(AdjudicationError::Invalid(format!(
"requested policy `{}` does not match `{}`",
spec.policy_id, config.policy_id
)));
}
if spec.external_result.len() > config.max_text_bytes || spec.note.len() > config.max_text_bytes
{
return Err(AdjudicationError::Invalid(
"external result or note exceeds max_text_bytes".into(),
));
}
validate_effects(&spec.effects, config.max_effects)
}
/// Validate effect allocation and reject ambiguous duplicate statistics.
fn validate_effects(effects: &[ChosenEffect], max_effects: usize) -> Result<(), AdjudicationError> {
if effects.len() > max_effects {
return Err(AdjudicationError::Invalid(
"too many explicit effects".into(),
));
}
let unique = effects
.iter()
.map(|effect| effect.stat)
.collect::<HashSet<_>>();
if unique.len() != effects.len() {
return Err(AdjudicationError::Invalid(
"an adjudication may change each statistic at most once".into(),
));
}
Ok(())
}
/// Apply a basis-point multiplier with saturating multiplication.
fn scale(value: isize, basis_points: isize) -> isize {
value.saturating_mul(basis_points) / 10_000
}
/// Generate a stable UUID from canonical serialized content.
fn content_id(bytes: &[u8]) -> Uuid {
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))
}

290
lib_efo/src/conflict.rs Normal file
View File

@ -0,0 +1,290 @@
//! Persistent, multi-side fight and war state.
use std::collections::{BTreeMap, BTreeSet, HashSet};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
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")]
pub enum ConflictKind {
/// Normally completes after its first adjudicated round.
Fight,
/// Continues until one side remains, a stalemate is declared, or it is ended.
War,
}
/// Conflict lifecycle state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum ConflictStatus {
/// Created but not advanced.
Planned,
/// At least one war round has completed and multiple sides remain.
Active,
/// No winner was produced.
Stalemate,
/// One named side remains.
Won {
/// Winning side label.
side: String,
},
/// Explicitly ended by the game master.
Ended {
/// Human explanation.
reason: String,
},
}
impl ConflictStatus {
/// Whether another round may be adjudicated.
pub fn can_advance(&self) -> bool {
matches!(self, Self::Planned | Self::Active)
}
}
/// Stable participant reference; normal entities are never owned or deleted.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParticipantRef {
/// Stored entity collection.
pub entity_type: EntityType,
/// Stable entity identity.
pub id: Uuid,
/// User-defined coalition label.
pub side: String,
/// Relative commitment for future rulesets.
pub committed_weight: u32,
/// Whether an adjudication removed this participant from the conflict.
#[serde(default)]
pub removed: bool,
}
/// One immutable-in-spirit conflict round audit entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConflictRound {
/// Monotonic one-based round number.
pub number: u64,
/// Adjudication record IDs produced for participants.
pub records: Vec<Uuid>,
}
/// Persisted generic conflict.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConflictState {
/// Stable identity.
pub id: Uuid,
/// Human name.
pub name: String,
/// Fight or war behavior.
pub kind: ConflictKind,
/// Participants in deterministic UUID order.
pub participants: Vec<ParticipantRef>,
/// Number of applied rounds.
pub round: u64,
/// Current lifecycle state.
pub status: ConflictStatus,
/// Versioned resolution policy.
pub ruleset_id: String,
/// Applied round history keyed by number.
#[serde(default)]
pub rounds: BTreeMap<u64, ConflictRound>,
}
/// Invalid conflict input or transition.
#[derive(Debug, thiserror::Error)]
pub enum ConflictError {
/// Semantic invariant failed.
#[error("invalid conflict: {0}")]
Invalid(String),
/// Requested conflict does not exist.
#[error("conflict `{0}` was not found; run `efo conflict list`")]
Missing(String),
}
/// Validate and create a planned conflict.
pub fn create_conflict(
world: &EpochInfo,
id: Uuid,
name: String,
kind: ConflictKind,
mut participants: Vec<ParticipantRef>,
) -> Result<ConflictState, ConflictError> {
participants.sort_unstable_by_key(|participant| participant.id);
let conflict = ConflictState {
id,
name,
kind,
participants,
round: 0,
status: ConflictStatus::Planned,
ruleset_id: DEFAULT_CONFLICT_RULESET.into(),
rounds: BTreeMap::new(),
};
validate_conflict(world, &conflict)?;
Ok(conflict)
}
/// Validate every persisted conflict and cross-reference.
pub fn validate_conflicts(world: &EpochInfo) -> Result<(), ConflictError> {
for (key, conflict) in &world.conflicts {
if key != &conflict.id {
return Err(ConflictError::Invalid(format!(
"map key @{key} does not match conflict @{}",
conflict.id
)));
}
validate_conflict(world, conflict)?;
}
Ok(())
}
/// Resolve a conflict by exact ID or unambiguous case-insensitive name prefix.
pub fn find_conflict<'a>(
world: &'a EpochInfo,
selector: &str,
) -> Result<&'a ConflictState, ConflictError> {
let matches = world
.conflicts
.values()
.filter(|conflict| {
selector
.strip_prefix('@')
.is_some_and(|id| conflict.id.to_string().starts_with(id))
|| conflict
.name
.to_lowercase()
.starts_with(&selector.to_lowercase())
})
.collect::<Vec<_>>();
match matches.as_slice() {
[conflict] => Ok(conflict),
[] => Err(ConflictError::Missing(selector.into())),
_ => Err(ConflictError::Invalid(format!(
"selector `{selector}` is ambiguous; use @UUID"
))),
}
}
/// Record a round and derive its deterministic lifecycle result.
pub fn finish_round(
conflict: &mut ConflictState,
records: Vec<Uuid>,
removed: &HashSet<Uuid>,
) -> Result<(), ConflictError> {
if !conflict.status.can_advance() {
return Err(ConflictError::Invalid(format!(
"{} is already finished",
conflict.name
)));
}
let number = conflict.round.saturating_add(1);
if conflict.rounds.contains_key(&number) {
return Err(ConflictError::Invalid(format!(
"round {number} is already recorded"
)));
}
for participant in &mut conflict.participants {
participant.removed |= removed.contains(&participant.id);
}
let remaining = conflict
.participants
.iter()
.filter(|participant| !participant.removed)
.map(|participant| participant.side.clone())
.collect::<BTreeSet<_>>();
conflict.round = number;
conflict
.rounds
.insert(number, ConflictRound { number, records });
conflict.status = match remaining.len() {
0 => ConflictStatus::Stalemate,
1 => ConflictStatus::Won {
side: remaining.into_iter().next().unwrap_or_default(),
},
_ if conflict.kind == ConflictKind::Fight => ConflictStatus::Stalemate,
_ => ConflictStatus::Active,
};
Ok(())
}
/// Validate one conflict independently of map identity.
fn validate_conflict(world: &EpochInfo, conflict: &ConflictState) -> Result<(), ConflictError> {
if conflict.name.trim().is_empty() {
return Err(ConflictError::Invalid("name cannot be empty".into()));
}
if conflict.ruleset_id != DEFAULT_CONFLICT_RULESET {
return Err(ConflictError::Invalid(format!(
"unsupported ruleset `{}`",
conflict.ruleset_id
)));
}
if conflict.participants.len() < 2 {
return Err(ConflictError::Invalid(
"at least two participants are required".into(),
));
}
let mut ids = HashSet::new();
let mut sides = BTreeSet::new();
for participant in &conflict.participants {
if participant.entity_type == EntityType::Player {
return Err(ConflictError::Invalid(
"player is not a stored entity type".into(),
));
}
if !ids.insert(participant.id)
|| participant.side.trim().is_empty()
|| participant.committed_weight == 0
{
return Err(ConflictError::Invalid(
"participants must have unique IDs, non-empty sides, and positive weights".into(),
));
}
world
.find_entity_strict(participant.id, Some(participant.entity_type))
.map_err(|error| ConflictError::Invalid(error.to_string()))?;
if !participant.removed {
sides.insert(participant.side.as_str());
}
}
if conflict.round == 0 && sides.len() < 2 {
return Err(ConflictError::Invalid(
"at least two active sides are required".into(),
));
}
if conflict.rounds.len() != usize::try_from(conflict.round).unwrap_or(usize::MAX)
|| conflict.rounds.keys().copied().ne(1..=conflict.round)
{
return Err(ConflictError::Invalid(
"round history is not contiguous".into(),
));
}
if conflict
.rounds
.values()
.flat_map(|round| &round.records)
.any(|record| !world.adjudications.contains_key(record))
{
return Err(ConflictError::Invalid(
"round refers to a missing adjudication record".into(),
));
}
Ok(())
}

163
lib_efo/src/diff.rs Normal file
View File

@ -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<String>,
/// 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<EntityChange>,
/// Summary before/after when changed.
pub summary: Option<(String, String)>,
/// Tags before/after when changed.
pub tags: Option<(Vec<String>, Vec<String>)>,
}
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<EntityChange>) {
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<String>,
) -> 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<String> {
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::<Vec<_>>();
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,
}
}

View File

@ -21,6 +21,7 @@ use crate::{
error::EpochError,
stats::{self, EntityType, MetaStats, OverallStats, Symbols, TypedLink},
};
pub mod edit;
pub mod implementations;
/// An entity that can be present in the game world.

148
lib_efo/src/entity/edit.rs Normal file
View File

@ -0,0 +1,148 @@
//! Validated text inputs for interactive entity authoring.
use super::{EffectApplication, EffectBounds, Entity, EntityDuration};
use crate::stats::EntityType;
/// Editable fields shared by entity forms. Unexposed metadata stays intact.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntityDraft {
/// Non-empty display name.
pub name: String,
/// Free-form, possibly multiline description.
pub description: String,
/// Exact coordinates as `x,y`.
pub position: String,
/// `permanent`, `done`, or a number of turns.
pub duration: String,
/// `recurring`, `when-present`, `todo`, or `done`.
pub effect: String,
/// Inclusive effect bounds in `min:max` form.
pub bounds: String,
/// Absolute statistic values as whitespace-separated `field:value` pairs.
pub statistics: String,
}
impl EntityDraft {
/// Construct a zero-stat entity with a stable UUID and type-specific defaults.
pub fn new_entity(kind: EntityType) -> Entity {
let event = kind == EntityType::Event;
Entity {
id: uuid::Uuid::new_v4(),
entity_type: kind,
duration: if event {
EntityDuration::Duration(1)
} else {
EntityDuration::Permanent
},
effect_nature: if event {
EffectApplication::PermanentEffectToApply
} else {
EffectApplication::WhenPresent
},
effect_bounds: match kind {
EntityType::Character => EffectBounds { min: 20, max: 110 },
EntityType::Town => EffectBounds { min: 20, max: 60 },
EntityType::Calamity => EffectBounds { min: 20, max: 80 },
EntityType::Event => EffectBounds { min: 10, max: 80 },
_ => EffectBounds { min: 0, max: 120 },
},
..Entity::default()
}
}
/// Populate a form without losing relationships or other unexposed fields.
pub fn from_entity(entity: &Entity) -> Result<Self, String> {
let position =
serde_json::to_value(entity.position()).map_err(|error| error.to_string())?;
let statistics =
serde_json::to_value(entity.get_stats()).map_err(|error| error.to_string())?;
Ok(Self {
name: entity.name.clone(),
description: entity.description.clone(),
position: format!("{},{}", position[0], position[1]),
duration: match entity.duration {
EntityDuration::Permanent => "permanent".into(),
EntityDuration::Done => "done".into(),
EntityDuration::Duration(turns) => turns.to_string(),
},
effect: match entity.effect_nature {
EffectApplication::Recurring => "recurring",
EffectApplication::WhenPresent => "when-present",
EffectApplication::PermanentEffectToApply => "todo",
EffectApplication::PermanentEffectApplied => "done",
}
.into(),
bounds: format!("{}:{}", entity.effect_bounds.min, entity.effect_bounds.max),
statistics: statistics
.as_object()
.ok_or("statistics are not an object")?
.iter()
.map(|(key, value)| format!("{key}:{value}"))
.collect::<Vec<_>>()
.join(" "),
})
}
/// Validate inputs and produce a new entity without mutating the original.
/// Unlisted statistics and all relationships are preserved.
pub fn apply(&self, original: &Entity) -> Result<Entity, String> {
let name = self.name.trim();
if name.is_empty() || name.chars().any(char::is_control) {
return Err("Name: enter a non-empty name without control characters".into());
}
let mut entity = original.clone();
entity.name = name.into();
entity.description = self.description.clone();
let coordinates: Vec<_> = self.position.split(',').map(str::trim).collect();
if coordinates.len() != 2 {
return Err("Position: use exact x,y coordinates (for example 12,-5)".into());
}
let coordinates: Vec<isize> = coordinates
.iter()
.map(|value| value.parse::<isize>())
.collect::<Result<_, _>>()
.map_err(|_| "Position: both coordinates must be integers")?;
entity.metadata.position = serde_json::from_value(serde_json::json!(coordinates))
.map_err(|error| format!("Position: {error}"))?;
entity.duration = self.duration.parse().map_err(|error| {
format!("Duration: {error}; use permanent, done, or a number of turns")
})?;
entity.effect_nature = match self.effect.trim().to_lowercase().as_str() {
"recurring" => EffectApplication::Recurring,
"when-present" => EffectApplication::WhenPresent,
"todo" => EffectApplication::PermanentEffectToApply,
"done" => EffectApplication::PermanentEffectApplied,
_ => return Err("Effect: use recurring, when-present, todo, or done".into()),
};
entity.effect_bounds = self
.bounds
.parse()
.map_err(|error| format!("Bounds: {error}; use min:max"))?;
if entity.effect_bounds.min > entity.effect_bounds.max {
return Err("Bounds: minimum must not exceed maximum".into());
}
let mut statistics =
serde_json::to_value(&entity.stats).map_err(|error| error.to_string())?;
let fields = statistics
.as_object_mut()
.ok_or("statistics are not an object")?;
let mut seen = std::collections::BTreeSet::new();
for pair in self.statistics.split_whitespace() {
let (key, value) = pair
.split_once(':')
.ok_or_else(|| format!("Statistics: `{pair}` must be field:value"))?;
if !fields.contains_key(key) || !seen.insert(key) {
return Err(format!(
"Statistics: unknown or repeated field `{key}`; use the full field names shown in the form"
));
}
let value: isize = value
.parse()
.map_err(|_| format!("Statistics: `{key}` requires an integer"))?;
fields.insert(key.into(), serde_json::json!(value));
}
entity.stats =
serde_json::from_value(statistics).map_err(|error| format!("Statistics: {error}"))?;
entity.update_metastats();
Ok(entity)
}
}

View File

@ -2,6 +2,7 @@
mod from_impl;
use std::hash::Hash;
use crate::output::symbol;
use crate::{
Displayable,
entity::Entity,
@ -16,11 +17,25 @@ mod methods;
// ---------- Implementation ----------
impl Displayable for Entity {
// Detailed multi-line view (used e.g. in logs)
fn print_full(&self, epoch_info: &EpochInfo) {
println!("{}", self.to_pretty_tree(epoch_info),);
if let Ok(c) = self.stats_to_table() {
println!("{c}");
fn full_display(&self, epoch_info: &EpochInfo) -> String {
let mut output = self.to_pretty_tree(epoch_info);
if let Ok(table) = self.stats_to_table() {
output.push('\n');
output.push_str(&table.to_string());
}
output
}
/// 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
@ -30,18 +45,22 @@ impl Displayable for Entity {
.metadata
.capital
.as_ref()
.map(|c| format!("Capital: {} ", c.to_symbol().blue()))
.map(|c| format!("Capital: {}{} ", symbol("", ""), c.to_symbol().blue()))
.unwrap_or_default();
let governor = self
.metadata
.governor
.as_ref()
.map(|g| format!("Governor: {}", g.to_symbol().blue()))
.map(|g| format!("Governor: {}{}", symbol("", ""), g.to_symbol().blue()))
.unwrap_or_default();
let prestige = if *self.metadata.prestige > 0 {
format!(" {:2}{}", self.metadata.prestige, "".yellow())
format!(
" {:2}{}",
self.metadata.prestige,
symbol("", " prestige").yellow()
)
} else {
String::new()
};
@ -82,7 +101,7 @@ fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &stats::EntityType)
.map(|e| e.to_symbol())
.unwrap_or(format!(
"{}{} is missing {}",
"".red(),
symbol("", "missing ").red(),
id.to_symbol().red(),
e_type.clone().to_shortest().blue()
))

View File

@ -252,10 +252,15 @@ impl Entity {
/// Defer the update of all stats
pub fn update_metastats(&mut self) {
self.stats.update();
self.stats.clamp_for(self.entity_type);
}
/// Returns whether the entity match an optionnal identifier
/// Return whether this entity's persisted statistics satisfy its domain.
pub fn stats_are_bounded(&self) -> bool {
self.stats.is_bounded_for(self.entity_type)
}
/// Return whether the entity matches an optional identifier.
pub fn match_identifier(&self, entity_identifier: &Option<EntityIdentifier>) -> bool {
match entity_identifier {
Some(EntityIdentifier::Name(name)) => {

View File

@ -8,6 +8,7 @@
//! 4. **Entity creation** – deterministic or RNG‑based.
//! 5. **Utility helpers** – position handling, identifier matching.
use crate::output::symbol;
use cli_table::{Style, WithTitle};
use colored::*;
use rand::distr::Distribution;
@ -52,6 +53,11 @@ impl Entity {
}
}
/// Read the entity's typed relationships without exposing mutable metadata.
pub fn links(&self) -> &[stats::TypedLink] {
&self.metadata.links
}
/// Removes a link (UUID) from the entity's metadata.
///
/// If the supplied `id_to_remove` exists in `self.metadata.links`, it is
@ -135,9 +141,10 @@ impl Entity {
let mut out = String::new();
out.push_str(&format!(
"[{} {} 󰻾[{}]]\n",
"[{} {} {}[{}]]\n",
self.entity_type.to_symbol().blue().bold(),
self.name.cyan().bold(),
symbol("󰻾", "@"),
self.id.to_string().blue().bold()
));
@ -159,7 +166,7 @@ impl Entity {
&format!(
"├─ {} : {}{}\n",
"faction".bright_green(),
"".yellow(),
symbol("", "faction ").yellow(),
faction.to_string().yellow(),
),
));
@ -181,7 +188,7 @@ impl Entity {
"├─ {}: {}{}\n",
"prestige".bright_green(),
self.metadata.prestige.to_string().yellow(),
"".yellow()
symbol("", " prestige").yellow()
),
));
}

View File

@ -158,7 +158,7 @@ Entity {
),
reach: None,
},
entity_type: Monster,
entity_type: Calamity,
duration: Permanent,
effect_nature: Recurring,
effect_bounds: EffectBounds {

View File

@ -281,6 +281,7 @@ fn effect_bound_testing() {
}
#[test]
#[cfg(feature = "nerd-fonts")]
fn snapshot_full_oneline_display() {
init_snapshot_env();
let e = full_entity();
@ -302,6 +303,7 @@ fn snapshot_full_oneline_display() {
}
#[test]
#[cfg(feature = "nerd-fonts")]
fn snapshot_minimal_oneline_display() {
init_snapshot_env();
let e = Entity::default();
@ -418,7 +420,7 @@ fn snapshot_entity_delta() {
prestige: stats::GenericStat(3),
reach: stats::Reach::Local(12),
},
entity_type: EntityType::Monster,
entity_type: EntityType::Calamity,
duration: EntityDuration::Permanent,
effect_nature: EffectApplication::Recurring,
effect_bounds: EffectBounds::from(0..33),
@ -602,7 +604,7 @@ fn test_rng() {
Entity::create_rng(&EntityType::Character, &crate::utils::RngLevel::Zero).unwrap();
Entity::create_rng(&EntityType::Player, &crate::utils::RngLevel::Low).unwrap();
Entity::create_rng(&EntityType::Town, &crate::utils::RngLevel::Med).unwrap();
Entity::create_rng(&EntityType::Monster, &crate::utils::RngLevel::High).unwrap();
Entity::create_rng(&EntityType::Calamity, &crate::utils::RngLevel::High).unwrap();
Entity::create_rng(&EntityType::Blocker, &crate::utils::RngLevel::Legendary).unwrap();
Entity::create_rng(&EntityType::Event, &crate::utils::RngLevel::Mixed).unwrap();
Entity::create_rng(&EntityType::Event, &crate::utils::RngLevel::Flawed).unwrap();

View File

@ -33,6 +33,8 @@ pub use epoch_config::EpochConfig;
pub mod epoch_info;
pub use epoch_info::EpochInfo;
pub mod index;
pub use index::{EntityIndex, EntityLocation};
pub mod epoch_traits;
// TODO(5): Try to load from a config and have it inserted as a backup
@ -47,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

View File

@ -10,9 +10,10 @@
//! The world data and all event logs belong to the individual epoch
//! directories and are **not** part of this file.
use crate::output::symbol;
use crate::{
epoch::{
EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, TagList,
EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SaveMode, TagList,
epoch_traits::ConfigWritable,
},
stats::{self, Symbols},
@ -21,7 +22,6 @@ use colored::*;
use std::{
collections::HashMap,
fs::{read_to_string, remove_dir_all},
path::Path,
};
use log::{info, warn};
@ -55,6 +55,9 @@ pub struct EpochConfig {
/// A hashmap containing the name of all existing epochs, only loaded in memory if used
#[serde(skip)]
pub list_existing_epochs: HashMap<EpochId, Option<EpochInfo>>,
/// Whether the current cache entry is an authoritative worktree.
#[serde(skip)]
pub preloaded_current: bool,
}
impl Default for EpochConfig {
@ -64,36 +67,13 @@ impl Default for EpochConfig {
epoch_id: EpochId::new(0),
tags: HashMap::new(),
list_existing_epochs: HashMap::new(),
preloaded_current: false,
version: env!("EFO_SHORT_VERSION").to_string(),
}
}
}
impl EpochConfig {
/// Create a new config from an existig path
pub fn new_from_path(_path: Option<&Path>) -> Result<Self, EpochError> {
let path = Path::new(MAIN_NAME);
if path.is_file() {
// TODO(6): write a trait for this
let config: EpochConfig = serde_json::from_str(&io_err_with_help!(
read_to_string(path),
"Reading config from path {:?}",
path
)?)
.map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
version: format!("Current version: {}", env!("EFO_SHORT_VERSION")),
})?;
Ok(config.initialize()?)
} else {
Err(EpochError::MainFolderInvalid(
EpochConfig::default().save_folder(),
))
}
}
/// Output the current version vs the filesystem version
pub fn version(&self) -> String {
format!(
@ -103,29 +83,6 @@ impl EpochConfig {
)
}
/// Initialize the epoch structure in depth.
///
/// Scans the default configuration folder for sub-directories that are
/// interpreted as epoch identifiers, logs each discovered epoch and
/// registers it in the in-memory cache.
///
/// This function may return an error if the configuration folder cannot
/// be read or if any directory name cannot be parsed as an `EpochId`.
pub(crate) fn initialize(mut self) -> Result<Self, EpochError> {
let path = EpochConfig::default().save_subfolder();
let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?;
// let mut valid_folders = HashMap::new();
for elt in path {
let elt = io_err_with_help!(elt, "Opening file in main config folder")?;
if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() {
let id = elt.file_name().to_string_lossy().parse::<EpochId>()?;
info!("Preloaded Epoch {:?}", id);
self.list_existing_epochs.insert(id, None);
}
}
Ok(self)
}
/// Loads the metadata for an epoch from disk into the in-memory cache.
///
/// The epoch identified by `epoch_id` must exist in `list_existing_epochs`.
@ -139,6 +96,15 @@ impl EpochConfig {
/// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed.
/// * `Err(EpochError::Io { .. })` if the file could not be read.
pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> {
if self.preloaded_current
&& *epoch_id == self.epoch_id
&& self
.list_existing_epochs
.get(epoch_id)
.is_some_and(Option::is_some)
{
return Ok(());
}
// Preload the epoch
let version = self.version();
let value = self
@ -174,19 +140,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 +154,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`
@ -284,11 +247,6 @@ impl EpochConfig {
}
}
/// Return the name of the subfolder used to save this structure
pub(crate) fn save_subfolder(&self) -> String {
format!("{}/", SUBFOLDER_NAMING)
}
/// Delete an entire epoch folder by its ID.
///
/// The function removes the directory, deletes all references to the
@ -297,10 +255,7 @@ impl EpochConfig {
// TODO(9): Create a delete_ids taking an iterator for added performance on huge deletions
pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> {
if !self.list_existing_epochs.contains_key(&id) {
warn!(
"The given epoch {} doesn't exists and it's deletion was skipped",
id
)
warn!("Epoch {} does not exist; deletion was skipped", id)
} else {
io_err_with_help!(
remove_dir_all(EpochInfo::with_id(&id).save_folder()),
@ -316,19 +271,9 @@ impl EpochConfig {
/// Compute the next epoch.
///
/// Currently this function is a placeholder that creates a new epoch
/// with the ID immediately following the current one. The actual logic
/// is deferred to the `EpochInfo -> World` subsystem.
/// Clone the current world into its next time step.
pub fn compute_next(&mut self) -> Result<EpochInfo, EpochError> {
// unimplemented!();
// Iter on events, increment time
// Iter on character, increment time
//
// create a new_towns_values vector, update it with base stats, then all events modifying underlying value
// create_new_character_base_v vector, do the same
// calculate the temps values (via function)
// TODO(1): Implement this
warn!("DEBUG LINE: COMPUTING NEXT EPOCH");
info!("Computing the epoch after {}", self.epoch_id);
// Set base for new epoch
let mut new_epoch = self.try_load_current()?.clone();
let _ = self.increment_time(&mut new_epoch);
@ -350,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)
@ -377,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,
@ -406,9 +327,7 @@ impl EpochConfig {
new_epoch.create_subfolders()?;
new_epoch.save_with_context("Saving new epoch", save_mode)?;
// Add the epoch to the list of epochs, not doing so will still have it added
// at the next iteration since the command always parse the files to determine it's state rater that the list
// not doing so would likely create errors if insert is used before another command
// Keep the in-memory index coherent for subsequent operations in this process.
let new_id = new_epoch.epoch_id;
self.list_existing_epochs.insert(new_id, Some(new_epoch));
self.epoch_id = new_id;
@ -445,7 +364,7 @@ impl EpochConfig {
// TODO: Make a method for this
for elt in items_to_log.iter().rev() {
let star = if elt.epoch_id == self.epoch_id {
""
symbol("", "→ ")
} else {
" "
};
@ -453,11 +372,12 @@ impl EpochConfig {
"{} {:>4} - {}{}{:10} {:50}",
star.green(),
elt.epoch_id.to_symbol().blue(),
"󰬌 ".yellow(),
symbol("󰬌 ", "entities: ").yellow(),
(elt.events.len()
+ elt.characters.len()
+ elt.towns.len()
+ elt.calamities.len()
+ elt.organizations.len()
+ elt.blockers.len())
.to_string()
.yellow(),

View File

@ -2,33 +2,34 @@
//!
//! The `EpochInfo` struct holds all information that the engine needs to
//! reconstruct a particular epoch.
//! It is persisted to `epoch/<epoch_id>/.epochinfo`. The file contains the epoch ID, the RNG
//! seed that produced the world, any optional tags, and a human-readable
//! summary. World data itself is stored separately (e.g. in `world.json`).
//! It is persisted to `epoch/<epoch_id>/epochinfo.json`. The file contains the
//! epoch ID, RNG seed, tags, summary, and the complete entity collections.
use cli_table::Table;
use derive_more::Display;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::create_dir_all;
use uuid::Uuid;
use crate::{
adjudication::{AdjudicationReport, EventAdjudicationState},
conflict::ConflictState,
entity::{Entity, EntityIdentifier},
epoch::{
EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList,
epoch_traits::{ConfigWritable, Prettiable},
},
error::EpochError,
simulation::{DiffusionState, MobilityState, Road},
stats::{EntityType, Position, PositionIdentifier, Symbols, TypedLink},
};
/// The metadata file stored inside each epoch directory
/// (`epoch/<epoch_id>/.epochinfo`).
///
/// It contains only the information that is needed for the engine to
/// reconstruct the state *of that particular epoch* (seed, selected
/// events, parent link, etc.). The full world data will be kept in
/// separate storage (e.g. `world.json`) but is for stored here.
/// It contains the information needed to reconstruct that epoch, including the
/// complete world entity collections.
#[derive(Debug, Clone, Serialize, Deserialize, Display, Table)]
#[display(
"Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})"
@ -38,6 +39,16 @@ pub struct EpochInfo {
#[table(title = "ID")]
pub epoch_id: EpochId,
/// Immutable predecessor in history.
#[serde(default)]
#[table(skip)]
pub parent_epoch: Option<EpochId>,
/// User-supplied history message for commits.
#[serde(default)]
#[table(skip)]
pub commit_message: String,
/// RNG seed that was used to generate randomised data for
/// this epoch. Keeping it in the file guarantees repeatable
/// behaviour when replaying the same epoch.
@ -62,6 +73,10 @@ pub struct EpochInfo {
#[table(skip)]
/// The list of characters currently present
pub characters: Vec<Entity>,
/// The list of organisations currently present.
#[serde(default)]
#[table(skip)]
pub organizations: Vec<Entity>,
#[table(skip)]
/// The list of towns currently present
pub towns: Vec<Entity>,
@ -71,6 +86,30 @@ pub struct EpochInfo {
#[table(skip)]
/// The list of blockers currently present
pub blockers: Vec<Entity>,
/// Stable travel edges between towns.
#[serde(default)]
#[table(skip)]
pub roads: Vec<Road>,
/// Explicit character residency and travel intent, keyed by character UUID.
#[serde(default)]
#[table(skip)]
pub mobility: BTreeMap<Uuid, MobilityState>,
/// Active event diffusion state keyed by event UUID.
#[serde(default)]
#[table(skip)]
pub diffusions: BTreeMap<Uuid, DiffusionState>,
/// Applied or recorded game-master adjudications, keyed by stable record ID.
#[serde(default)]
#[table(skip)]
pub adjudications: BTreeMap<Uuid, AdjudicationReport>,
/// Current attenuation/exhaustion state keyed by source event UUID.
#[serde(default)]
#[table(skip)]
pub event_adjudications: BTreeMap<Uuid, EventAdjudicationState>,
/// Persistent fights and wars keyed by stable conflict UUID.
#[serde(default)]
#[table(skip)]
pub conflicts: BTreeMap<Uuid, ConflictState>,
}
impl Prettiable for EpochInfo {}
@ -79,14 +118,23 @@ impl Default for EpochInfo {
fn default() -> Self {
Self {
epoch_id: EpochId::new(0),
parent_epoch: None,
commit_message: String::new(),
rng_seed: 0,
tags: TagList::new(),
summary: String::new(),
events: Vec::new(),
characters: Vec::new(),
organizations: Vec::new(),
towns: Vec::new(),
calamities: Vec::new(),
blockers: Vec::new(),
roads: Vec::new(),
mobility: BTreeMap::new(),
diffusions: BTreeMap::new(),
adjudications: BTreeMap::new(),
event_adjudications: BTreeMap::new(),
conflicts: BTreeMap::new(),
}
}
}
@ -217,6 +265,7 @@ impl EpochInfo {
.iter()
.find(predicate)
.or(self.characters.iter().find(predicate))
.or(self.organizations.iter().find(predicate))
.or(self.towns.iter().find(predicate))
.or(self.blockers.iter().find(predicate))
.or(self.calamities.iter().find(predicate))
@ -242,6 +291,7 @@ impl EpochInfo {
.iter()
.find(predicate)
.or(self.characters.iter().find(predicate))
.or(self.organizations.iter().find(predicate))
.or(self.towns.iter().find(predicate))
.or(self.blockers.iter().find(predicate))
.or(self.calamities.iter().find(predicate))
@ -252,7 +302,7 @@ impl EpochInfo {
}
}
/// Find an entity from an Uuid
// TODO: Siplify this with the better iterator
// TODO: Simplify this by sharing a single all-entity iterator.
pub fn find_entity_strict_as_mut(
&mut self,
id: Uuid,
@ -272,6 +322,7 @@ impl EpochInfo {
.iter_mut()
.find(predicate)
.or(self.characters.iter_mut().find(predicate))
.or(self.organizations.iter_mut().find(predicate))
.or(self.towns.iter_mut().find(predicate))
.or(self.blockers.iter_mut().find(predicate))
.or(self.calamities.iter_mut().find(predicate))
@ -284,14 +335,14 @@ impl EpochInfo {
/// Returns a slice over the entities of the requested type from the given `EpochInfo`.
///
/// The function matches the supplied `e_type` to the appropriate collection
/// inside `epoch_info`. For unimplemented entity types the call will panic
/// because of the `todo!()` placeholder.
/// inside `epoch_info`. The internal-only player type is not stored yet.
pub fn vec_entities(&self, e_type: &EntityType) -> &Vec<Entity> {
match e_type {
EntityType::Character => &self.characters,
EntityType::Player => unimplemented!("No players for now"),
EntityType::Town => &self.towns,
EntityType::Monster => &self.calamities,
EntityType::Calamity => &self.calamities,
EntityType::Organization => &self.organizations,
EntityType::Blocker => &self.blockers,
EntityType::Event => &self.events,
}
@ -324,13 +375,14 @@ impl EpochInfo {
/// `EpochInfo`.
///
/// Like `vec_entities`, this function selects the appropriate collection
/// based on `e_type`. Unimplemented variants will panic due to the `todo!()`.
/// based on `e_type`. The internal-only player type is not stored yet.
pub fn vec_entities_mut(&mut self, e_type: &EntityType) -> &mut Vec<Entity> {
match e_type {
EntityType::Character => &mut self.characters,
EntityType::Player => unimplemented!("No players for now"),
EntityType::Town => &mut self.towns,
EntityType::Monster => &mut self.calamities,
EntityType::Calamity => &mut self.calamities,
EntityType::Organization => &mut self.organizations,
EntityType::Blocker => &mut self.blockers,
EntityType::Event => &mut self.events,
}
@ -342,6 +394,7 @@ impl EpochInfo {
self.events
.iter_mut()
.chain(self.characters.iter_mut())
.chain(self.organizations.iter_mut())
.chain(self.towns.iter_mut())
.chain(self.calamities.iter_mut())
.chain(self.blockers.iter_mut())
@ -381,6 +434,177 @@ impl EpochInfo {
impl Symbols for EpochId {
fn to_symbol(&self) -> String {
format!("[󰹻 {:<2}]", self)
format!("[{} {:<2}]", crate::output::symbol("󰹻", "epoch"), self)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stats::Role;
fn entity(id: u128, name: &str, entity_type: EntityType) -> Entity {
let mut entity = Entity::default();
entity.id = Uuid::from_u128(id);
entity.name = name.into();
entity.entity_type = entity_type;
entity
}
fn populated_epoch() -> EpochInfo {
let mut epoch = EpochInfo::default();
epoch
.events
.push(entity(1, "Coronation", EntityType::Event));
epoch
.characters
.push(entity(2, "Aria", EntityType::Character));
epoch
.organizations
.push(entity(3, "Guild", EntityType::Organization));
epoch.towns.push(entity(4, "Haven", EntityType::Town));
epoch
.calamities
.push(entity(5, "Flood", EntityType::Calamity));
epoch.blockers.push(entity(6, "Gate", EntityType::Blocker));
epoch
}
#[test]
fn entity_collections_are_selected_for_every_stored_type() {
let mut epoch = populated_epoch();
for entity_type in [
EntityType::Event,
EntityType::Character,
EntityType::Organization,
EntityType::Town,
EntityType::Calamity,
EntityType::Blocker,
] {
assert_eq!(epoch.vec_entities(&entity_type).len(), 1);
epoch.vec_entities_mut(&entity_type)[0].description = "visited".into();
}
assert_eq!(
epoch
.iter_all_entities_mut()
.filter(|entity| entity.description == "visited")
.count(),
6
);
}
#[test]
fn lookup_supports_names_prefixes_ids_and_strict_types() {
let mut epoch = populated_epoch();
assert_eq!(
epoch
.find_any_entity(EntityIdentifier::Name("ar".into()))
.expect("name prefix")
.name,
"Aria"
);
assert_eq!(
epoch
.find_any_entity(EntityIdentifier::Id("00000000-0000".into()))
.expect("id prefix")
.name,
"Coronation"
);
assert_eq!(
epoch
.find_entity_of_type(
&Some(EntityIdentifier::Name("hav".into())),
&EntityType::Town,
)
.expect("typed lookup")
.id,
Uuid::from_u128(4)
);
assert!(
epoch
.find_entity_strict(Uuid::from_u128(4), Some(EntityType::Character))
.is_err()
);
epoch
.find_entity_strict_as_mut(Uuid::from_u128(4), None)
.expect("mutable lookup")
.name = "New Haven".into();
assert_eq!(
epoch
.find_entity_strict(Uuid::from_u128(4), Some(EntityType::Town))
.expect("strict lookup")
.name,
"New Haven"
);
assert!(
epoch
.find_any_entity(EntityIdentifier::Name("missing".into()))
.is_err()
);
}
#[test]
fn link_remove_and_swap_operations_preserve_collection_integrity() {
let mut epoch = populated_epoch();
let link = TypedLink::new(Uuid::from_u128(4), Role::Capital, EntityType::Town);
epoch
.add_to_links(Uuid::from_u128(2), &EntityType::Character, link)
.expect("add link");
epoch
.del_from_links(Uuid::from_u128(2), &EntityType::Character, link)
.expect("delete link");
assert!(
epoch
.add_to_links(Uuid::from_u128(99), &EntityType::Character, link)
.is_err()
);
let mut replacement = entity(2, "Aria II", EntityType::Character);
replacement.description = "replacement".into();
let old = epoch.swap_entity(replacement).expect("swap entity");
assert_eq!(old.name, "Aria");
assert_eq!(epoch.characters[0].name, "Aria II");
assert!(
epoch
.swap_entity(entity(99, "Nobody", EntityType::Character))
.is_err()
);
let removed = epoch
.remove_entity(
&Some(EntityIdentifier::Name("aria".into())),
&EntityType::Character,
)
.expect("remove entity");
assert_eq!(removed.id, Uuid::from_u128(2));
assert!(epoch.characters.is_empty());
}
#[test]
fn positions_resolve_from_exact_grid_and_entity_references() {
let mut epoch = populated_epoch();
epoch.towns[0].modify_position("12,34".parse().expect("position"));
assert_eq!(
epoch
.resolve_position(&"1,2".parse().expect("exact position"))
.expect("exact")
.to_inner(),
(1, 2)
);
assert_eq!(
epoch
.resolve_position(&"~2,3".parse().expect("grid position"))
.expect("grid")
.to_inner(),
(400, 600)
);
assert_eq!(
epoch
.resolve_position(&PositionIdentifier::Id(EntityIdentifier::Name(
"haven".into(),
)))
.expect("entity")
.to_inner(),
(12, 34)
);
}
}

View File

@ -7,7 +7,7 @@
use cli_table::{Style, Table, WithTitle};
use serde::Serialize;
use std::{fmt::Display, fs::File, io::Write};
use std::{fmt::Display, io::Write, path::Path};
use uuid::Uuid;
use crate::{epoch::SaveMode, error::EpochError, items_table};
@ -95,13 +95,22 @@ pub trait ConfigWritable: Serialize {
do_not_erase: &SaveMode,
// advice: Option<String>,
) -> Result<(), EpochError> {
let mut f = match *do_not_erase {
SaveMode::Erase => File::create(self.save_path()),
SaveMode::DoNotErase => File::create_new(self.save_path()),
}
.map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
write!(f, "{}", self.as_json(action_description.to_owned())?)
let save_path = self.save_path();
let destination = Path::new(&save_path);
let parent = destination.parent().unwrap_or_else(|| Path::new("."));
let json = self.as_json(action_description.to_owned())?;
let mut temporary = tempfile::NamedTempFile::new_in(parent)
.map_err(|error| EpochError::ConfigCreation(save_path.clone(), error))?;
temporary
.write_all(json.as_bytes())
.and_then(|_| temporary.as_file().sync_all())
.map_err(EpochError::ConfigWrite)?;
let persisted = match *do_not_erase {
SaveMode::Erase => temporary.persist(destination),
SaveMode::DoNotErase => temporary.persist_noclobber(destination),
};
persisted.map_err(|error| EpochError::ConfigCreation(save_path, error.error))?;
Ok(())
}
}
@ -184,6 +193,55 @@ mod tests {
assert_snapshot!(json);
}
#[test]
fn save_with_context_atomically_replaces_existing_content() {
let directory = tempdir().expect("temporary directory");
let path = directory.path().join("dummy.json");
std::fs::write(&path, "old content").expect("seed destination");
let item = DummyItem {
id: Uuid::nil(),
value: 42,
save: path.to_string_lossy().into_owned(),
};
item.save_with_context("replace test", &SaveMode::Erase)
.expect("replace destination");
let saved: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(&path).expect("read replaced destination"),
)
.expect("valid JSON");
assert_eq!(saved["value"], 42);
assert_eq!(
std::fs::read_dir(directory.path())
.expect("list temporary directory")
.count(),
1,
"the temporary file must be removed after persistence"
);
}
#[test]
fn save_with_context_does_not_clobber_when_forbidden() {
let directory = tempdir().expect("temporary directory");
let path = directory.path().join("dummy.json");
std::fs::write(&path, "keep this").expect("seed destination");
let item = DummyItem {
id: Uuid::nil(),
value: 42,
save: path.to_string_lossy().into_owned(),
};
assert!(
item.save_with_context("no-clobber test", &SaveMode::DoNotErase)
.is_err()
);
assert_eq!(
std::fs::read_to_string(path).expect("read preserved destination"),
"keep this"
);
}
// fn dummy_with_tempfile(value: i32) -> (DummyItem, std::path::PathBuf) {
// let dummy = DummyItem::new(value);
// (dummy.clone(), dummy.save.clone().into())

112
lib_efo/src/epoch/index.rs Normal file
View File

@ -0,0 +1,112 @@
//! Ephemeral indexes over the vector-backed persisted world.
//!
//! Repository files deliberately retain ordered vectors for compatibility and
//! deterministic output. `EntityIndex` can be rebuilt cheaply after a world
//! mutation and gives read-heavy operations hash-based exact lookup without
//! becoming another piece of state that can go stale on disk.
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
use crate::{entity::Entity, stats::EntityType};
use super::EpochInfo;
/// An entity's stable collection and current offset within that collection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EntityLocation {
/// Persisted entity collection.
pub entity_type: EntityType,
/// Offset in the collection's vector.
pub index: usize,
}
/// A rebuildable UUID and normalized-name index for one world snapshot.
#[derive(Debug, Clone, Default)]
pub struct EntityIndex {
/// First location seen for each UUID.
by_id: HashMap<Uuid, EntityLocation>,
/// Every location sharing the same case-insensitive name.
by_name: HashMap<String, Vec<EntityLocation>>,
/// UUIDs occurring more than once across any collection.
duplicate_ids: HashSet<Uuid>,
}
impl EntityIndex {
/// Build an index without changing the world or its serialized form.
#[must_use]
pub fn build(world: &EpochInfo) -> Self {
let mut result = Self::default();
for entity_type in [
EntityType::Character,
EntityType::Town,
EntityType::Event,
EntityType::Calamity,
EntityType::Organization,
EntityType::Blocker,
] {
for (index, entity) in world.vec_entities(&entity_type).iter().enumerate() {
let location = EntityLocation { entity_type, index };
if result.by_id.insert(entity.id, location).is_some() {
result.duplicate_ids.insert(entity.id);
}
result
.by_name
.entry(normalize_name(&entity.name))
.or_default()
.push(location);
}
}
result
}
/// Return the indexed location for an exact UUID.
#[must_use]
pub fn location_by_id(&self, id: Uuid) -> Option<EntityLocation> {
self.by_id.get(&id).copied()
}
/// Return every entity whose full name matches case-insensitively.
#[must_use]
pub fn locations_by_name(&self, name: &str) -> &[EntityLocation] {
self.by_name
.get(&normalize_name(name))
.map_or(&[], Vec::as_slice)
}
/// Resolve a previously indexed location against the unchanged world.
#[must_use]
pub fn resolve<'world>(
&self,
world: &'world EpochInfo,
location: EntityLocation,
) -> Option<&'world Entity> {
world
.vec_entities(&location.entity_type)
.get(location.index)
}
/// UUIDs that occur more than once, in unspecified order.
#[must_use]
pub fn duplicate_ids(&self) -> &HashSet<Uuid> {
&self.duplicate_ids
}
/// Number of unique UUID keys in the index.
#[must_use]
pub fn len(&self) -> usize {
self.by_id.len()
}
/// Whether the index contains no entities.
#[must_use]
pub fn is_empty(&self) -> bool {
self.by_id.is_empty()
}
}
/// Normalize human names for exact case-insensitive lookup.
fn normalize_name(name: &str) -> String {
name.trim().to_lowercase()
}

View File

@ -88,7 +88,7 @@ pub enum EpochError {
/// Name of the file causing problem
name: String,
/// Trick used to have a cute line showing the following error message
#[label("This file is present and forbid the command to execute properly")]
#[label("This file prevents the command from executing safely")]
show_label: Option<(usize, usize)>,
},
@ -105,7 +105,7 @@ pub enum EpochError {
id: EpochId,
/// The path of the epoch
path: PathBuf,
/// An optionnal help message
/// An optional help message
#[help]
help: Option<String>,
/// The source error
@ -131,15 +131,19 @@ pub enum EpochError {
))]
EpochFolderMissing(EpochId, PathBuf),
/// A future epoch exists, forbidding you to compute `next` and overriding them.
#[diagnostic(help("Use epoch reset if you want to erase all future epochs first"))]
/// A future epoch exists, so computing `next` would overwrite history.
#[diagnostic(help(
"Use `efo prune-future` for recoverable removal or `efo reset --hard` for permanent deletion"
))]
#[error("Cannot compute `next` because future epoch exists")]
#[diagnostic(code(EpochError::FutureEpochExist))]
FutureEpochExist,
/// A specific epoch exists, forbidding the further execution of the command.
#[diagnostic(help("Use epoch reset or manually delete the epoch {0}"))]
#[error("The epoch {0} exists forbidding the execution of the command")]
/// A specific epoch already exists, preventing the requested operation.
#[diagnostic(help(
"Use `efo prune-future` for recoverable removal; do not manually edit epoch directories"
))]
#[error("Epoch {0} already exists, so the operation was not performed")]
#[diagnostic(code(EpochError::EpochAlreadyExists))]
EpochAlreadyExists(EpochId),
@ -170,7 +174,7 @@ pub enum EpochError {
/// The source error
#[source]
source: std::io::Error,
/// An optionnal help message
/// An optional help message
#[help]
help: Option<String>,
/// Where the error originated from
@ -216,7 +220,7 @@ pub enum EpochError {
#[diagnostic(code(EpochError::Unknown))]
Unknown(String),
/// The user tried to parse an acronim that doen't match any stats known to the system.
/// The user supplied an acronym that does not match a known statistic.
#[error("Unknown stat acronym: {0}")]
#[diagnostic(code(EpochError::UnknownStatAcronim))]
UnknownStatAcronim(String),
@ -226,8 +230,16 @@ pub enum EpochError {
#[diagnostic(code(EpochError::IllFormedStatQualifier))]
IllFormedStatQualifier(String),
/// User error, meant to be very explicit over what happened and what to do.
#[error("An user facing error")]
/// The statistic name is recognised but is not stored by this release.
#[error("Statistic `{0}` is not implemented in this release")]
#[diagnostic(code(EpochError::UnsupportedStat))]
#[diagnostic(help(
"Use `efo <entity> add --help` and choose a currently supported statistic."
))]
UnsupportedStat(String),
/// User error with explicit guidance about what happened and what to do.
#[error("A user-facing error occurred")]
#[diagnostic(code(EpochError::UserError))]
UserError(#[help] UserErrors),
@ -238,7 +250,7 @@ pub enum EpochError {
/// The root cause originating the error
cause: String,
#[help]
/// Optionnal help
/// Optional help
help: Option<String>,
},

View File

@ -14,11 +14,20 @@ use crate::epoch::EpochInfo;
#[macro_use]
#[allow(unused_assignments)]
pub mod error;
pub mod adjudication;
pub mod conflict;
pub mod diff;
pub mod entity;
pub mod epoch;
pub mod naming;
pub mod output;
pub mod repository_format;
pub mod simulation;
pub mod stats;
pub mod transaction;
pub mod utils;
pub mod workspace;
pub mod worldgen;
// use std::io::Result as IoResult;
@ -61,9 +70,14 @@ pub mod utils;
/// This allows you to call `full_display`, `short_display` or `oneline_display`
/// directly on a vector of displayable items.
pub trait Displayable {
/// Return a fully-described string representation.
/// Print the fully-described representation for legacy callers.
fn print_full(&self, epoch_info: &EpochInfo) {
println!("{}", self.short_display(epoch_info));
println!("{}", self.full_display(epoch_info));
}
/// Return a fully-described string representation.
fn full_display(&self, epoch_info: &EpochInfo) -> String {
self.short_display(epoch_info)
}
/// Return a short, user-friendly string. Resolves Ids
@ -84,8 +98,11 @@ pub trait Displayable {
/// already implements `Displayable`. This is a **blanket implementation**,
/// so you do not need to write a manual impl for each concrete type
impl<T: Displayable> Displayable for Vec<T> {
fn print_full(&self, epoch_info: &EpochInfo) {
self.iter().for_each(|e| e.print_full(epoch_info));
fn full_display(&self, epoch_info: &EpochInfo) -> String {
self.iter()
.map(|entity| entity.full_display(epoch_info))
.collect::<Vec<_>>()
.join("\n")
}
fn short_display(&self, epoch_info: &EpochInfo) -> String {

View File

@ -3,10 +3,7 @@
use once_cell::sync::Lazy;
use rand::prelude::*;
use serde::{Deserialize, Serialize};
use std::{
fs, io,
path::{Path, PathBuf},
};
use std::{fs, io, path::Path};
use crate::Displayable;
use crate::entity::{EffectApplication, EffectBounds, EntityDuration};
@ -288,7 +285,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}")
}
}
@ -305,15 +302,12 @@ impl NamingData {
/// `include_str!` pulls the file at compile time.
const DEFAULT_JSON_STR: &str = include_str!("../naming.json");
/// Helper that determines the *runtime* location of the `naming.json` file.
fn naming_file_path() -> PathBuf {
PathBuf::from("naming.json")
}
/// Global instance that is lazily initialised on first use.
/// Global naming data loaded from the JSON embedded in the binary.
///
/// Generating a name is deliberately read-only and never creates files in the
/// user's world repository.
pub static NAMING: Lazy<NamingData> = Lazy::new(|| {
let path = naming_file_path();
NamingData::load_or_create(path).expect("Failed to load naming data")
serde_json::from_str(DEFAULT_JSON_STR).expect("embedded naming data must be valid")
});
#[cfg(test)]

12
lib_efo/src/output.rs Normal file
View File

@ -0,0 +1,12 @@
//! Compile-time selection of decorative terminal symbols.
/// Select a Nerd Font icon in default builds and a portable Unicode fallback
/// when the `nerd-fonts` feature is disabled.
#[must_use]
pub const fn symbol(nerd_font: &'static str, portable: &'static str) -> &'static str {
if cfg!(feature = "nerd-fonts") {
nerd_font
} else {
portable
}
}

View File

@ -0,0 +1,158 @@
//! Versioned persistence types for the reversible repository format.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::epoch::{EpochId, EpochInfo};
/// A persisted repository-format version, independent of the application version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct FormatVersion {
/// Compatibility-breaking format generation.
pub major: u32,
/// Backwards-compatible format revision within a generation.
pub minor: u32,
}
impl std::fmt::Display for FormatVersion {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}.{}", self.major, self.minor)
}
}
/// The only repository format supported by this pre-release build.
pub const CURRENT_FORMAT_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 };
/// The version-2 repository manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepositoryManifest {
/// On-disk format discriminator.
pub format_version: FormatVersion,
/// Stable identity shared by the manifest and transient snapshots.
pub repository_id: Uuid,
/// The immutable snapshot currently selected as HEAD.
pub epoch_id: EpochId,
/// The next epoch identifier; committed IDs are never reused.
pub next_epoch_id: EpochId,
/// The application version that last wrote the manifest.
pub version: String,
/// User-facing names for epochs.
#[serde(default)]
pub tags: BTreeMap<String, EpochId>,
}
impl RepositoryManifest {
/// Construct a manifest while enforcing the current format discriminator.
pub fn new(
repository_id: Uuid,
epoch_id: EpochId,
next_epoch_id: EpochId,
version: String,
tags: BTreeMap<String, EpochId>,
) -> Self {
Self {
format_version: CURRENT_FORMAT_VERSION,
repository_id,
epoch_id,
next_epoch_id,
version,
tags,
}
}
}
/// A complete version-2 index or worktree snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositorySnapshot {
/// Snapshot format discriminator.
pub format_version: FormatVersion,
/// Identity of the repository that owns this snapshot.
pub repository_id: Uuid,
/// HEAD epoch from which the snapshot was derived.
pub base_epoch_id: EpochId,
/// Complete editable world state.
pub world: EpochInfo,
}
impl RepositorySnapshot {
/// Create a complete transient snapshot for the current format.
pub fn new(repository_id: Uuid, base_epoch_id: EpochId, world: EpochInfo) -> Self {
Self {
format_version: CURRENT_FORMAT_VERSION,
repository_id,
base_epoch_id,
world,
}
}
}
/// Failure to identify a supported repository manifest.
#[derive(Debug, thiserror::Error)]
pub enum FormatError {
/// JSON was malformed or did not satisfy the selected schema.
#[error("repository manifest is invalid: {0}")]
Invalid(#[from] serde_json::Error),
/// A future or otherwise unsupported format was requested.
#[error("repository format {found} is unsupported; this build supports {supported}")]
Unsupported {
/// Unsupported stored format.
found: FormatVersion,
/// Latest supported format.
supported: FormatVersion,
},
}
/// Decode a manifest and reject formats this build cannot safely understand.
pub fn decode_manifest(bytes: &[u8]) -> Result<RepositoryManifest, FormatError> {
let manifest: RepositoryManifest = serde_json::from_slice(bytes)?;
if manifest.format_version.major != CURRENT_FORMAT_VERSION.major
|| manifest.format_version.minor > CURRENT_FORMAT_VERSION.minor
{
return Err(FormatError::Unsupported {
found: manifest.format_version,
supported: CURRENT_FORMAT_VERSION,
});
}
Ok(manifest)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_format_is_rejected() {
let error = decode_manifest(br#"{"epoch_id":{"id":3},"version":"0.1","tags":{}}"#)
.expect_err("unversioned manifest");
assert!(matches!(error, FormatError::Invalid(_)));
}
#[test]
fn explicit_discriminator_selects_current_reader() {
let manifest = RepositoryManifest::new(
Uuid::nil(),
EpochId::new(3),
EpochId::new(8),
"0.2".to_owned(),
BTreeMap::new(),
);
let bytes = serde_json::to_vec(&manifest).expect("serialize manifest");
let decoded = decode_manifest(&bytes).expect("current manifest");
assert_eq!(decoded, manifest);
}
#[test]
fn unknown_formats_are_not_guessed() {
let bytes = br#"{"format_version":{"major":2,"minor":0},"repository_id":"00000000-0000-0000-0000-000000000000","epoch_id":{"id":0},"next_epoch_id":{"id":1},"version":"test","tags":{}}"#;
let error = decode_manifest(bytes).expect_err("unsupported");
assert!(matches!(
error,
FormatError::Unsupported {
found: FormatVersion { major: 2, minor: 0 },
..
}
));
}
}

574
lib_efo/src/simulation.rs Normal file
View File

@ -0,0 +1,574 @@
//! Deterministic spatial travel primitives.
use std::{
cmp::Reverse,
collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet},
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{epoch::EpochInfo, stats::Position};
/// An undirected, stable road between two towns.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Road {
/// Stable road identity.
pub id: Uuid,
/// First town endpoint.
pub from: Uuid,
/// Second town endpoint.
pub to: Uuid,
/// Travel speed as a percentage of one map unit per tick.
pub speed_percent: u32,
/// Setting-specific searchable labels.
#[serde(default)]
pub tags: Vec<String>,
}
/// Persisted character relationship to space.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum MobilityState {
/// Character remains tied to one town.
Resident {
/// Town containing the resident.
place: Uuid,
},
/// Character is not tied to a town and may travel directly.
Roaming {
/// Current unconstrained position.
position: Position,
},
/// Character is following a reviewable travel plan.
Travelling {
/// Position at the start of this plan.
origin: Position,
/// Destination town.
destination: Uuid,
/// Towns selected by the pathfinder, including destination.
route: Vec<Uuid>,
/// Applied ticks.
elapsed_ticks: u64,
/// Ticks required to arrive.
total_ticks: u64,
},
}
/// A deterministic route preview.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TravelPlan {
/// Towns traversed; empty means direct off-road travel.
pub route: Vec<Uuid>,
/// Required simulation ticks.
pub total_ticks: u64,
/// Whether the selected route uses roads.
pub uses_roads: bool,
}
/// Scheduled arrival of an event at one town.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffusionTarget {
/// Destination town.
pub town: Uuid,
/// Tick, relative to diffusion start, when the event arrives.
pub arrival_tick: u64,
/// Town route used; empty means direct spatial diffusion.
pub route: Vec<Uuid>,
}
/// Persisted frontier and affected-set for one diffusing event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffusionState {
/// Event's immutable origin for this run.
pub origin: Position,
/// Applied simulation ticks.
pub elapsed_ticks: u64,
/// Optional tick at which propagation stops.
pub expires_after: Option<u64>,
/// Deterministically ordered arrival schedule.
pub frontier: Vec<DiffusionTarget>,
/// Towns already reached, preventing repeated effects.
#[serde(default)]
pub affected: BTreeSet<Uuid>,
/// Reached towns waiting for a game-master ruling.
#[serde(default)]
pub pending: BTreeSet<Uuid>,
/// Towns and characters resolved to durable adjudication records.
#[serde(default)]
pub resolved: BTreeMap<Uuid, Uuid>,
/// Whether expiry has already stopped this event.
#[serde(default)]
pub expired: bool,
}
/// Result of previewing or applying a diffusion tick.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffusionTick {
/// Newly reached `(event, town)` pairs.
pub reached: Vec<(Uuid, Uuid)>,
/// Events removed because their expiry was reached.
pub expired: Vec<Uuid>,
}
/// Invalid topology or travel request.
#[derive(Debug, thiserror::Error)]
pub enum SimulationError {
/// A destroyed event cannot begin another diffusion.
#[error(
"event @{0} was destroyed by adjudication; restore or revert that ruling before diffusing it"
)]
EventDestroyed(Uuid),
/// A referenced character does not exist.
#[error("character @{0} does not exist")]
CharacterMissing(Uuid),
/// A referenced town does not exist.
#[error("town @{0} does not exist")]
TownMissing(Uuid),
/// A road violates a topology invariant.
#[error("invalid road @{id}: {reason}")]
InvalidRoad {
/// Offending road identity.
id: Uuid,
/// Violated invariant.
reason: String,
},
/// Travel speed must be positive.
#[error("off-road speed must be greater than zero")]
InvalidSpeed,
/// A referenced event does not exist.
#[error("event @{0} does not exist")]
EventMissing(Uuid),
/// Persisted diffusion state violates an invariant.
#[error("invalid diffusion for event @{event}: {reason}")]
InvalidDiffusion {
/// Event owning the state.
event: Uuid,
/// Violated invariant.
reason: String,
},
}
/// Validate road identities, endpoints, and speeds.
pub fn validate_roads(world: &EpochInfo) -> Result<(), SimulationError> {
let towns = world
.towns
.iter()
.map(|town| town.id)
.collect::<HashSet<_>>();
let mut ids = HashSet::new();
let mut edges = HashSet::new();
for road in &world.roads {
let edge = if road.from < road.to {
(road.from, road.to)
} else {
(road.to, road.from)
};
let reason = if road.id.is_nil() || !ids.insert(road.id) {
Some("missing or duplicate identity")
} else if road.from == road.to {
Some("endpoints are identical")
} else if !towns.contains(&road.from) || !towns.contains(&road.to) {
Some("endpoint is not a town")
} else if road.speed_percent == 0 {
Some("speed percentage is zero")
} else if !edges.insert(edge) {
Some("duplicate endpoints")
} else {
None
};
if let Some(reason) = reason {
return Err(SimulationError::InvalidRoad {
id: road.id,
reason: reason.into(),
});
}
}
Ok(())
}
/// Validate that mobility keys and place references match stored entities.
pub fn validate_mobility(world: &EpochInfo) -> Result<(), SimulationError> {
let characters = world
.characters
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
let towns = world
.towns
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
for (character, state) in &world.mobility {
if !characters.contains(character) {
return Err(SimulationError::CharacterMissing(*character));
}
let place = match state {
MobilityState::Resident { place } => Some(*place),
MobilityState::Travelling { destination, .. } => Some(*destination),
MobilityState::Roaming { .. } => None,
};
if let Some(place) = place
&& !towns.contains(&place)
{
return Err(SimulationError::TownMissing(place));
}
}
Ok(())
}
/// Validate persisted diffusion references and frontier ordering.
pub fn validate_diffusions(world: &EpochInfo) -> Result<(), SimulationError> {
let events = world
.events
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
let towns = world
.towns
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
for (event, state) in &world.diffusions {
if !events.contains(event) {
return Err(SimulationError::EventMissing(*event));
}
let mut previous = None;
for target in &state.frontier {
if !towns.contains(&target.town)
|| target.route.iter().any(|town| !towns.contains(town))
{
return Err(SimulationError::TownMissing(target.town));
}
let key = (target.arrival_tick, target.town);
if previous.is_some_and(|prior| prior > key) {
return Err(SimulationError::InvalidDiffusion {
event: *event,
reason: "frontier is not deterministically ordered".into(),
});
}
previous = Some(key);
}
if state
.pending
.iter()
.any(|town| !towns.contains(town) || !state.affected.contains(town))
{
return Err(SimulationError::InvalidDiffusion {
event: *event,
reason: "pending arrival refers to a missing town".into(),
});
}
if state.resolved.iter().any(|(target, record)| {
world.find_entity_strict(*target, None).is_err()
|| !world.adjudications.contains_key(record)
}) {
return Err(SimulationError::InvalidDiffusion {
event: *event,
reason: "resolved target refers to a missing adjudication".into(),
});
}
}
Ok(())
}
/// Build a deterministic diffusion schedule without changing the world.
pub fn plan_diffusion(
world: &EpochInfo,
event: Uuid,
road_speed: u32,
direct_speed: u32,
expires_after: Option<u64>,
) -> Result<DiffusionState, SimulationError> {
validate_roads(world)?;
if world
.event_adjudications
.get(&event)
.is_some_and(|state| state.destroyed)
{
return Err(SimulationError::EventDestroyed(event));
}
if road_speed == 0 || direct_speed == 0 {
return Err(SimulationError::InvalidSpeed);
}
let source = world
.events
.iter()
.find(|entity| entity.id == event)
.ok_or(SimulationError::EventMissing(event))?;
let origin = source.position().clone();
let origin_town = world
.towns
.iter()
.filter(|town| town.position() == &origin)
.map(|town| town.id)
.min();
let mut frontier = world
.towns
.iter()
.map(|town| {
let direct = ticks(&origin, town.position(), direct_speed);
let road =
origin_town.and_then(|start| road_route_scaled(world, start, town.id, road_speed));
match road {
Some((cost, route)) if cost <= direct => DiffusionTarget {
town: town.id,
arrival_tick: cost,
route,
},
_ => DiffusionTarget {
town: town.id,
arrival_tick: direct,
route: Vec::new(),
},
}
})
.collect::<Vec<_>>();
frontier.sort_unstable_by_key(|target| (target.arrival_tick, target.town));
Ok(DiffusionState {
origin,
elapsed_ticks: 0,
expires_after,
frontier,
affected: BTreeSet::new(),
pending: BTreeSet::new(),
resolved: BTreeMap::new(),
expired: false,
})
}
/// Store a previously previewed diffusion schedule.
pub fn begin_diffusion(world: &mut EpochInfo, event: Uuid, state: DiffusionState) {
world.diffusions.insert(event, state);
}
/// Advance all event frontiers once without reaching a town twice.
pub fn tick_diffusion(world: &mut EpochInfo, amount: u64) -> DiffusionTick {
let mut reached = Vec::new();
let mut expired = Vec::new();
for (event, state) in &mut world.diffusions {
if state.expired {
continue;
}
state.elapsed_ticks = state.elapsed_ticks.saturating_add(amount);
let limit = state.expires_after.unwrap_or(u64::MAX);
for target in &state.frontier {
if target.arrival_tick <= state.elapsed_ticks.min(limit)
&& state.affected.insert(target.town)
{
state.pending.insert(target.town);
reached.push((*event, target.town));
}
}
if state
.expires_after
.is_some_and(|expiry| state.elapsed_ticks >= expiry)
{
state.expired = true;
expired.push(*event);
}
}
reached.sort_unstable();
expired.sort_unstable();
DiffusionTick { reached, expired }
}
/// Select the fastest road route, falling back to slower direct travel.
pub fn plan_travel(
world: &EpochInfo,
character: Uuid,
destination: Uuid,
offroad_speed: u32,
) -> Result<TravelPlan, SimulationError> {
validate_roads(world)?;
if offroad_speed == 0 {
return Err(SimulationError::InvalidSpeed);
}
let person = world
.characters
.iter()
.find(|entity| entity.id == character)
.ok_or(SimulationError::CharacterMissing(character))?;
let target = world
.towns
.iter()
.find(|entity| entity.id == destination)
.ok_or(SimulationError::TownMissing(destination))?;
let direct = ticks(person.position(), target.position(), offroad_speed);
let start = world
.mobility
.get(&character)
.and_then(|state| match state {
MobilityState::Resident { place } => Some(*place),
_ => None,
})
.or_else(|| {
world
.towns
.iter()
.find(|town| town.position() == person.position())
.map(|town| town.id)
});
let Some(start) = start else {
return Ok(TravelPlan {
route: Vec::new(),
total_ticks: direct,
uses_roads: false,
});
};
let Some((cost, route)) = road_route(world, start, destination) else {
return Ok(TravelPlan {
route: Vec::new(),
total_ticks: direct,
uses_roads: false,
});
};
if cost < direct {
Ok(TravelPlan {
route,
total_ticks: cost,
uses_roads: true,
})
} else {
Ok(TravelPlan {
route: Vec::new(),
total_ticks: direct,
uses_roads: false,
})
}
}
/// Store a previewed plan as worktree travel intent.
pub fn begin_travel(
world: &mut EpochInfo,
character: Uuid,
destination: Uuid,
plan: &TravelPlan,
) -> Result<(), SimulationError> {
let origin = world
.characters
.iter()
.find(|entity| entity.id == character)
.ok_or(SimulationError::CharacterMissing(character))?
.position()
.clone();
world.mobility.insert(
character,
MobilityState::Travelling {
origin,
destination,
route: plan.route.clone(),
elapsed_ticks: 0,
total_ticks: plan.total_ticks,
},
);
Ok(())
}
/// Advance every active journey and return the characters that arrived.
pub fn tick_travel(world: &mut EpochInfo, amount: u64) -> Vec<Uuid> {
let towns = world
.towns
.iter()
.map(|town| (town.id, town.position().clone()))
.collect::<HashMap<_, _>>();
let mut arrived = Vec::new();
for (character, state) in &mut world.mobility {
if let MobilityState::Travelling {
destination,
elapsed_ticks,
total_ticks,
..
} = state
{
*elapsed_ticks = elapsed_ticks.saturating_add(amount).min(*total_ticks);
if *elapsed_ticks == *total_ticks {
if let Some(position) = towns.get(destination)
&& let Some(entity) = world
.characters
.iter_mut()
.find(|entity| entity.id == *character)
{
entity.modify_position(position.clone());
}
let place = *destination;
*state = MobilityState::Resident { place };
arrived.push(*character);
}
}
}
arrived.sort_unstable();
arrived
}
/// Find the deterministic shortest road-time path.
fn road_route(world: &EpochInfo, start: Uuid, destination: Uuid) -> Option<(u64, Vec<Uuid>)> {
road_route_scaled(world, start, destination, 100)
}
/// Find a shortest road path with an additional propagation speed multiplier.
fn road_route_scaled(
world: &EpochInfo,
start: Uuid,
destination: Uuid,
speed_scale: u32,
) -> Option<(u64, Vec<Uuid>)> {
if start == destination {
return Some((0, vec![destination]));
}
let towns = world
.towns
.iter()
.map(|town| (town.id, town.position()))
.collect::<HashMap<_, _>>();
let mut graph: HashMap<Uuid, Vec<(Uuid, u64)>> = HashMap::new();
for road in &world.roads {
let effective_speed = u64::from(road.speed_percent)
.saturating_mul(u64::from(speed_scale))
.div_ceil(100)
.min(u64::from(u32::MAX)) as u32;
let cost = ticks(towns[&road.from], towns[&road.to], effective_speed.max(1));
graph.entry(road.from).or_default().push((road.to, cost));
graph.entry(road.to).or_default().push((road.from, cost));
}
for edges in graph.values_mut() {
edges.sort_unstable_by_key(|edge| edge.0);
}
let mut distances = HashMap::from([(start, 0_u64)]);
let mut previous = BTreeMap::new();
let mut queue = BinaryHeap::from([Reverse((0_u64, start))]);
while let Some(Reverse((cost, node))) = queue.pop() {
if node == destination {
break;
}
if cost > *distances.get(&node).unwrap_or(&u64::MAX) {
continue;
}
for &(next, edge) in graph.get(&node).map_or(&[][..], Vec::as_slice) {
let candidate = cost.saturating_add(edge);
if candidate < *distances.get(&next).unwrap_or(&u64::MAX) {
distances.insert(next, candidate);
previous.insert(next, node);
queue.push(Reverse((candidate, next)));
}
}
}
let cost = *distances.get(&destination)?;
let mut route = vec![destination];
let mut cursor = destination;
while cursor != start {
cursor = *previous.get(&cursor)?;
route.push(cursor);
}
route.reverse();
Some((cost, route))
}
/// Convert geometric distance and integer speed into at least one tick.
fn ticks(from: &Position, to: &Position, speed_percent: u32) -> u64 {
let distance = from.distance(to).unsigned_abs() as u64;
distance
.saturating_mul(100)
.div_ceil(u64::from(speed_percent))
.max(1)
}

View File

@ -251,6 +251,71 @@ fn color_cell_categories(cell: CellStruct, value: &GenericStat) -> CellStruct {
}
impl OverallStats {
/// Clamp user-editable values to the supported simulation domain.
///
/// Population is an unbounded non-negative count. Growth and event/blocker
/// modifiers may be negative; other normalised values use `0..=120`.
pub fn clamp_for(&mut self, kind: EntityType) {
let modifier = matches!(kind, EntityType::Event | EntityType::Blocker);
self.population = GenericStat(if modifier {
(*self.population).max(-120)
} else {
(*self.population).max(0)
});
self.growth_rate = GenericStat((*self.growth_rate).clamp(-120, 120));
let minimum = if modifier { -120 } else { 0 };
for value in [
&mut self.crime,
&mut self.happiness,
&mut self.food,
&mut self.industry,
&mut self.science,
&mut self.trade,
&mut self.army,
&mut self.strength,
&mut self.fortification,
&mut self.threat,
&mut self.bureaucracy,
&mut self.transportation,
&mut self.sprawl,
&mut self.health,
] {
*value = GenericStat((**value).clamp(minimum, 120));
}
self.update();
}
/// Whether all editable values already satisfy the persisted domain.
pub fn is_bounded_for(&self, kind: EntityType) -> bool {
let mut copy = self.clone();
copy.clamp_for(kind);
let fields = [
ListStats::Demographics,
ListStats::Population,
ListStats::Growthrate,
ListStats::Crime,
ListStats::Happiness,
ListStats::Economy,
ListStats::Food,
ListStats::Industry,
ListStats::Science,
ListStats::Trade,
ListStats::Military,
ListStats::Army,
ListStats::Strength,
ListStats::Fortification,
ListStats::Threat,
ListStats::Infrastructure,
ListStats::Bureaucracy,
ListStats::Transportation,
ListStats::Sprawl,
ListStats::Health,
];
fields
.iter()
.all(|field| self.get_field(field) == copy.get_field(field))
}
/// Create Stats with a given rng distribution
pub(crate) fn create_rng(
rng: &RngLevel,
@ -424,7 +489,7 @@ pub struct StatPair {
///
/// The struct is a thin wrapper around a pair of `isize` values
/// representing the X and Y coordinates.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub, Mul)]
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, Add, Sub, Mul)]
pub struct Position(isize, isize);
/// A grid-aligned position used for chunk look-ups.
@ -558,12 +623,14 @@ pub enum ListStats {
/// The list of all types of entities
#[allow(missing_docs)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum EntityType {
Character,
Player,
Town,
Monster,
/// A calamity.
Calamity,
Organization,
Blocker,
#[default]
Event,

View File

@ -1,4 +1,4 @@
//! All traits implementatition for the main structs are deffered here
//! Trait implementations for the primary statistics structures.
#![allow(dead_code)]
use crate::stats::{GameStat, GenericStat, ListStats, OverallStats};
@ -113,11 +113,15 @@ impl OverallStats {
ListStats::Industry => &self.industry,
ListStats::Science => &self.science,
ListStats::Trade => &self.trade,
ListStats::Social => unimplemented!("This version doens't implement this stat"), //&self.social,
ListStats::Culture => unimplemented!("This version doens't implement this stat"), //&self.culture,
ListStats::Education => unimplemented!("This version doens't implement this stat"), //&self.education,
ListStats::Tourism => unimplemented!("This version doens't implement this stat"), //&self.tourism,
ListStats::Influence => unimplemented!("This version doens't implement this stat"), //&self.influence,
ListStats::Social => unimplemented!("this release does not store the social stat"),
ListStats::Culture => unimplemented!("this release does not store the culture stat"),
ListStats::Education => {
unimplemented!("this release does not store the education stat")
}
ListStats::Tourism => unimplemented!("this release does not store the tourism stat"),
ListStats::Influence => {
unimplemented!("this release does not store the influence stat")
}
ListStats::Military => &self.military,
ListStats::Army => &self.army,
ListStats::Strength => &self.strength,
@ -157,11 +161,15 @@ impl OverallStats {
ListStats::Industry => &mut self.industry,
ListStats::Science => &mut self.science,
ListStats::Trade => &mut self.trade,
ListStats::Social => unimplemented!("This version doens't implement this stat"), //&mut self.social,
ListStats::Culture => unimplemented!("This version doens't implement this stat"), //&mut self.culture,
ListStats::Education => unimplemented!("This version doens't implement this stat"), //&mut self.education,
ListStats::Tourism => unimplemented!("This version doens't implement this stat"), //&mut self.tourism,
ListStats::Influence => unimplemented!("This version doens't implement this stat"), //&mut self.influence,
ListStats::Social => unimplemented!("this release does not store the social stat"),
ListStats::Culture => unimplemented!("this release does not store the culture stat"),
ListStats::Education => {
unimplemented!("this release does not store the education stat")
}
ListStats::Tourism => unimplemented!("this release does not store the tourism stat"),
ListStats::Influence => {
unimplemented!("this release does not store the influence stat")
}
ListStats::Military => &mut self.military,
ListStats::Army => &mut self.army,
ListStats::Strength => &mut self.strength,

View File

@ -27,6 +27,16 @@ impl FromStr for StatPair {
};
let stat: ListStats = stat_str.parse()?;
if matches!(
stat,
ListStats::Social
| ListStats::Culture
| ListStats::Education
| ListStats::Tourism
| ListStats::Influence
) {
return Err(EpochError::UnsupportedStat(stat_str.to_owned()));
}
let value: isize = val_str
.parse()
.map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?;
@ -264,10 +274,10 @@ impl FromStr for ListStats {
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"dem" | "demog" | "demographics" | "demo" => Ok(ListStats::Demographics),
"pop" | "popul" | "populations" => Ok(ListStats::Population),
"grow" | "grw" | "growth" => Ok(ListStats::Growthrate),
"cri" | "crim" | "crimes" => Ok(ListStats::Crime),
"hapn" | "happines" | "hap" => Ok(ListStats::Happiness),
"pop" | "popul" | "population" | "populations" => Ok(ListStats::Population),
"grow" | "grw" | "growth" | "growthrate" => Ok(ListStats::Growthrate),
"cri" | "crim" | "crime" | "crimes" => Ok(ListStats::Crime),
"hapn" | "happiness" | "happines" | "hap" => Ok(ListStats::Happiness),
"eco" | "economy" | "econ" => Ok(ListStats::Economy),
"food" | "fo" | "agr" | "agri" | "fod" => Ok(ListStats::Food),
"industry" | "indus" | "ind" => Ok(ListStats::Industry),

View File

@ -5,6 +5,7 @@ expression: out
:[C]
 :[P]
󱡵 :[T]
 :[M]
 :[X]
 :[O]
 :[B]
:[E]

View File

@ -1,5 +1,6 @@
//! All symbol implementations
//!
use crate::output::symbol;
use crate::{
entity::{EffectApplication, EffectBounds, EntityDuration},
stats::{
@ -12,9 +13,9 @@ use colored::Colorize;
impl Symbols for Role {
fn to_symbol(&self) -> String {
match self {
Role::Govern => "".to_string(),
Role::Capital => "".to_string(),
Role::Undefined => "󱣩".to_string(),
Role::Govern => symbol("", "governs ").to_string(),
Role::Capital => symbol("", "capital ").to_string(),
Role::Undefined => symbol("󱣩", "link").to_string(),
}
}
}
@ -25,19 +26,21 @@ impl Symbols for EntityType {
EntityType::Character => "[C]".to_string(),
EntityType::Player => "[P]".to_string(),
EntityType::Town => "[T]".to_string(),
EntityType::Monster => "[M]".to_string(),
EntityType::Calamity => "[X]".to_string(),
EntityType::Organization => "[O]".to_string(),
EntityType::Blocker => "[B]".to_string(),
EntityType::Event => "[E]".to_string(),
}
}
fn to_symbol(&self) -> String {
match self {
EntityType::Character => "".to_string(),
EntityType::Player => "".to_string(),
EntityType::Town => "󱡵 ".to_string(),
EntityType::Monster => "".to_string(),
EntityType::Blocker => "".to_string(),
EntityType::Event => "".to_string(),
EntityType::Character => symbol("", "person").to_string(),
EntityType::Player => symbol("", "player ").to_string(),
EntityType::Town => symbol("󱡵 ", "town ").to_string(),
EntityType::Calamity => symbol("", "calamity ").to_string(),
EntityType::Organization => symbol("", "organisation ").to_string(),
EntityType::Blocker => symbol("", "blocker ").to_string(),
EntityType::Event => symbol("", "event").to_string(),
}
}
}
@ -83,13 +86,13 @@ impl Symbols for OverallStats {
format!(
"{:2}{} {:2}{} {:2}{} {:2}{}",
self.demographics,
"".green(),
symbol("", "dem ").green(),
self.economy,
"💰".yellow(),
self.military,
"".red(),
symbol("", "mil ").red(),
self.infrastructure,
"󰡢".cyan(),
symbol("󰡢", "inf").cyan(),
)
}
}
@ -127,31 +130,31 @@ impl Symbols for ListStats {
}
fn to_symbol(&self) -> String {
match self {
ListStats::Demographics => "".blue(),
ListStats::Population => "".green(),
ListStats::Growthrate => "".green(),
ListStats::Crime => "󱀣".green(),
ListStats::Happiness => "".green(),
ListStats::Demographics => symbol("", "DEM ").blue(),
ListStats::Population => symbol("", "POP ").green(),
ListStats::Growthrate => symbol("", "GRW ").green(),
ListStats::Crime => symbol("󱀣", "CRM").green(),
ListStats::Happiness => symbol("", "HPY ").green(),
ListStats::Economy => "💰".blue(),
ListStats::Food => "󰔬".yellow(),
ListStats::Food => symbol("󰔬", "FOD").yellow(),
ListStats::Industry => "🏭".yellow(),
ListStats::Science => "󰧑 ".yellow(),
ListStats::Trade => "".yellow(),
ListStats::Social => "󱕹 ".blue(),
ListStats::Science => symbol("󰧑 ", "SCI ").yellow(),
ListStats::Trade => symbol("", "TRD ").yellow(),
ListStats::Social => symbol("󱕹 ", "SOC ").blue(),
ListStats::Culture => "🎭".purple(),
ListStats::Education => "📚".purple(),
ListStats::Tourism => "🏖️".purple(),
ListStats::Influence => "🌍".purple(),
ListStats::Military => "🪖".blue(),
ListStats::Army => "".red(),
ListStats::Strength => "󰞇 ".red(),
ListStats::Army => symbol("", "ARM ").red(),
ListStats::Strength => symbol("󰞇 ", "STR ").red(),
ListStats::Fortification => "🔒".red(),
ListStats::Threat => "⚡".red(),
ListStats::Infrastructure => "🏗️ ".blue(),
ListStats::Bureaucracy => "🏛️ ".cyan(),
ListStats::Transportation => "󰔬 ".cyan(),
ListStats::Transportation => symbol("󰔬 ", "TRP ").cyan(),
ListStats::Sprawl => "🏙️".cyan(),
ListStats::Health => "".cyan(),
ListStats::Health => symbol("", "HLT").cyan(),
}
.to_string()
}

View File

@ -90,6 +90,14 @@ fn stat_pair_ill_formed_errors_are_detected() {
let err = stats::StatPair::from_str("unknown:5").unwrap_err();
assert!(matches!(err, EpochError::UnknownStatAcronim(_)));
}
#[test]
fn stat_pair_rejects_recognised_but_unimplemented_stats() {
for name in ["social", "culture", "education", "tourism", "influence"] {
let err = stats::StatPair::from_str(&format!("{name}:10")).unwrap_err();
assert!(matches!(err, EpochError::UnsupportedStat(_)));
}
}
#[test]
fn position_invalid_format_errors_are_detected() {
// 1️⃣ No comma
@ -115,6 +123,7 @@ fn position_invalid_format_errors_are_detected() {
assert!(matches!(err, EpochError::ParsePositionError(_)));
}
#[test]
#[cfg(feature = "nerd-fonts")]
fn test_liststats_aliases() {
// Each tuple: (alias, expected enum variant)
let cases = vec![
@ -246,6 +255,43 @@ fn test_liststats_aliases() {
assert_snapshot!(output);
}
#[test]
fn documented_full_stat_names_parse() {
for (name, expected) in [
("population", stats::ListStats::Population),
("growthrate", stats::ListStats::Growthrate),
("crime", stats::ListStats::Crime),
("happiness", stats::ListStats::Happiness),
] {
assert_eq!(name.parse::<stats::ListStats>().expect(name), expected);
}
}
#[test]
fn stat_domains_preserve_counts_and_clamp_normalised_values() {
let mut persistent = stats::OverallStats {
population: stats::GenericStat(250_000),
growth_rate: stats::GenericStat(-999),
strength: stats::GenericStat(-4),
health: stats::GenericStat(999),
..Default::default()
};
persistent.clamp_for(stats::EntityType::Town);
assert_eq!(*persistent.population, 250_000);
assert_eq!(*persistent.growth_rate, -120);
assert_eq!(*persistent.strength, 0);
assert_eq!(*persistent.health, 120);
assert!(persistent.is_bounded_for(stats::EntityType::Town));
let mut modifier = stats::OverallStats {
food: stats::GenericStat(-999),
..Default::default()
};
modifier.clamp_for(stats::EntityType::Event);
assert_eq!(*modifier.food, -120);
assert!(modifier.is_bounded_for(stats::EntityType::Event));
}
#[test]
fn test_liststats_unknown_alias() {
// Pick a string that is not in the list of known aliases.
@ -262,12 +308,14 @@ fn test_liststats_unknown_alias() {
}
#[test]
#[cfg(feature = "nerd-fonts")]
fn test_entity_type_to_shortest() {
let out = [
stats::EntityType::Character,
stats::EntityType::Player,
stats::EntityType::Town,
stats::EntityType::Monster,
stats::EntityType::Calamity,
stats::EntityType::Organization,
stats::EntityType::Blocker,
stats::EntityType::Event,
]

370
lib_efo/src/transaction.rs Normal file
View File

@ -0,0 +1,370 @@
//! Exclusive repository writes and recoverable single-file transactions.
use std::{
fs::{self, File, OpenOptions},
io::Write,
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
/// Metadata describing the process that owns a repository writer lock.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockInfo {
/// Stable repository identity when a manifest is readable.
pub repository_id: Option<Uuid>,
/// Operating-system process identifier.
pub pid: u32,
/// OS process-start token used to distinguish PID reuse.
pub process_start: String,
/// Host identifier when available.
pub hostname: String,
/// User-facing operation holding the lock.
pub command: String,
/// Unix timestamp at lock acquisition.
pub created_at: u64,
}
/// An exclusively held writer lock, removed automatically on clean exit.
#[derive(Debug)]
pub struct RepositoryLock {
/// Path removed when the guard is dropped.
path: PathBuf,
}
/// Durable record for an interrupted file replacement.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TransactionJournal {
/// Ordered replacements; the manifest must be supplied last.
entries: Vec<TransactionEntry>,
}
/// One recoverable file replacement.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TransactionEntry {
/// Destination path relative to repository root.
destination: PathBuf,
/// Prepared replacement path relative to repository root.
temporary: PathBuf,
/// Optional prior content used for rollback.
backup: Option<PathBuf>,
/// Checksum of the complete replacement.
new_checksum: String,
}
/// Result of inspecting recovery state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveryOutcome {
/// No journal was present.
Clean,
/// A prepared but uncommitted replacement was discarded.
RolledBack,
/// A committed replacement was verified and its journal removed.
Completed,
}
/// Transaction and locking failures.
#[derive(Debug, thiserror::Error)]
pub enum TransactionError {
/// A filesystem operation failed.
#[error("repository transaction failed at `{path}`: {source}")]
Io {
/// Affected path.
path: PathBuf,
/// Underlying error.
#[source]
source: std::io::Error,
},
/// Another writer already owns the repository.
#[error("repository is locked by PID {pid} on {hostname} running `{command}`")]
Locked {
/// Owner process ID.
pid: u32,
/// Owner host.
hostname: String,
/// Owner operation.
command: String,
},
/// Lock data or a transaction journal is malformed.
#[error("repository transaction metadata at `{path}` is invalid: {source}")]
Json {
/// Affected path.
path: PathBuf,
/// Decode error.
#[source]
source: serde_json::Error,
},
/// Recovery cannot safely infer the intended state.
#[error("cannot recover transaction: {0}")]
Ambiguous(String),
}
impl RepositoryLock {
/// Acquire the one exclusive writer slot for a repository.
pub fn acquire(root: &Path, command: impl Into<String>) -> Result<Self, TransactionError> {
let path = root.join(".efo/lock");
let info = LockInfo {
repository_id: repository_id(root),
pid: std::process::id(),
process_start: process_start_token(),
hostname: std::env::var("HOSTNAME").unwrap_or_else(|_| "unknown-host".to_owned()),
command: command.into(),
created_at: now()?,
};
let bytes = serde_json::to_vec_pretty(&info).map_err(|source| TransactionError::Json {
path: path.clone(),
source,
})?;
let mut file = match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => file,
Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
let owner = inspect_lock(root)?;
return Err(TransactionError::Locked {
pid: owner.pid,
hostname: owner.hostname,
command: owner.command,
});
}
Err(source) => return Err(io_error(path, source)),
};
file.write_all(&bytes)
.and_then(|_| file.sync_all())
.map_err(|source| io_error(path.clone(), source))?;
sync_directory(path.parent().unwrap_or(root))?;
Ok(Self { path })
}
}
/// Read repository identity without making lock acquisition depend on it.
fn repository_id(root: &Path) -> Option<Uuid> {
let bytes = fs::read(root.join(".epoch")).ok()?;
crate::repository_format::decode_manifest(&bytes)
.ok()
.map(|manifest| manifest.repository_id)
}
/// Capture a PID-reuse-resistant token where the host exposes one.
fn process_start_token() -> String {
fs::read_to_string(format!("/proc/{}/stat", std::process::id()))
.ok()
.and_then(|stat| stat.split_whitespace().nth(21).map(str::to_owned))
.unwrap_or_else(|| format!("created-{}", now().unwrap_or_default()))
}
impl Drop for RepositoryLock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
if let Some(parent) = self.path.parent() {
let _ = File::open(parent).and_then(|directory| directory.sync_all());
}
}
}
/// Read current writer ownership without modifying the lock.
pub fn inspect_lock(root: &Path) -> Result<LockInfo, TransactionError> {
let path = root.join(".efo/lock");
let bytes = fs::read(&path).map_err(|source| io_error(path.clone(), source))?;
serde_json::from_slice(&bytes).map_err(|source| TransactionError::Json { path, source })
}
/// Break a lock only after the caller has made the explicit safety decision.
pub fn break_lock(root: &Path) -> Result<LockInfo, TransactionError> {
let owner = inspect_lock(root)?;
let path = root.join(".efo/lock");
fs::remove_file(&path).map_err(|source| io_error(path.clone(), source))?;
sync_directory(path.parent().unwrap_or(root))?;
Ok(owner)
}
/// Atomically replace one repository file under an exclusive lock.
pub fn replace_file(
root: &Path,
destination: &Path,
bytes: &[u8],
command: &str,
) -> Result<(), TransactionError> {
replace_files(
root,
&[(destination.to_path_buf(), bytes.to_vec())],
command,
)
}
/// Replace several files under one lock and journal, in the supplied order.
pub fn replace_files(
root: &Path,
replacements: &[(PathBuf, Vec<u8>)],
command: &str,
) -> Result<(), TransactionError> {
let lock = RepositoryLock::acquire(root, command)?;
replace_files_locked(root, replacements, &lock)
}
/// Replace files while retaining the caller's lock across validation and writing.
pub(crate) fn replace_files_locked(
root: &Path,
replacements: &[(PathBuf, Vec<u8>)],
lock: &RepositoryLock,
) -> Result<(), TransactionError> {
if lock.path != root.join(".efo/lock") {
return Err(TransactionError::Ambiguous(
"writer lock belongs to another repository".into(),
));
}
recover_unlocked(root)?;
let workspace = root.join(".efo");
let journal_path = workspace.join("transaction.json");
let mut entries = Vec::new();
for (index, (destination, bytes)) in replacements.iter().enumerate() {
let temporary = workspace.join(format!("transaction-{index}.tmp"));
let backup_path = workspace.join(format!("transaction-{index}.bak"));
write_bytes_synced(&temporary, bytes)?;
let backup = if destination.exists() {
write_bytes_synced(
&backup_path,
&fs::read(destination).map_err(|source| io_error(destination.clone(), source))?,
)?;
Some(
backup_path
.strip_prefix(root)
.map_err(|_| TransactionError::Ambiguous("backup escaped repository".into()))?
.to_path_buf(),
)
} else {
None
};
entries.push(TransactionEntry {
destination: relative(root, destination)?,
temporary: relative(root, &temporary)?,
backup,
new_checksum: checksum(bytes),
});
}
let journal = TransactionJournal { entries };
write_json_synced(&journal_path, &journal)?;
for entry in &journal.entries {
let destination = root.join(&entry.destination);
fs::rename(root.join(&entry.temporary), &destination)
.map_err(|source| io_error(destination.clone(), source))?;
sync_directory(destination.parent().unwrap_or(root))?;
}
cleanup_transaction(root, &journal)?;
fs::remove_file(&journal_path).map_err(|source| io_error(journal_path.clone(), source))?;
sync_directory(&workspace)
}
/// Recover an interrupted replacement while holding a new writer lock.
pub fn recover(root: &Path) -> Result<RecoveryOutcome, TransactionError> {
let _lock = RepositoryLock::acquire(root, "recover")?;
recover_unlocked(root)
}
/// Resolve a journal after exclusive ownership has already been acquired.
fn recover_unlocked(root: &Path) -> Result<RecoveryOutcome, TransactionError> {
let journal_path = root.join(".efo/transaction.json");
if !journal_path.exists() {
return Ok(RecoveryOutcome::Clean);
}
let bytes = fs::read(&journal_path).map_err(|source| io_error(journal_path.clone(), source))?;
let journal: TransactionJournal =
serde_json::from_slice(&bytes).map_err(|source| TransactionError::Json {
path: journal_path.clone(),
source,
})?;
let committed = journal.entries.iter().all(|entry| {
fs::read(root.join(&entry.destination))
.ok()
.is_some_and(|bytes| checksum(&bytes) == entry.new_checksum)
});
let outcome = if committed {
RecoveryOutcome::Completed
} else {
for entry in journal.entries.iter().rev() {
let destination = root.join(&entry.destination);
if let Some(backup) = &entry.backup {
fs::rename(root.join(backup), &destination)
.map_err(|source| io_error(destination, source))?;
} else if destination.exists() {
fs::remove_file(&destination).map_err(|source| io_error(destination, source))?;
}
}
RecoveryOutcome::RolledBack
};
cleanup_transaction(root, &journal)?;
fs::remove_file(&journal_path).map_err(|source| io_error(journal_path.clone(), source))?;
sync_directory(journal_path.parent().unwrap_or(root))?;
Ok(outcome)
}
/// Remove prepared and backup files after commit or recovery.
fn cleanup_transaction(root: &Path, journal: &TransactionJournal) -> Result<(), TransactionError> {
for entry in &journal.entries {
for relative in std::iter::once(&entry.temporary).chain(entry.backup.iter()) {
let path = root.join(relative);
if path.exists() {
fs::remove_file(&path).map_err(|source| io_error(path, source))?;
}
}
}
Ok(())
}
/// Convert an absolute repository path into a journal-safe relative path.
fn relative(root: &Path, path: &Path) -> Result<PathBuf, TransactionError> {
path.strip_prefix(root).map(Path::to_path_buf).map_err(|_| {
TransactionError::Ambiguous(format!("path `{}` escaped repository", path.display()))
})
}
/// Write and flush raw transaction data.
fn write_bytes_synced(path: &Path, bytes: &[u8]) -> Result<(), TransactionError> {
let mut file = File::create(path).map_err(|source| io_error(path.to_path_buf(), source))?;
file.write_all(bytes)
.and_then(|_| file.sync_all())
.map_err(|source| io_error(path.to_path_buf(), source))
}
/// Write durable JSON metadata before a transaction commit point.
fn write_json_synced<T: Serialize>(path: &Path, value: &T) -> Result<(), TransactionError> {
let bytes = serde_json::to_vec_pretty(value).map_err(|source| TransactionError::Json {
path: path.to_path_buf(),
source,
})?;
let mut file = File::create(path).map_err(|source| io_error(path.to_path_buf(), source))?;
file.write_all(&bytes)
.and_then(|_| file.sync_all())
.map_err(|source| io_error(path.to_path_buf(), source))?;
sync_directory(path.parent().unwrap_or_else(|| Path::new(".")))
}
/// Flush directory metadata.
fn sync_directory(path: &Path) -> Result<(), TransactionError> {
File::open(path)
.and_then(|directory| directory.sync_all())
.map_err(|source| io_error(path.to_path_buf(), source))
}
/// Current Unix time for human lock inspection.
fn now() -> Result<u64, TransactionError> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs())
.map_err(|_| TransactionError::Ambiguous("system clock is before Unix epoch".to_owned()))
}
/// Stable accidental-corruption checksum for transaction decisions.
fn checksum(bytes: &[u8]) -> String {
format!(
"{:016x}",
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
(hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3)
})
)
}
/// Attach an affected path to an I/O failure.
fn io_error(path: PathBuf, source: std::io::Error) -> TransactionError {
TransactionError::Io { path, source }
}

1020
lib_efo/src/workspace.rs Normal file

File diff suppressed because it is too large Load Diff

356
lib_efo/src/worldgen.rs Normal file
View File

@ -0,0 +1,356 @@
//! Deterministic, configuration-driven world generation.
use std::{fs, path::Path};
use rand::{Rng, SeedableRng, rngs::StdRng, seq::IndexedRandom};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
entity::Entity,
epoch::EpochInfo,
repository_format::FormatVersion,
stats::{EntityType, Position},
};
/// Schema understood by this build for world-generation configuration.
pub const CURRENT_CONFIG_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 };
/// Embedded, offline-safe default configuration.
pub const DEFAULT_CONFIG_JSON: &str = include_str!("../assets/worldgen/default.json");
/// Amount of state to generate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum GenerationLevel {
/// One positioned event.
Event,
/// One town with residents and a local event.
Settlement,
/// A medium subset of the configured world.
Region,
/// A complete configured world.
World,
}
/// Inclusive entity-count range.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CountRange {
/// Smallest generated count.
pub min: usize,
/// Largest generated count.
pub max: usize,
}
/// Output canvas and coordinate bounds.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanvasConfig {
/// Width in pixels/world units.
pub width: u32,
/// Height in pixels/world units.
pub height: u32,
}
/// Configured ranges for every persisted entity collection.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EntityCounts {
/// Character count.
pub characters: CountRange,
/// Town count.
pub towns: CountRange,
/// Event count.
pub events: CountRange,
/// Calamity count.
pub calamities: CountRange,
/// Organisation count.
pub organisations: CountRange,
/// Blocker count.
pub blockers: CountRange,
}
/// Name pools used by deterministic generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamePools {
/// Character names.
pub characters: Vec<String>,
/// Town names.
pub towns: Vec<String>,
/// Event names.
pub events: Vec<String>,
/// Calamity names.
pub calamities: Vec<String>,
/// Organisation names.
pub organisations: Vec<String>,
/// Blocker names.
pub blockers: Vec<String>,
}
/// Complete versioned input for the generator.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorldGenConfig {
/// Configuration schema, independent from repository format.
pub schema_version: FormatVersion,
/// Spatial bounds.
pub canvas: CanvasConfig,
/// Full-world collection ranges.
pub counts: EntityCounts,
/// User-editable naming pools.
pub names: NamePools,
}
/// Configuration and generation failures.
#[derive(Debug, thiserror::Error)]
pub enum WorldGenError {
/// Reading an external configuration failed.
#[error("cannot read worldgen config `{path}`: {source}")]
Io {
/// Affected file.
path: std::path::PathBuf,
/// Filesystem failure.
#[source]
source: std::io::Error,
},
/// JSON did not match the schema.
#[error("invalid worldgen config `{path}`: {source}")]
Json {
/// Embedded label or external file.
path: std::path::PathBuf,
/// Decode failure.
#[source]
source: serde_json::Error,
},
/// Semantic validation rejected otherwise valid JSON.
#[error("invalid worldgen configuration: {0}")]
Invalid(String),
}
impl WorldGenConfig {
/// Load and validate the embedded defaults.
pub fn embedded() -> Result<Self, WorldGenError> {
Self::decode(
DEFAULT_CONFIG_JSON.as_bytes(),
Path::new("<embedded worldgen config>"),
)
}
/// Load and validate an external override.
pub fn load(path: &Path) -> Result<Self, WorldGenError> {
let bytes = fs::read(path).map_err(|source| WorldGenError::Io {
path: path.to_owned(),
source,
})?;
Self::decode(&bytes, path)
}
/// Decode and validate bytes while retaining their diagnostic source.
fn decode(bytes: &[u8], path: &Path) -> Result<Self, WorldGenError> {
let config: Self = serde_json::from_slice(bytes).map_err(|source| WorldGenError::Json {
path: path.to_owned(),
source,
})?;
config.validate()?;
Ok(config)
}
/// Validate limits before allocation or generation.
pub fn validate(&self) -> Result<(), WorldGenError> {
if self.schema_version != CURRENT_CONFIG_VERSION {
return Err(WorldGenError::Invalid(format!(
"schema {} is unsupported; expected {}",
self.schema_version, CURRENT_CONFIG_VERSION
)));
}
if self.canvas.width == 0
|| self.canvas.height == 0
|| self.canvas.width > 100_000
|| self.canvas.height > 100_000
{
return Err(WorldGenError::Invalid(
"canvas dimensions must each be between 1 and 100000".into(),
));
}
let entries = [
("characters", self.counts.characters, &self.names.characters),
("towns", self.counts.towns, &self.names.towns),
("events", self.counts.events, &self.names.events),
("calamities", self.counts.calamities, &self.names.calamities),
(
"organisations",
self.counts.organisations,
&self.names.organisations,
),
("blockers", self.counts.blockers, &self.names.blockers),
];
for (label, range, names) in entries {
if range.min > range.max || range.max > 10_000 {
return Err(WorldGenError::Invalid(format!(
"{label} count must be ordered and no greater than 10000"
)));
}
if range.max > 0 && names.is_empty() {
return Err(WorldGenError::Invalid(format!(
"{label} names cannot be empty when entities may be generated"
)));
}
}
Ok(())
}
}
/// Generate a deterministic complete snapshot from a validated configuration.
pub fn generate(config: &WorldGenConfig, seed: u64, level: GenerationLevel) -> EpochInfo {
let mut rng = StdRng::seed_from_u64(seed);
let mut world = EpochInfo {
rng_seed: seed,
..EpochInfo::default()
};
let counts = selected_counts(config, level, &mut rng);
world.characters = entities(
&config.names.characters,
counts[0],
EntityType::Character,
config,
&mut rng,
);
world.towns = entities(
&config.names.towns,
counts[1],
EntityType::Town,
config,
&mut rng,
);
world.events = entities(
&config.names.events,
counts[2],
EntityType::Event,
config,
&mut rng,
);
world.calamities = entities(
&config.names.calamities,
counts[3],
EntityType::Calamity,
config,
&mut rng,
);
world.organizations = entities(
&config.names.organisations,
counts[4],
EntityType::Organization,
config,
&mut rng,
);
world.blockers = entities(
&config.names.blockers,
counts[5],
EntityType::Blocker,
config,
&mut rng,
);
world
}
/// Resolve configured ranges into concrete counts for one generation level.
fn selected_counts(
config: &WorldGenConfig,
level: GenerationLevel,
rng: &mut StdRng,
) -> [usize; 6] {
match level {
GenerationLevel::Event => [0, 0, 1, 0, 0, 0],
GenerationLevel::Settlement => [rng.random_range(3..=6), 1, 1, 0, 0, 0],
GenerationLevel::Region => [
pick(config.counts.characters, rng).div_ceil(2),
pick(config.counts.towns, rng).max(1).div_ceil(2),
pick(config.counts.events, rng).max(1).div_ceil(2),
pick(config.counts.calamities, rng).div_ceil(2),
pick(config.counts.organisations, rng).div_ceil(2),
pick(config.counts.blockers, rng).div_ceil(2),
],
GenerationLevel::World => [
pick(config.counts.characters, rng),
pick(config.counts.towns, rng),
pick(config.counts.events, rng),
pick(config.counts.calamities, rng),
pick(config.counts.organisations, rng),
pick(config.counts.blockers, rng),
],
}
}
/// Pick an inclusive count reproducibly.
fn pick(range: CountRange, rng: &mut StdRng) -> usize {
rng.random_range(range.min..=range.max)
}
/// Build one positioned entity collection from a name pool.
fn entities(
names: &[String],
count: usize,
kind: EntityType,
config: &WorldGenConfig,
rng: &mut StdRng,
) -> Vec<Entity> {
(0..count)
.map(|index| {
let base = names
.choose(rng)
.cloned()
.unwrap_or_else(|| "Unnamed".to_owned());
let mut entity = Entity::default();
entity.name = format!("{base} {}", index + 1);
entity.id = Uuid::from_u128(rng.random());
entity.entity_type = kind;
entity.modify_position(Position::from((
rng.random_range(0..config.canvas.width) as isize,
rng.random_range(0..config.canvas.height) as isize,
)));
entity
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_config_is_valid() {
WorldGenConfig::embedded().expect("valid embedded config");
}
#[test]
fn the_same_seed_replays_exactly() {
let config = WorldGenConfig::embedded().expect("config");
let first = generate(&config, 42, GenerationLevel::World);
let second = generate(&config, 42, GenerationLevel::World);
assert_eq!(
serde_json::to_value(first).expect("first"),
serde_json::to_value(second).expect("second")
);
}
#[test]
fn levels_are_cumulative_in_scope() {
let config = WorldGenConfig::embedded().expect("config");
let event = generate(&config, 7, GenerationLevel::Event);
assert_eq!(event.events.len(), 1);
assert!(event.towns.is_empty());
let settlement = generate(&config, 7, GenerationLevel::Settlement);
assert_eq!(settlement.towns.len(), 1);
assert!(!settlement.characters.is_empty());
}
#[test]
fn invalid_ranges_and_empty_pools_are_rejected() {
let mut config = WorldGenConfig::embedded().expect("config");
config.counts.towns = CountRange { min: 3, max: 2 };
assert!(config.validate().is_err());
config.counts.towns = CountRange { min: 1, max: 2 };
config.names.towns.clear();
assert!(config.validate().is_err());
}
}

View File

@ -0,0 +1,185 @@
use std::fs;
use lib_efo::{
adjudication::{
AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec,
ChosenEffect, StatName, apply_to_target, apply_to_world, preview, preview_at_potency,
},
entity::Entity,
epoch::EpochInfo,
stats::{EntityType, ListStats, Modification, StatPair},
};
use uuid::Uuid;
fn entity(id: u128, health: isize) -> Entity {
let mut entity = Entity::default();
entity.id = Uuid::from_u128(id);
entity.entity_type = EntityType::Town;
entity.change_stat_strict(
StatPair {
stat: ListStats::Health,
value: health.into(),
},
Modification::Replace,
);
entity.update_metastats();
entity
}
fn spec(config: &AdjudicationConfig, disposition: AdjudicationDisposition) -> AdjudicationSpec {
AdjudicationSpec {
level: AdjudicationLevel::Bad,
disposition,
source: Uuid::from_u128(1),
external_result: "d20=4".into(),
note: "The master rules that the walls absorb part of the shock.".into(),
effects: vec![ChosenEffect {
stat: StatName::Health,
delta: -40,
}],
policy_id: config.policy_id.clone(),
}
}
#[test]
fn embedded_and_external_policies_validate() {
let config = AdjudicationConfig::embedded().expect("embedded");
let directory = tempfile::tempdir().expect("tempdir");
let path = directory.path().join("adjudication.json");
fs::write(&path, serde_json::to_vec_pretty(&config).expect("encode")).expect("write");
assert_eq!(AdjudicationConfig::load(&path).expect("external"), config);
}
#[test]
fn master_effects_are_never_invented_and_disposition_controls_application() {
let config = AdjudicationConfig::embedded().expect("config");
for (disposition, expected_delta) in [
(AdjudicationDisposition::Applied, -40),
(AdjudicationDisposition::Dampened, -20),
(AdjudicationDisposition::Avoided, 0),
(AdjudicationDisposition::Destroyed, 0),
] {
let target = entity(2, 100);
let report = preview(&config, &spec(&config, disposition), &target, 3).expect("preview");
assert_eq!(report.changes.len(), 1);
assert_eq!(report.changes[0].applied_delta, expected_delta);
assert_eq!(report.changes[0].after, 100 + expected_delta);
assert_eq!(report.external_result, "d20=4");
}
}
#[test]
fn previews_are_stable_apply_exactly_and_refuse_stale_targets() {
let config = AdjudicationConfig::embedded().expect("config");
let mut target = entity(2, 100);
let report = preview(
&config,
&spec(&config, AdjudicationDisposition::Dampened),
&target,
3,
)
.expect("preview");
assert_eq!(
report,
preview(
&config,
&spec(&config, AdjudicationDisposition::Dampened),
&target,
3,
)
.expect("replay")
);
apply_to_target(&report, &mut target).expect("apply");
assert_eq!(**target.get_stats().get_field(&ListStats::Health), 80);
assert!(apply_to_target(&report, &mut target).is_err());
}
#[test]
fn explicit_effects_are_clamped_and_invalid_master_input_is_rejected() {
let config = AdjudicationConfig::embedded().expect("config");
let target = entity(2, 10);
let report = preview(
&config,
&spec(&config, AdjudicationDisposition::Applied),
&target,
0,
)
.expect("preview");
assert_eq!(report.changes[0].after, 0);
let mut duplicate = spec(&config, AdjudicationDisposition::Applied);
duplicate.effects.push(duplicate.effects[0]);
assert!(preview(&config, &duplicate, &target, 0).is_err());
let mut wrong_policy = spec(&config, AdjudicationDisposition::Applied);
wrong_policy.policy_id = "other".into();
assert!(preview(&config, &wrong_policy, &target, 0).is_err());
}
#[test]
fn omitted_effects_use_progressively_dampened_policy_defaults() {
let config = AdjudicationConfig::embedded().expect("config");
let target = entity(2, 100);
let expected = [
(AdjudicationLevel::Excellent, 0),
(AdjudicationLevel::Good, -5),
(AdjudicationLevel::Mid, -10),
(AdjudicationLevel::Bad, -15),
(AdjudicationLevel::Worsen, -18),
(AdjudicationLevel::Apocalypse, -20),
];
for (level, delta) in expected {
let mut ruling = spec(&config, AdjudicationDisposition::Applied);
ruling.level = level;
ruling.effects.clear();
let report = preview(&config, &ruling, &target, 0).expect("default preview");
assert!(report.effects_were_defaulted);
assert_eq!(report.changes[0].applied_delta, delta);
assert_eq!(report.changes[0].after, 100 + delta);
}
let mut explicit = spec(&config, AdjudicationDisposition::Applied);
explicit.level = AdjudicationLevel::Excellent;
let report = preview(&config, &explicit, &target, 0).expect("explicit preview");
assert!(!report.effects_were_defaulted);
assert_eq!(report.changes[0].applied_delta, -40);
}
#[test]
fn source_attenuation_persists_and_destroyed_events_stop_diffusion() {
let config = AdjudicationConfig::embedded().expect("config");
let mut event = Entity::default();
event.id = Uuid::from_u128(1);
event.entity_type = EntityType::Event;
let target = entity(2, 100);
let mut world = EpochInfo::default();
world.events.push(event);
world.towns.push(target.clone());
let mut ruling = spec(&config, AdjudicationDisposition::Applied);
ruling.effects.clear();
let first = preview(&config, &ruling, &target, 0).expect("first preview");
assert_eq!(first.source_potency_after, 7500);
let world = apply_to_world(&world, &config, &first, EntityType::Town).expect("first apply");
assert_eq!(
world.event_adjudications[&ruling.source].potency_basis_points,
7500
);
let changed_target = &world.towns[0];
let second =
preview_at_potency(&config, &ruling, changed_target, 1, 7500).expect("attenuated preview");
assert_eq!(second.changes[0].applied_delta, -11);
ruling.disposition = AdjudicationDisposition::Destroyed;
ruling.external_result = "the source is destroyed".into();
let destroyed =
preview_at_potency(&config, &ruling, changed_target, 2, 7500).expect("destroyed preview");
let world =
apply_to_world(&world, &config, &destroyed, EntityType::Town).expect("destroyed apply");
assert!(world.event_adjudications[&ruling.source].destroyed);
assert_eq!(
world.event_adjudications[&ruling.source].potency_basis_points,
0
);
assert!(lib_efo::simulation::plan_diffusion(&world, ruling.source, 100, 25, None).is_err());
}

140
lib_efo/tests/conflict.rs Normal file
View File

@ -0,0 +1,140 @@
use std::collections::HashSet;
use lib_efo::{
conflict::{
ConflictKind, ConflictStatus, ParticipantRef, create_conflict, finish_round,
validate_conflicts,
},
entity::Entity,
epoch::EpochInfo,
stats::EntityType,
};
use uuid::Uuid;
fn entity(id: u128, kind: EntityType, name: &str) -> Entity {
let mut entity = Entity::default();
entity.id = Uuid::from_u128(id);
entity.entity_type = kind;
entity.name = name.into();
entity
}
fn world() -> EpochInfo {
let mut world = EpochInfo::default();
world.towns.push(entity(1, EntityType::Town, "Haven"));
world
.organizations
.push(entity(2, EntityType::Organization, "Guild"));
world
.characters
.push(entity(3, EntityType::Character, "Aria"));
world
}
fn participant(id: u128, kind: EntityType, side: &str) -> ParticipantRef {
ParticipantRef {
entity_type: kind,
id: Uuid::from_u128(id),
side: side.into(),
committed_weight: 1,
removed: false,
}
}
#[test]
fn mixed_two_and_three_side_conflicts_validate_independently_of_insertion_order() {
let world = world();
let a = create_conflict(
&world,
Uuid::from_u128(20),
"The Crossing".into(),
ConflictKind::War,
vec![
participant(3, EntityType::Character, "third"),
participant(1, EntityType::Town, "red"),
participant(2, EntityType::Organization, "blue"),
],
)
.expect("valid conflict");
let b = create_conflict(
&world,
Uuid::from_u128(20),
"The Crossing".into(),
ConflictKind::War,
vec![
participant(2, EntityType::Organization, "blue"),
participant(1, EntityType::Town, "red"),
participant(3, EntityType::Character, "third"),
],
)
.expect("valid reordered conflict");
assert_eq!(a, b);
}
#[test]
fn fights_stalemate_and_wars_continue_or_select_the_remaining_side() {
let world = world();
let participants = vec![
participant(1, EntityType::Town, "red"),
participant(2, EntityType::Organization, "blue"),
];
let mut fight = create_conflict(
&world,
Uuid::from_u128(20),
"Fight".into(),
ConflictKind::Fight,
participants.clone(),
)
.expect("fight");
finish_round(&mut fight, Vec::new(), &HashSet::new()).expect("round");
assert_eq!(fight.status, ConflictStatus::Stalemate);
let mut war = create_conflict(
&world,
Uuid::from_u128(21),
"War".into(),
ConflictKind::War,
participants,
)
.expect("war");
finish_round(&mut war, Vec::new(), &HashSet::new()).expect("round");
assert_eq!(war.status, ConflictStatus::Active);
finish_round(&mut war, Vec::new(), &HashSet::from([Uuid::from_u128(2)]))
.expect("decisive round");
assert_eq!(war.status, ConflictStatus::Won { side: "red".into() });
}
#[test]
fn malformed_participants_and_cross_references_are_rejected() {
let mut world = world();
let duplicate = vec![
participant(1, EntityType::Town, "red"),
participant(1, EntityType::Town, "blue"),
];
assert!(
create_conflict(
&world,
Uuid::from_u128(20),
"Bad".into(),
ConflictKind::Fight,
duplicate
)
.is_err()
);
let conflict = create_conflict(
&world,
Uuid::from_u128(20),
"Valid".into(),
ConflictKind::Fight,
vec![
participant(1, EntityType::Town, "red"),
participant(2, EntityType::Organization, "blue"),
],
)
.expect("valid");
world.conflicts.insert(conflict.id, conflict);
validate_conflicts(&world).expect("valid world conflicts");
world.organizations.clear();
assert!(validate_conflicts(&world).is_err());
}

47
lib_efo/tests/diff.rs Normal file
View File

@ -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!([]));
}

View File

@ -0,0 +1,212 @@
use lib_efo::{
entity::{Entity, edit::EntityDraft},
stats::EntityType,
transaction::RepositoryLock,
workspace::Workspace,
};
use std::fs;
fn candidate(kind: EntityType, name: &str) -> Entity {
let base = EntityDraft::new_entity(kind);
let mut draft = EntityDraft::from_entity(&base).expect("draft");
draft.name = name.into();
draft.description = "Unicode town: Draän\nSecond line".into();
draft.position = "12,-5".into();
draft.statistics = "food:17 population:30".into();
draft.apply(&base).expect("valid form")
}
#[test]
fn all_six_types_support_create_edit_exact_undo_and_existing_restore() {
let temp = tempfile::tempdir().expect("temp");
let mut workspace = Workspace::initialize(temp.path(), "test").expect("init");
let manifest = fs::read(temp.path().join(".epoch")).expect("manifest");
let index = fs::read(temp.path().join(".efo/index.json")).expect("index");
for kind in [
EntityType::Character,
EntityType::Town,
EntityType::Event,
EntityType::Calamity,
EntityType::Organization,
EntityType::Blocker,
] {
let original = candidate(kind, "Original");
workspace
.apply_entity_change(None, Some(&original))
.expect("create");
let other = candidate(kind, "Other");
workspace
.apply_entity_change(None, Some(&other))
.expect("create other");
let prior = fs::read(temp.path().join(".efo/worktree.json")).expect("worktree");
let mut draft = EntityDraft::from_entity(&original).expect("draft");
draft.name = "Renamed".into();
draft.duration = "12".into();
let edited = draft.apply(&original).expect("edit draft");
workspace
.apply_entity_change(Some(&original), Some(&edited))
.expect("edit");
let opened = Workspace::open(temp.path()).expect("reopen");
assert_eq!(opened.worktree.world.vec_entities(&kind)[0].name, "Renamed");
workspace
.apply_entity_change(Some(&edited), Some(&original))
.expect("undo edit");
assert_eq!(
fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"),
prior
);
workspace
.apply_entity_change(Some(&original), None)
.expect("undo creation");
workspace
.restore_worktree_entities(
kind,
&[lib_efo::entity::EntityIdentifier::Id(other.id.to_string())],
)
.expect("CLI restore operation");
assert!(workspace.worktree.world.vec_entities(&kind).is_empty());
}
assert_eq!(
fs::read(temp.path().join(".epoch")).expect("manifest"),
manifest
);
assert_eq!(
fs::read(temp.path().join(".efo/index.json")).expect("index"),
index
);
assert!(!workspace.has_staged_changes());
assert!(!workspace.has_unstaged_changes());
}
#[test]
fn stale_worktree_or_index_lock_and_journal_refuse_without_losing_data() {
let temp = tempfile::tempdir().expect("temp");
let mut workspace = Workspace::initialize(temp.path(), "test").expect("init");
let entity = candidate(EntityType::Town, "Durn");
let baseline = fs::read(temp.path().join(".efo/worktree.json")).expect("worktree");
let lock = RepositoryLock::acquire(workspace.root(), "other writer").expect("lock");
assert!(
workspace
.apply_entity_change(None, Some(&entity))
.expect_err("locked")
.to_string()
.contains("locked")
);
assert!(workspace.worktree.world.towns.is_empty());
drop(lock);
fs::write(temp.path().join(".efo/transaction.json"), "{}").expect("journal");
assert!(
workspace
.apply_entity_change(None, Some(&entity))
.expect_err("journal")
.to_string()
.contains("efo recover")
);
assert_eq!(
fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"),
baseline
);
fs::remove_file(temp.path().join(".efo/transaction.json")).expect("remove simulated journal");
let mut external = Workspace::open(temp.path()).expect("open");
external
.apply_entity_change(None, Some(&entity))
.expect("external create");
assert!(
workspace
.apply_entity_change(None, Some(&candidate(EntityType::Town, "Other")))
.expect_err("stale")
.to_string()
.contains("repository changed")
);
workspace = Workspace::open(temp.path()).expect("open");
external.stage_all().expect("external stage");
assert!(
workspace
.apply_entity_change(Some(&entity), None)
.expect_err("stale index")
.to_string()
.contains("repository changed")
);
assert_eq!(
Workspace::open(temp.path())
.expect("open")
.worktree
.world
.towns[0]
.name,
"Durn"
);
assert!(!temp.path().join(".efo/lock").exists());
}
#[test]
fn validation_preserves_relationships_and_rejects_invalid_fields() {
let mut original = candidate(EntityType::Town, "Durn");
original.change_governor(lib_efo::stats::CharacterId(uuid::Uuid::new_v4()));
let draft = EntityDraft::from_entity(&original).expect("draft");
assert_eq!(
serde_json::to_value(draft.apply(&original).expect("unchanged")).expect("json"),
serde_json::to_value(&original).expect("json")
);
let mut invalid = draft.clone();
for name in ["", " \t", "bad\nname"] {
invalid.name = name.into();
assert!(invalid.apply(&original).is_err());
}
invalid = draft.clone();
invalid.bounds = "80:10".into();
assert!(invalid.apply(&original).is_err());
invalid = draft.clone();
invalid.position = "NaN,2".into();
assert!(invalid.apply(&original).is_err());
invalid = draft.clone();
invalid.duration = "foreverish".into();
assert!(invalid.apply(&original).is_err());
invalid = draft.clone();
invalid.effect = "bad".into();
assert!(invalid.apply(&original).is_err());
for statistics in [
"missing:2",
"food:no",
"food:2 food:4",
"food",
"food:999999999999999999999999999999999",
] {
invalid = draft.clone();
invalid.statistics = statistics.into();
assert!(invalid.apply(&original).is_err());
}
}
#[test]
fn duplicate_names_changed_identity_and_corrupt_state_are_not_saved() {
let temp = tempfile::tempdir().expect("temp");
let mut workspace = Workspace::initialize(temp.path(), "test").expect("init");
let entity = candidate(EntityType::Event, "Éclipse");
workspace
.apply_entity_change(None, Some(&entity))
.expect("create");
let prior = fs::read(temp.path().join(".efo/worktree.json")).expect("worktree");
assert!(
workspace
.apply_entity_change(None, Some(&candidate(EntityType::Event, "éclipse")))
.is_err()
);
let mut changed = entity.clone();
changed.id = uuid::Uuid::new_v4();
assert!(
workspace
.apply_entity_change(Some(&entity), Some(&changed))
.is_err()
);
assert_eq!(
fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"),
prior
);
fs::write(temp.path().join(".efo/worktree.json"), "invalid").expect("corrupt");
assert!(workspace.apply_entity_change(Some(&entity), None).is_err());
assert_eq!(
fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"),
b"invalid"
);
}

View File

@ -0,0 +1,50 @@
use lib_efo::{
entity::Entity,
epoch::{EntityIndex, EpochInfo},
stats::EntityType,
};
use uuid::Uuid;
fn entity(id: u128, name: &str, entity_type: EntityType) -> Entity {
let mut entity = Entity::default();
entity.id = Uuid::from_u128(id);
entity.name = name.into();
entity.entity_type = entity_type;
entity
}
#[test]
fn index_resolves_ids_and_case_insensitive_names_without_serialized_state() {
let mut world = EpochInfo::default();
world
.characters
.push(entity(1, " Aria ", EntityType::Character));
world.towns.push(entity(2, "Haven", EntityType::Town));
let index = EntityIndex::build(&world);
let aria = index.location_by_id(Uuid::from_u128(1)).expect("UUID");
assert_eq!(index.resolve(&world, aria).expect("entity").name, " Aria ");
assert_eq!(index.locations_by_name("ARIA"), &[aria]);
assert_eq!(index.len(), 2);
assert!(index.duplicate_ids().is_empty());
let serialized = serde_json::to_value(&world).expect("serialize world");
assert!(serialized.get("by_id").is_none());
assert!(serialized.get("by_name").is_none());
}
#[test]
fn index_reports_duplicate_ids_and_ambiguous_names() {
let mut world = EpochInfo::default();
world.events.push(entity(9, "The Fall", EntityType::Event));
world
.calamities
.push(entity(9, "the fall", EntityType::Calamity));
let index = EntityIndex::build(&world);
assert_eq!(index.len(), 1);
assert_eq!(index.locations_by_name("the fall").len(), 2);
assert_eq!(index.duplicate_ids(), &HashSet::from([Uuid::from_u128(9)]));
}
use std::collections::HashSet;

View File

@ -0,0 +1,59 @@
use std::{fs, path::PathBuf};
use lib_efo::{epoch::EpochId, workspace::Workspace};
fn example_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../examples/ravenous-draan")
}
#[test]
fn curated_draan_world_is_a_clean_usable_repository() {
let root = example_root();
let workspace = Workspace::open(&root).expect("open curated example");
assert_eq!(workspace.head.epoch_id, EpochId::new(1));
assert!(!workspace.has_staged_changes());
assert!(!workspace.has_unstaged_changes());
assert_eq!(workspace.head.towns.len(), 23);
assert_eq!(workspace.head.characters.len(), 6);
assert_eq!(workspace.head.organizations.len(), 5);
assert_eq!(workspace.head.calamities.len(), 7);
assert_eq!(workspace.head.blockers.len(), 4);
assert_eq!(workspace.head.events.len(), 5);
let entities = workspace
.head
.towns
.iter()
.chain(&workspace.head.characters)
.chain(&workspace.head.organizations)
.chain(&workspace.head.calamities)
.chain(&workspace.head.blockers)
.chain(&workspace.head.events);
for entity in entities {
assert!(
!entity.description.trim().is_empty(),
"{} needs lore",
entity.name
);
let position = serde_json::to_value(entity.position()).expect("serialize position");
let coordinates = position.as_array().expect("position coordinate pair");
for coordinate in coordinates {
assert!(
(0..=100).contains(&coordinate.as_i64().expect("integer coordinate")),
"{} position is on the percentage map",
entity.name
);
}
}
}
#[test]
fn curated_draan_map_is_the_expected_png() {
let bytes = fs::read(example_root().join("map.png")).expect("read example map");
assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
let width = u32::from_be_bytes(bytes[16..20].try_into().expect("PNG width"));
let height = u32::from_be_bytes(bytes[20..24].try_into().expect("PNG height"));
assert_eq!((width, height), (3840, 2160));
}

144
lib_efo/tests/simulation.rs Normal file
View File

@ -0,0 +1,144 @@
use lib_efo::{
entity::Entity,
epoch::EpochInfo,
simulation::{
MobilityState, Road, begin_diffusion, begin_travel, plan_diffusion, plan_travel,
tick_diffusion, tick_travel, validate_roads,
},
stats::EntityType,
};
use uuid::Uuid;
fn entity(id: u128, kind: EntityType, position: &str) -> Entity {
let mut entity = Entity::default();
entity.id = Uuid::from_u128(id);
entity.name = format!("entity {id}");
entity.entity_type = kind;
entity.modify_position(position.parse().expect("position"));
entity
}
fn world() -> EpochInfo {
let mut world = EpochInfo {
towns: vec![
entity(1, EntityType::Town, "0,0"),
entity(2, EntityType::Town, "10,0"),
entity(3, EntityType::Town, "20,0"),
],
characters: vec![entity(4, EntityType::Character, "0,0")],
events: vec![entity(5, EntityType::Event, "0,0")],
..EpochInfo::default()
};
world.mobility.insert(
Uuid::from_u128(4),
MobilityState::Resident {
place: Uuid::from_u128(1),
},
);
world.roads = vec![
Road {
id: Uuid::from_u128(10),
from: Uuid::from_u128(1),
to: Uuid::from_u128(2),
speed_percent: 200,
tags: vec!["paved".into()],
},
Road {
id: Uuid::from_u128(11),
from: Uuid::from_u128(2),
to: Uuid::from_u128(3),
speed_percent: 200,
tags: Vec::new(),
},
];
world
}
#[test]
fn fastest_route_is_deterministic_and_travel_arrives_reversibly() {
let mut world = world();
let plan =
plan_travel(&world, Uuid::from_u128(4), Uuid::from_u128(3), 50).expect("travel plan");
assert!(plan.uses_roads);
assert_eq!(
plan.route,
[Uuid::from_u128(1), Uuid::from_u128(2), Uuid::from_u128(3)]
);
assert_eq!(plan.total_ticks, 10);
begin_travel(&mut world, Uuid::from_u128(4), Uuid::from_u128(3), &plan).expect("begin");
assert!(tick_travel(&mut world, 9).is_empty());
assert_eq!(tick_travel(&mut world, 1), [Uuid::from_u128(4)]);
assert_eq!(
world.mobility[&Uuid::from_u128(4)],
MobilityState::Resident {
place: Uuid::from_u128(3)
}
);
assert_eq!(world.characters[0].position().to_inner(), (20, 0));
}
#[test]
fn direct_fallback_and_invalid_topology_are_explicit() {
let mut world = world();
world.roads.clear();
let plan =
plan_travel(&world, Uuid::from_u128(4), Uuid::from_u128(3), 50).expect("direct plan");
assert!(!plan.uses_roads);
assert_eq!(plan.total_ticks, 40);
world.roads.push(Road {
id: Uuid::from_u128(12),
from: Uuid::from_u128(1),
to: Uuid::from_u128(1),
speed_percent: 100,
tags: Vec::new(),
});
assert!(validate_roads(&world).is_err());
}
#[test]
fn old_snapshots_default_new_spatial_fields() {
let mut value = serde_json::to_value(EpochInfo::default()).expect("serialize");
value.as_object_mut().expect("object").remove("roads");
value.as_object_mut().expect("object").remove("mobility");
value.as_object_mut().expect("object").remove("diffusions");
let decoded: EpochInfo = serde_json::from_value(value).expect("old snapshot");
assert!(decoded.roads.is_empty());
assert!(decoded.mobility.is_empty());
assert!(decoded.diffusions.is_empty());
}
#[test]
fn diffusion_uses_roads_once_converges_and_expires() {
let mut world = world();
let event = Uuid::from_u128(5);
let state = plan_diffusion(&world, event, 100, 25, Some(11)).expect("frontier");
assert_eq!(state.frontier.len(), 3);
assert!(state.frontier.iter().all(|target| !target.route.is_empty()));
begin_diffusion(&mut world, event, state);
let first = tick_diffusion(&mut world, 5);
assert_eq!(first.reached.len(), 2);
assert!(first.expired.is_empty());
assert!(tick_diffusion(&mut world, 0).reached.is_empty());
let last = tick_diffusion(&mut world, 6);
assert_eq!(last.reached.len(), 1);
assert_eq!(last.expired, [event]);
assert!(tick_diffusion(&mut world, 100).reached.is_empty());
assert_eq!(world.diffusions[&event].affected.len(), 3);
}
#[test]
fn diffusion_replay_is_deterministic_across_varied_worlds() {
for offset in 0..64_u128 {
let mut world = world();
world.events[0].id = Uuid::from_u128(100 + offset);
let event = world.events[0].id;
let first =
plan_diffusion(&world, event, 75 + offset as u32, 20, None).expect("first plan");
let second =
plan_diffusion(&world, event, 75 + offset as u32, 20, None).expect("replayed plan");
assert_eq!(first, second, "variation {offset}");
}
}

View File

@ -0,0 +1,50 @@
use std::fs;
use lib_efo::transaction::{
RecoveryOutcome, RepositoryLock, TransactionError, break_lock, inspect_lock, recover,
replace_file,
};
#[test]
fn writer_lock_is_exclusive_and_inspectable() {
let directory = tempfile::tempdir().expect("temporary repository");
fs::create_dir(directory.path().join(".efo")).expect("workspace");
let lock = RepositoryLock::acquire(directory.path(), "first writer").expect("first lock");
let owner = inspect_lock(directory.path()).expect("inspect owner");
assert_eq!(owner.command, "first writer");
let error = RepositoryLock::acquire(directory.path(), "second writer")
.expect_err("second writer must be refused");
assert!(matches!(error, TransactionError::Locked { .. }));
drop(lock);
RepositoryLock::acquire(directory.path(), "after release").expect("released lock");
}
#[test]
fn explicit_break_returns_the_displaced_owner() {
let directory = tempfile::tempdir().expect("temporary repository");
fs::create_dir(directory.path().join(".efo")).expect("workspace");
let lock = RepositoryLock::acquire(directory.path(), "abandoned writer").expect("lock");
std::mem::forget(lock);
let owner = break_lock(directory.path()).expect("break lock");
assert_eq!(owner.command, "abandoned writer");
assert!(!directory.path().join(".efo/lock").exists());
}
#[test]
fn replacement_is_atomic_and_leaves_no_transaction_metadata() {
let directory = tempfile::tempdir().expect("temporary repository");
fs::create_dir(directory.path().join(".efo")).expect("workspace");
let destination = directory.path().join(".efo/worktree.json");
fs::write(&destination, b"old").expect("old state");
replace_file(directory.path(), &destination, b"new", "edit worktree").expect("replace state");
assert_eq!(fs::read(destination).expect("new state"), b"new");
assert!(!directory.path().join(".efo/transaction.json").exists());
assert!(!directory.path().join(".efo/lock").exists());
assert_eq!(
recover(directory.path()).expect("clean recovery"),
RecoveryOutcome::Clean
);
}

222
lib_efo/tests/workspace.rs Normal file
View File

@ -0,0 +1,222 @@
use std::fs;
use lib_efo::{
entity::{Entity, EntityIdentifier},
epoch::{EpochId, EpochInfo},
stats::EntityType,
workspace::{Workspace, WorkspaceError},
};
fn repository() -> tempfile::TempDir {
let directory = tempfile::tempdir().expect("temporary repository");
Workspace::initialize(directory.path(), "fixture").expect("initialize repository");
directory
}
#[test]
fn all_layers_begin_clean_and_complete() {
let directory = repository();
let workspace = Workspace::open(directory.path()).expect("workspace");
assert!(!workspace.has_staged_changes());
assert!(!workspace.has_unstaged_changes());
assert_eq!(workspace.head.epoch_id, EpochId::new(0));
}
#[test]
fn unfinished_journal_blocks_layer_reads_until_recovery() {
let directory = repository();
fs::write(directory.path().join(".efo/transaction.json"), "{}").expect("journal");
let error = Workspace::open(directory.path()).expect_err("journal must block readers");
assert!(matches!(error, WorkspaceError::RecoveryRequired));
}
#[test]
fn time_advance_commits_even_an_empty_world() {
let directory = repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
assert_eq!(
workspace.advance_and_commit().expect("advance"),
EpochId::new(1)
);
assert_eq!(workspace.head.commit_message, "Advance time");
}
#[test]
fn entity_staging_and_both_restore_directions_are_isolated() {
let directory = repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
let mut aria = Entity::default();
aria.id = uuid::Uuid::from_u128(1);
aria.name = "Aria".into();
aria.entity_type = EntityType::Character;
workspace.worktree.world.characters.push(aria);
workspace.save_worktree("test edit").expect("save worktree");
let mut workspace = Workspace::open(directory.path()).expect("changed workspace");
assert!(workspace.has_unstaged_changes());
assert!(!workspace.has_staged_changes());
workspace
.stage_entities(
EntityType::Character,
&[EntityIdentifier::Name("Aria".into())],
)
.expect("stage Aria");
assert!(workspace.has_staged_changes());
assert!(!workspace.has_unstaged_changes());
workspace.restore_index().expect("unstage all");
assert!(!workspace.has_staged_changes());
assert!(workspace.has_unstaged_changes());
workspace.restore_worktree().expect("discard worktree");
assert!(!workspace.has_unstaged_changes());
assert!(workspace.worktree.world.characters.is_empty());
}
#[test]
fn commit_creates_immutable_history_and_advances_all_layers() {
let directory = repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
let mut aria = Entity::default();
aria.id = uuid::Uuid::from_u128(1);
aria.name = "Aria".into();
aria.entity_type = EntityType::Character;
workspace.worktree.world.characters.push(aria);
workspace.save_worktree("test edit").expect("worktree");
let mut workspace = Workspace::open(directory.path()).expect("changed workspace");
workspace.stage_all().expect("stage");
let id = workspace.commit("Add Aria".into()).expect("commit");
assert_eq!(id, EpochId::new(1));
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(2));
assert!(!workspace.has_staged_changes());
assert!(!workspace.has_unstaged_changes());
let committed: EpochInfo = serde_json::from_slice(
&fs::read(directory.path().join("epoch/1/epochinfo.json")).expect("epoch 1"),
)
.expect("committed epoch");
assert_eq!(committed.parent_epoch, Some(EpochId::new(0)));
assert_eq!(committed.commit_message, "Add Aria");
let original: EpochInfo = serde_json::from_slice(
&fs::read(directory.path().join("epoch/0/epochinfo.json")).expect("epoch 0"),
)
.expect("original epoch");
assert!(original.characters.is_empty());
let reverted = workspace.revert(EpochId::new(1)).expect("revert epoch 1");
assert_eq!(reverted, EpochId::new(2));
assert!(workspace.head.characters.is_empty());
assert_eq!(workspace.head.parent_epoch, Some(EpochId::new(1)));
workspace
.switch(EpochId::new(1))
.expect("switch to epoch 1");
assert_eq!(workspace.head.characters.len(), 1);
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(3));
assert_eq!(
workspace.future_epochs().expect("future"),
vec![EpochId::new(2)]
);
let backup = workspace.prune_future().expect("prune future");
assert!(!directory.path().join("epoch/2").exists());
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(2));
assert!(backup.join("prune.json").is_file());
assert_eq!(
workspace.restore_pruned(&backup).expect("restore future"),
1
);
assert!(directory.path().join("epoch/2/epochinfo.json").exists());
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(3));
}
#[test]
fn revert_aborts_when_later_edits_overlap_the_target_change() {
let directory = repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
let mut aria = Entity::default();
aria.id = uuid::Uuid::from_u128(1);
aria.name = "Aria".into();
aria.entity_type = EntityType::Character;
workspace.worktree.world.characters.push(aria);
workspace.stage_all().expect("stage addition");
workspace.commit("Add Aria".into()).expect("first commit");
workspace.worktree.world.characters[0].name = "Aria Changed".into();
workspace.stage_all().expect("stage edit");
workspace
.commit("Rename Aria".into())
.expect("second commit");
let error = workspace
.revert(EpochId::new(1))
.expect_err("overlap must conflict");
assert!(matches!(error, WorkspaceError::Conflict(_)));
assert_eq!(workspace.manifest.epoch_id, EpochId::new(2));
assert!(!directory.path().join("epoch/3").exists());
}
#[test]
fn revert_to_worktree_is_reviewable_and_restorable() {
let directory = repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
let mut aria = Entity::default();
aria.id = uuid::Uuid::from_u128(1);
aria.name = "Aria".into();
aria.entity_type = EntityType::Character;
workspace.worktree.world.characters.push(aria);
workspace.stage_all().expect("stage Aria");
workspace.commit("Add Aria".into()).expect("commit Aria");
workspace
.revert_to_worktree(EpochId::new(1))
.expect("apply inverse");
assert!(workspace.worktree.world.characters.is_empty());
assert!(workspace.has_unstaged_changes());
assert!(!workspace.has_staged_changes());
workspace.restore_worktree().expect("restore inverse");
assert_eq!(workspace.worktree.world.characters.len(), 1);
}
#[test]
fn hard_reset_discards_transient_state_and_newer_epochs() {
let directory = repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
workspace.worktree.world.summary = "committed".into();
workspace.stage_all().expect("stage summary");
workspace.commit("First".into()).expect("first commit");
workspace.worktree.world.summary = "dirty".into();
let removed = workspace.hard_reset(EpochId::new(0)).expect("hard reset");
assert_eq!(removed, vec![EpochId::new(1)]);
assert_eq!(workspace.manifest.epoch_id, EpochId::new(0));
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(1));
assert!(workspace.worktree.world.summary.is_empty());
assert!(!directory.path().join("epoch/1").exists());
}
#[test]
fn prune_backup_restores_future_tags_and_allocator() {
let directory = repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
workspace.worktree.world.summary = "tagged future".into();
workspace.worktree.world.tags.push("future".into());
workspace.stage_all().expect("stage tagged future");
workspace
.commit("Tagged future".into())
.expect("commit future");
workspace.switch(EpochId::new(0)).expect("switch backward");
let backup = workspace.prune_future().expect("prune tagged future");
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(1));
assert!(!workspace.manifest.tags.contains_key("future"));
workspace
.restore_pruned(&backup)
.expect("restore tagged future");
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(2));
assert_eq!(
workspace.manifest.tags.get("future"),
Some(&EpochId::new(1))
);
}

View File

@ -0,0 +1,24 @@
#!/bin/sh
set -eu
version="${1:-0.1.0}"
output="${2:-epoch-forge-simulation-config-v${version}.zip}"
case "$output" in
/*) ;;
*) output="$PWD/$output" ;;
esac
if ! command -v zip >/dev/null 2>&1; then
echo "error: zip is required to package simulation configuration" >&2
exit 1
fi
package_dir="$(mktemp -d)"
trap 'rm -rf "$package_dir"' EXIT HUP INT TERM
cp lib_efo/assets/simulation/default.json "$package_dir/default.json"
cp lib_efo/assets/simulation/README.md "$package_dir/README.md"
touch -t 200001010000 "$package_dir/default.json" "$package_dir/README.md"
(cd "$package_dir" && sha256sum default.json README.md > SHA256SUMS)
touch -t 200001010000 "$package_dir/SHA256SUMS"
(cd "$package_dir" && zip -X "$output" default.json README.md SHA256SUMS)
echo "Created $output"

View File

@ -0,0 +1,22 @@
#!/bin/sh
set -eu
version="${1:-0.1.0}"
output="${2:-epoch-forge-worldgen-config-v${version}.zip}"
case "$output" in
/*) ;;
*) output="$PWD/$output" ;;
esac
if ! command -v zip >/dev/null 2>&1; then
echo "error: zip is required to package worldgen configuration" >&2
exit 1
fi
package_dir="$(mktemp -d)"
trap 'rm -rf "$package_dir"' EXIT HUP INT TERM
cp lib_efo/assets/worldgen/default.json "$package_dir/default.json"
cp lib_efo/assets/worldgen/README.md "$package_dir/README.md"
touch -t 200001010000 "$package_dir/default.json" "$package_dir/README.md"
(cd "$package_dir" && zip -X "$output" default.json README.md)
echo "Created $output"

View File

@ -0,0 +1,33 @@
#!/bin/sh
set -eu
tag="${1:?usage: upload-worldgen-config.sh TAG ZIP}"
asset="${2:?usage: upload-worldgen-config.sh TAG ZIP}"
base_url="${GITEA_URL:-https://proxy.dandaedre.com/gitea}"
repository="${GITEA_REPOSITORY:-idle-org/epoch_forge}"
if [ -z "${GITEA_TOKEN:-}" ]; then
echo "error: GITEA_TOKEN is required" >&2
exit 1
fi
if [ ! -f "$asset" ]; then
echo "error: asset does not exist: $asset" >&2
exit 1
fi
release_json="$(curl --fail --silent --show-error \
--header "Authorization: token $GITEA_TOKEN" \
"$base_url/api/v1/repos/$repository/releases/tags/$tag")"
release_id="$(printf '%s' "$release_json" | sed -n 's/^[[:space:]]*{"id":\([0-9][0-9]*\),.*/\1/p' | head -n 1)"
if [ -z "$release_id" ]; then
echo "error: could not determine release ID for tag $tag" >&2
exit 1
fi
curl --fail --silent --show-error \
--request POST \
--header "Authorization: token $GITEA_TOKEN" \
--form "attachment=@$asset" \
"$base_url/api/v1/repos/$repository/releases/$release_id/assets?name=$(basename "$asset")"
echo
echo "Uploaded $(basename "$asset") to release $tag"

12
tarpaulin.toml Normal file
View File

@ -0,0 +1,12 @@
[coverage]
workspace = true
all-features = true
exclude-files = ["bin_efo/src/*"]
[report]
out = ["Html"]
# CLI behavior is exercised through subprocess integration tests. Tarpaulin's
# ptrace backend cannot attribute those child executions reliably (and its
# follow-exec mode currently segfaults), so measure the directly instrumented
# library and TUI code rather than reporting every CLI adapter as uncovered.

17
tui_efo/Cargo.toml Normal file
View File

@ -0,0 +1,17 @@
[package]
name = "efo-tui"
version = "0.1.0"
edition = "2024"
repository = "https://proxy.dandaedre.com/gitea/idle-org/epoch_forge"
[dependencies]
clap = { workspace = true }
crossterm = { workspace = true }
lib_efo = { path = "../lib_efo", default-features = false }
ratatui = { workspace = true, features = ["unstable-rendered-line-info"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
uuid = { workspace = true }
[dev-dependencies]
tempfile = "3.23.0"

216
tui_efo/src/details.rs Normal file
View File

@ -0,0 +1,216 @@
//! Presentation-only entity views, derived from the same serialized fields.
use lib_efo::entity::Entity;
use ratatui::{
style::Stylize,
text::{Line, Span, Text},
};
use serde_json::Value;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DetailView {
#[default]
Formatted,
Json,
}
impl DetailView {
pub fn toggle(&mut self) {
*self = match self {
Self::Formatted => Self::Json,
Self::Json => Self::Formatted,
};
}
pub fn name(self) -> &'static str {
match self {
Self::Formatted => "Formatted",
Self::Json => "JSON",
}
}
pub fn text(self, entity: &Entity) -> Text<'static> {
match self {
Self::Json => match serde_json::to_string_pretty(entity) {
Ok(json) => Text::from(json),
Err(error) => Text::from(format!("Could not display details: {error}")),
},
Self::Formatted => match serde_json::to_value(entity) {
Ok(value) => formatted(entity, &value),
Err(error) => Text::from(format!("Could not display details: {error}")),
},
}
}
}
fn formatted(entity: &Entity, value: &Value) -> Text<'static> {
let mut lines = vec![
Line::from(entity.name.clone()).bold(),
Line::from(format!("@{}", entity.id)),
Line::from(""),
Line::from("Description").bold(),
];
if entity.description.is_empty() {
lines.push(Line::from("—"));
} else {
lines.extend(
entity
.description
.split('\n')
.map(|line| Line::from(line.to_owned())),
);
}
if let Some(fields) = value.as_object() {
lines.push(Line::from(""));
lines.push(Line::from("Properties").bold());
for key in ["entity_type", "duration", "effect_nature", "effect_bounds"] {
if let Some(value) = fields.get(key) {
field(&mut lines, key, value, 0);
}
}
for (key, value) in fields {
if matches!(
key.as_str(),
"name"
| "id"
| "description"
| "entity_type"
| "duration"
| "effect_nature"
| "effect_bounds"
) {
continue;
}
lines.push(Line::from(""));
field(&mut lines, key, value, 0);
}
}
Text::from(lines)
}
fn label(key: &str) -> String {
match key {
"entity_type" => "Type".into(),
"stats" => "Statistics".into(),
_ => {
let words = key.replace('_', " ");
let mut chars = words.chars();
match chars.next() {
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
}
}
}
fn scalar(value: &Value) -> String {
match value {
Value::Null => "—".into(),
Value::String(text) if text.is_empty() => "(empty)".into(),
Value::String(text) => text.clone(),
_ => value.to_string(),
}
}
fn field(lines: &mut Vec<Line<'static>>, key: &str, value: &Value, depth: usize) {
let indent = " ".repeat(depth);
let label = label(key);
match value {
Value::Object(fields) if !fields.is_empty() => {
lines.push(Line::from(format!("{indent}{label}")).bold());
for (key, value) in fields {
field(lines, key, value, depth + 1);
}
}
Value::Array(items) if items.iter().any(|item| item.is_object() || item.is_array()) => {
lines.push(Line::from(format!("{indent}{label}")).bold());
for (index, value) in items.iter().enumerate() {
field(lines, &format!("Item {}", index + 1), value, depth + 1);
}
}
_ => {
let text = match value {
Value::Object(_) => "(empty)".into(),
Value::Array(items) if items.is_empty() => "None".into(),
Value::Array(items) => items.iter().map(scalar).collect::<Vec<_>>().join(", "),
_ => scalar(value),
};
for (index, part) in text.split('\n').enumerate() {
let prefix = if index == 0 {
format!("{label}:")
} else {
String::new()
};
lines.push(Line::from(vec![
Span::raw(format!("{indent}{prefix:<16} ")).bold(),
Span::raw(part.to_owned()),
]));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use lib_efo::{entity::EntityDuration, stats::EntityType};
#[test]
fn event_has_readable_sections_and_exact_json_alternative() {
let mut event = Entity::default();
event.name = "Éclipse".into();
event.description = "First line\nSecond line".into();
event.entity_type = EntityType::Event;
event.change_duration(EntityDuration::Duration(8));
let text = DetailView::Formatted.text(&event).to_string();
for expected in [
"Éclipse",
"First line\nSecond line",
"Properties",
"Type:",
"Event",
"Statistics",
"Metadata",
"Duration:",
] {
assert!(text.contains(expected), "missing {expected}: {text}");
}
assert!(!text.contains("\"entity_type\""));
let json = DetailView::Json.text(&event).to_string();
assert_eq!(
serde_json::from_str::<Value>(&json).expect("JSON"),
serde_json::to_value(&event).expect("entity")
);
}
#[test]
fn nested_and_future_fields_remain_visible() {
let mut lines = Vec::new();
field(
&mut lines,
"custom_fields",
&serde_json::json!({
"notes": "α\nβ", "enabled": false, "missing": null,
"position": [74, 50], "links": [{"other_id": "@abc", "weight": -3}],
"empty_map": {}, "empty_list": []
}),
0,
);
let text = Text::from(lines).to_string();
for expected in [
"Custom fields",
"Notes:",
"α",
"β",
"false",
"—",
"74, 50",
"Other id:",
"@abc",
"-3",
"(empty)",
"None",
] {
assert!(text.contains(expected), "missing {expected}: {text}");
}
}
}

401
tui_efo/src/editor.rs Normal file
View File

@ -0,0 +1,401 @@
//! Modal, in-memory entity forms. Persistence stays in `Workspace`.
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use lib_efo::entity::{Entity, edit::EntityDraft};
use ratatui::{
Frame,
layout::{Constraint, Layout},
text::Text,
widgets::{Block, List, ListItem, Paragraph, Wrap},
};
const LABELS: [&str; 7] = [
"Name",
"Description",
"Position",
"Duration",
"Effect",
"Bounds",
"Statistics",
];
const HINTS: [&str; 7] = [
"Required; names must be unique within this collection",
"Free text; Enter inserts a new line",
"Exact x,y coordinates, for example 12,-5",
"permanent, done, or a number of turns",
"recurring, when-present, todo, or done",
"Minimum:maximum, for example 10:80",
"Absolute field:value pairs; full field names; unlisted values are preserved",
];
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
Form,
Preview,
Discard,
}
pub enum Action {
None,
Cancel,
Save,
}
pub struct Editor {
pub before: Option<Entity>,
pub candidate: Option<Entity>,
base: Entity,
values: Vec<String>,
initial: Vec<String>,
preview_values: Vec<String>,
field: usize,
cursor: usize,
mode: Mode,
scroll: u16,
max_scroll: u16,
pub error: String,
}
impl Editor {
pub fn open(base: Entity, creating: bool) -> Result<Self, String> {
let draft = EntityDraft::from_entity(&base)?;
let values = fields(draft);
let cursor = base.name.len();
Ok(Self {
before: (!creating).then(|| base.clone()),
candidate: None,
base,
initial: values.clone(),
preview_values: values.clone(),
values,
field: 0,
cursor,
mode: Mode::Form,
scroll: 0,
max_scroll: 0,
error: String::new(),
})
}
fn draft(&self) -> EntityDraft {
EntityDraft {
name: self.values[0].clone(),
description: self.values[1].clone(),
position: self.values[2].clone(),
duration: self.values[3].clone(),
effect: self.values[4].clone(),
bounds: self.values[5].clone(),
statistics: self.values[6].clone(),
}
}
fn focus(&mut self, index: usize) {
self.field = index;
self.cursor = self.values[index].len();
}
pub fn paste(&mut self, text: &str) {
if self.mode != Mode::Form {
return;
}
let text: String = text
.chars()
.filter_map(|c| {
if c == '\n' {
Some(if self.field == 1 { '\n' } else { ' ' })
} else if c.is_control() {
None
} else {
Some(c)
}
})
.collect();
self.values[self.field].insert_str(self.cursor, &text);
self.cursor += text.len();
self.error.clear();
}
pub fn handle(&mut self, key: KeyEvent) -> Action {
if self.mode == Mode::Discard {
return match key.code {
KeyCode::Char('y') => Action::Cancel,
KeyCode::Char('n') | KeyCode::Esc => {
self.mode = Mode::Form;
Action::None
}
_ => Action::None,
};
}
if self.mode == Mode::Preview {
match key.code {
KeyCode::Char('y') => return Action::Save,
KeyCode::Esc | KeyCode::Char('n') => {
self.mode = Mode::Form;
self.error.clear();
}
KeyCode::Up | KeyCode::Char('k') => self.scroll = self.scroll.saturating_sub(1),
KeyCode::Down | KeyCode::Char('j') => {
self.scroll = self.scroll.saturating_add(1).min(self.max_scroll)
}
KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(10),
KeyCode::PageDown => {
self.scroll = self.scroll.saturating_add(10).min(self.max_scroll)
}
KeyCode::Home => self.scroll = 0,
KeyCode::End => self.scroll = self.max_scroll,
_ => {}
}
return Action::None;
}
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('s') => match self.draft().apply(&self.base).and_then(|entity| {
let values = fields(EntityDraft::from_entity(&entity)?);
Ok((entity, values))
}) {
Ok((entity, values)) => {
self.preview_values = values;
self.candidate = Some(entity);
self.mode = Mode::Preview;
self.scroll = 0;
self.error.clear();
}
Err(error) => self.error = error,
},
KeyCode::Char('u') => {
self.values[self.field].clear();
self.cursor = 0;
}
_ => {}
}
return Action::None;
}
match key.code {
KeyCode::Esc => {
if self.values == self.initial {
return Action::Cancel;
}
self.mode = Mode::Discard;
}
KeyCode::BackTab => self.focus((self.field + 6) % 7),
KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => {
self.focus((self.field + 6) % 7)
}
KeyCode::Tab | KeyCode::Down => self.focus((self.field + 1) % 7),
KeyCode::Up => self.focus((self.field + 6) % 7),
KeyCode::Home => self.cursor = 0,
KeyCode::End => self.cursor = self.values[self.field].len(),
KeyCode::Left => {
self.cursor = self.values[self.field][..self.cursor]
.char_indices()
.next_back()
.map_or(0, |(index, _)| index)
}
KeyCode::Right => {
if let Some(c) = self.values[self.field][self.cursor..].chars().next() {
self.cursor += c.len_utf8();
}
}
KeyCode::Backspace => {
if let Some((index, _)) = self.values[self.field][..self.cursor]
.char_indices()
.next_back()
{
self.values[self.field].drain(index..self.cursor);
self.cursor = index;
}
}
KeyCode::Delete => {
if self.cursor < self.values[self.field].len() {
self.values[self.field].remove(self.cursor);
}
}
KeyCode::Enter if self.field == 1 => self.paste("\n"),
KeyCode::Enter => self.focus((self.field + 1) % 7),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::ALT) => {
self.paste(&c.to_string())
}
_ => {}
}
Action::None
}
pub fn render(&mut self, frame: &mut Frame<'_>) {
let area = frame.area();
let rows = Layout::vertical([
Constraint::Length(if area.height < 14 { 2 } else { 3 }),
Constraint::Min(1),
Constraint::Length((area.height / 4).clamp(2, 5)),
])
.split(area);
let title = format!(
"{} {:?} · worktree only · @{}",
if self.before.is_none() { "Add" } else { "Edit" },
self.base.entity_type,
self.base.id
);
frame.render_widget(
Paragraph::new(title).block(Block::bordered().title(" Entity editor ")),
rows[0],
);
let footer = if self.mode == Mode::Discard {
frame.render_widget(Paragraph::new("Discard this unsaved draft?\n\ny: discard n / Esc: continue editing\nNothing has been saved.").block(Block::bordered().title(" Confirm discard ")).wrap(Wrap { trim: false }), rows[1]);
String::new()
} else if self.mode == Mode::Preview {
let mut text = format!(
"Confirm {} in the WORKTREE only.\nHEAD and index stay unchanged.\nUndo this save with u; stage/commit with efo when ready.\n\n",
if self.before.is_none() {
"creation"
} else {
"edit"
}
);
let changed = self
.preview_values
.iter()
.zip(&self.initial)
.enumerate()
.filter(|(_, (after, before))| self.before.is_none() || after != before);
for (index, (after, before)) in changed {
text.push_str(&format!(
"{}\n Before: {}\n After: {}\n\n",
LABELS[index],
if self.before.is_none() {
"(new entity)"
} else {
before
},
after
));
}
if !self.error.is_empty() {
text.push_str(&format!(
"Save failed: {}\nDraft retained. Esc returns to the form.\n",
self.error
));
}
let paragraph = Paragraph::new(Text::from(text)).wrap(Wrap { trim: false });
self.max_scroll = paragraph
.line_count(rows[1].width.saturating_sub(2))
.saturating_sub(usize::from(rows[1].height.saturating_sub(2)))
.min(usize::from(u16::MAX)) as u16;
self.scroll = self.scroll.min(self.max_scroll);
frame.render_widget(
paragraph
.block(Block::bordered().title(" Save preview · ↑↓ / PgUp/PgDn scroll "))
.scroll((self.scroll, 0)),
rows[1],
);
format!(
"y save · n / Esc back to form\n{}",
if self.error.is_empty() {
""
} else {
"SAVE FAILED · scroll preview to read error"
}
)
} else {
let body = if area.width >= 90 {
let columns =
Layout::horizontal([Constraint::Length(24), Constraint::Min(1)]).split(rows[1]);
let items = LABELS.iter().enumerate().map(|(index, label)| {
ListItem::new(format!(
"{} {}",
if index == self.field { "›" } else { " " },
label
))
});
frame.render_widget(
List::new(items).block(Block::bordered().title(" Fields · Tab / ↑↓ ")),
columns[0],
);
columns[1]
} else {
rows[1]
};
let value = &self.values[self.field];
let displayed = format!("{}▏{}", &value[..self.cursor], &value[self.cursor..]);
let inner_width = body.width.saturating_sub(2);
let cursor_line = Paragraph::new(format!("{}▏", &value[..self.cursor]))
.wrap(Wrap { trim: false })
.line_count(inner_width);
let offset = cursor_line
.saturating_sub(usize::from(body.height.saturating_sub(2)))
.min(usize::from(u16::MAX)) as u16;
frame.render_widget(
Paragraph::new(displayed)
.wrap(Wrap { trim: false })
.scroll((offset, 0))
.block(Block::bordered().title(format!(
" {} ({}/7) ",
LABELS[self.field],
self.field + 1
))),
body,
);
if self.error.is_empty() {
format!(
"Tab/↑↓ field · ←→ cursor · Ctrl-U clear\nCtrl-S preview/save · Esc cancel\n{}",
HINTS[self.field]
)
} else {
format!("{}\nCtrl-S retry · Esc cancel", self.error)
}
};
frame.render_widget(Paragraph::new(footer).wrap(Wrap { trim: false }), rows[2]);
}
}
fn fields(draft: EntityDraft) -> Vec<String> {
vec![
draft.name,
draft.description,
draft.position,
draft.duration,
draft.effect,
draft.bounds,
draft.statistics,
]
}
#[cfg(test)]
mod tests {
use super::*;
use lib_efo::stats::EntityType;
use ratatui::{Terminal, backend::TestBackend};
fn key(editor: &mut Editor, code: KeyCode) {
editor.handle(KeyEvent::new(code, KeyModifiers::NONE));
}
#[test]
fn unicode_cursor_paste_multiline_and_modal_preview() {
let mut editor =
Editor::open(EntityDraft::new_entity(EntityType::Event), true).expect("editor");
editor.paste("É日x");
key(&mut editor, KeyCode::Left);
key(&mut editor, KeyCode::Backspace);
assert_eq!(editor.values[0], "Éx");
key(&mut editor, KeyCode::Home);
key(&mut editor, KeyCode::Delete);
assert_eq!(editor.values[0], "x");
key(&mut editor, KeyCode::Tab);
editor.paste("line one\nline two");
key(&mut editor, KeyCode::Enter);
assert_eq!(editor.values[1], "line one\nline two\n");
editor.handle(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
assert!(editor.mode == Mode::Preview);
let candidate = serde_json::to_value(editor.candidate.as_ref()).expect("json");
editor.paste("must not change preview");
assert_eq!(
serde_json::to_value(editor.candidate.as_ref()).expect("json"),
candidate
);
for (width, height) in [(1, 1), (32, 10), (60, 16), (120, 30)] {
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal");
editor.render_test(&mut terminal);
key(&mut editor, KeyCode::End);
editor.render_test(&mut terminal);
}
key(&mut editor, KeyCode::Esc);
assert!(editor.mode == Mode::Form);
}
impl Editor {
fn render_test(&mut self, terminal: &mut Terminal<TestBackend>) {
terminal.draw(|frame| self.render(frame)).expect("render");
}
}
}

Some files were not shown because too many files have changed in this diff Show More