Compare commits

...

7 Commits

36 changed files with 2608 additions and 107 deletions

1
.gitignore vendored
View File

@ -29,6 +29,7 @@ testepo*
naming.json naming.json
config.toml config.toml
tarpaulin-report.html tarpaulin-report.html
/coverage/
# Local repositories used for manual CLI testing and IDE inspection. # Local repositories used for manual CLI testing and IDE inspection.
/.local/ /.local/

View File

@ -258,6 +258,36 @@ and [`docs/presentation-design.md`](docs/presentation-design.md).
destroyed no-op effects, clamping, stale/repeated application, CLI audit, destroyed no-op effects, clamping, stale/repeated application, CLI audit,
aliasing, and worktree restoration. aliasing, and worktree restoration.
### Deterministic execution design
- Active implementation: [epoch resolution task list](docs/epoch-resolution-tasks.md).
- [x] All resolution commands share a persisted epoch baseline;
clamp each independent ruling, sum its effective contribution, clamp the total.
Commit/epoch-next is the compounding boundary.
- [x] Publish format 1.1 with 1.0 reads, atomic upgrade, full stale-state checks,
complete-resolution stage/restore, historical validation, and CLI permutation tests.
- [x] Add pinned event-local ChaCha12 named draws; keep GM rolls external and
preserve the existing worldgen algorithm. Actual worker pools remain future work.
- Final validation: 167 all-feature workspace tests, formatting, and strict
Clippy pass. Coverage includes all six three-ruling permutations, three mixed
CLI orders, format upgrades, legacy records, stale snapshots, and overflow.
- [x] Document immutable batch inputs, event/occurrence RNG identities, exact
delta reduction, normalization, retries, phase barriers, and atomic publication
in `docs/deterministic-execution-design.md`.
- [x] Compare current adjudication/diffusion/conflict code with simultaneous
semantics and mentally check schedule independence and failure cases.
- Decision: simultaneous clamping and snapshot source potency are new ruleset
semantics, not a behavior-preserving parallelization of sequential commands.
- Discovery: current per-report absolute after-values, source-state overwrites,
sequential worldgen RNG, and platform-sized arithmetic need dedicated work.
- Validation: formatting, all-target/all-feature locked workspace tests, and
strict Clippy passed; this change documents rules without changing runtime behavior.
- [x] Implement a versioned serial batch reference and proposal/receipt schema
with compatibility fixtures before introducing a worker pool.
- [x] Convert mental checks into executable permutation, retry, stale-state,
arithmetic, recovery, and event-local RNG golden-vector tests.
### Presentation completion (#10) ### Presentation completion (#10)
- [x] Approve the remaining renderer/export contract in - [x] Approve the remaining renderer/export contract in
@ -350,6 +380,8 @@ These require user approval and are not part of the current implementation:
position tests; document and provide a runnable `lib_efo` repository example. position tests; document and provide a runnable `lib_efo` repository example.
- [x] Configure Tarpaulin around its subprocess-attribution limitation and - [x] Configure Tarpaulin around its subprocess-attribution limitation and
refresh `rust_autobadges` at a directly measured coverage level above 70%. refresh `rust_autobadges` at a directly measured coverage level above 70%.
- [x] Generate version, test, and measured-coverage badges in Jenkins cleanup;
archive all branches and safely publish only `main` under the shared asset root.
## TUI release-readiness pass ## TUI release-readiness pass

View File

@ -55,8 +55,9 @@ workflows. Tests that touch a repository must use a temporary directory and
must not depend on execution order. Snapshot tests are appropriate for stable must not depend on execution order. Snapshot tests are appropriate for stable
human output; assertions on structured data are preferred for persistence. 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 Tarpaulin runs in CI with the tracked configuration and its documented line-
for routine commits. Refresh their badges only for a significant release. coverage floor. Do not restore `rust_autobadges`; Jenkins renders and publishes
the mutable badges from verified test and coverage results.
## Documentation and commits ## Documentation and commits

1
Cargo.lock generated
View File

@ -652,6 +652,7 @@ dependencies = [
"miette", "miette",
"once_cell", "once_cell",
"rand", "rand",
"rand_chacha",
"serde", "serde",
"serde_json", "serde_json",
"tempfile", "tempfile",

147
Jenkinsfile vendored
View File

@ -7,6 +7,11 @@ pipeline {
environment { environment {
CARGO_TERM_COLOR = 'always' CARGO_TERM_COLOR = 'always'
RUST_BACKTRACE = '1' RUST_BACKTRACE = '1'
CARGO_TARPAULIN_VERSION = '0.37.5'
BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
BADGE_OWNER = 'idle-org'
BADGE_PROJECT = 'epoch_forge'
BADGE_DEFAULT_BRANCH = 'main'
} }
stages { stages {
@ -19,6 +24,11 @@ pipeline {
git submodule sync --recursive git submodule sync --recursive
git submodule update --init --recursive git submodule update --init --recursive
# Jenkins may reuse workspaces. Never trust badges or
# completion markers left by an earlier build.
rm -rf -- coverage
mkdir -m 0755 coverage
''' '''
} }
} }
@ -49,6 +59,16 @@ pipeline {
cargo --version cargo --version
rustfmt --version rustfmt --version
cargo clippy --version cargo clippy --version
if ! cargo tarpaulin --version 2>/dev/null \
| grep -F "$CARGO_TARPAULIN_VERSION" >/dev/null; then
echo "Installing cargo-tarpaulin $CARGO_TARPAULIN_VERSION..."
cargo install cargo-tarpaulin \
--version "$CARGO_TARPAULIN_VERSION" \
--locked
fi
cargo tarpaulin --version
''' '''
} }
} }
@ -90,6 +110,50 @@ pipeline {
--all-targets \ --all-targets \
--all-features \ --all-features \
--locked --locked
case "$BUILD_NUMBER" in
''|*[!0-9]*)
echo "ERROR: BUILD_NUMBER is not numeric: $BUILD_NUMBER" >&2
exit 1
;;
esac
: > "coverage/.tests-passed-$BUILD_NUMBER"
'''
}
}
stage('Coverage') {
steps {
sh '''
set -eu
echo "Measuring workspace line coverage (minimum 65%)..."
cargo tarpaulin \
--workspace \
--all-features \
--locked \
--output-dir coverage
summary=coverage/tarpaulin-report.json
[ -f "$summary" ] && [ -s "$summary" ] || {
echo "ERROR: Tarpaulin did not create $summary." >&2
exit 1
}
coverage_value=$(sed -n \
's/.*"coverage":\([0-9][0-9.]*\),"covered":[0-9][0-9]*,"coverable":[0-9][0-9]*}$/\1/p' \
"$summary")
if ! awk -v value="$coverage_value" 'BEGIN {
valid = value ~ /^[0-9]+([.][0-9]+)?$/ && value >= 0 && value <= 100
exit(valid ? 0 : 1)
}'; then
echo "ERROR: invalid overall coverage in $summary: $coverage_value" >&2
exit 1
fi
scripts/ci-coverage-badges.sh coverage --value "$coverage_value"
rm -f "$summary"
: > "coverage/.coverage-ready-$BUILD_NUMBER"
''' '''
} }
} }
@ -104,7 +168,9 @@ pipeline {
--workspace \ --workspace \
--all-targets \ --all-targets \
--all-features \ --all-features \
--locked --locked \
-- \
-D warnings
''' '''
} }
} }
@ -133,8 +199,8 @@ pipeline {
publishChecks( publishChecks(
conclusion: 'SUCCESS', conclusion: 'SUCCESS',
name: 'Rust CI', name: 'Rust CI',
summary: 'Epoch Forge passed all CI checks.', summary: 'Epoch Forge passed tests, coverage, and all CI checks.',
text: 'Formatting, workspace checks, tests, Clippy, and the release build completed successfully.', text: 'Formatting, workspace checks, tests, the coverage floor, Clippy, and the release build passed. Badge artifacts are finalized during cleanup.',
title: 'Build Successful' title: 'Build Successful'
) )
@ -146,7 +212,7 @@ pipeline {
conclusion: 'FAILURE', conclusion: 'FAILURE',
name: 'Rust CI', name: 'Rust CI',
summary: 'Epoch Forge failed CI.', summary: 'Epoch Forge failed CI.',
text: 'Formatting, compilation, tests, Clippy, or the release build failed. Check the Jenkins log.', text: 'Formatting, compilation, tests, coverage, Clippy, or the release build failed. Cleanup still generates current badge artifacts; check the Jenkins log.',
title: 'Build Failed' title: 'Build Failed'
) )
@ -158,11 +224,80 @@ pipeline {
conclusion: 'ACTION_REQUIRED', conclusion: 'ACTION_REQUIRED',
name: 'Rust CI', name: 'Rust CI',
summary: 'Epoch Forge CI is unstable.', summary: 'Epoch Forge CI is unstable.',
text: 'The Jenkins build completed with an unstable status.', text: 'The Jenkins build is unstable. Cleanup still generates current test, coverage, and version badge artifacts.',
title: 'Build Unstable' title: 'Build Unstable'
) )
echo '⚠️ Epoch Forge CI is unstable.' echo '⚠️ Epoch Forge CI is unstable.'
} }
cleanup {
script {
sh '''
set -eu
test_marker="coverage/.tests-passed-$BUILD_NUMBER"
coverage_marker="coverage/.coverage-ready-$BUILD_NUMBER"
if [ -f "$test_marker" ]; then
scripts/ci-coverage-badges.sh test --value passing
else
scripts/ci-coverage-badges.sh test --value failing
fi
if [ ! -f "$coverage_marker" ]; then
scripts/ci-coverage-badges.sh coverage --value -
fi
version=$(awk '
/^\[package\][[:space:]]*$/ { in_package = 1; next }
/^\[/ && in_package { exit }
in_package && /^[[:space:]]*version[[:space:]]*=/ {
line = $0
sub(/^[^=]*=[[:space:]]*"/, "", line)
sub(/"[[:space:]]*$/, "", line)
print line
exit
}
' bin_efo/Cargo.toml)
[ -n "$version" ] || {
echo "ERROR: could not read efo version from bin_efo/Cargo.toml." >&2
exit 1
}
scripts/ci-coverage-badges.sh version --value "$version"
rm -f coverage/tarpaulin-report.json \
"$test_marker" "$coverage_marker"
for badge in version test coverage; do
path="coverage/$badge.svg"
if [ -L "$path" ] || [ ! -f "$path" ] || [ ! -s "$path" ]; then
echo "ERROR: invalid badge artifact: $path" >&2
exit 1
fi
done
'''
archiveArtifacts(
allowEmptyArchive: false,
artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg',
fingerprint: true
)
if (env.BRANCH_NAME == env.BADGE_DEFAULT_BRANCH) {
sh '''
set -eu
scripts/publish-ci-coverage-badges.sh \
"$BADGE_PUBLICATION_ROOT" \
"$BADGE_OWNER" \
"$BADGE_PROJECT" \
"$BADGE_DEFAULT_BRANCH" \
version test coverage
'''
} else {
echo "Skipping public badge publication for branch ${env.BRANCH_NAME ?: '(unset)'}; default is ${env.BADGE_DEFAULT_BRANCH}."
}
}
}
} }
} }

View File

@ -1,6 +1,6 @@
# Epoch Forge # Epoch Forge
![coverage](badges/coverage.svg) ![version](badges/version.svg) ![tests](badges/test.svg) ![coverage](https://assets.dandaedre.com/coverage/idle-org/epoch_forge/main/coverage.svg) ![version](https://assets.dandaedre.com/coverage/idle-org/epoch_forge/main/version.svg) ![tests](https://assets.dandaedre.com/coverage/idle-org/epoch_forge/main/test.svg)
Epoch Forge (`efo`) is an early-alpha command-line tool for managing a game's 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 world or organisation across a sequence of snapshots called **epochs**. It is
@ -10,7 +10,7 @@ future timeline when needed.
The current release manages organisations, characters, towns, events, The current release manages organisations, characters, towns, events,
calamities, and blockers with statistics and relationships. Repository format calamities, and blockers with statistics and relationships. Repository format
1.0 provides worktree/index staging, immutable commits, restore, conflict-safe 1.1 provides worktree/index staging, immutable commits, restore, conflict-safe
revert, switching, and recoverable future pruning from initialisation. A separate revert, switching, and recoverable future pruning from initialisation. A separate
TUI searches entities across HEAD, staged, and working state, and offers TUI searches entities across HEAD, staged, and working state, and offers
previewed entity creation/editing with one-step undo. Custom fields and TUI previewed entity creation/editing with one-step undo. Custom fields and TUI
@ -71,7 +71,7 @@ Run `efo --help`, `efo <command> --help`, or see the
| Area | Available now | Not available yet | | 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 | | Repository | Initialise format 1.1; 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 | | 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 | | 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 | | 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 |
@ -123,11 +123,26 @@ cargo test --workspace --all-targets --all-features --locked
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
``` ```
Tarpaulin and `rust_autobadges` are intentionally release-only. They do not run CI runs the pinned `cargo-tarpaulin` 0.37.5 release with:
in routine CI because of their cost; badge files are refreshed for significant
releases. The Tarpaulin configuration excludes the thin CLI adapters because ```bash
their subprocess integration tests cannot be attributed reliably by its ptrace cargo tarpaulin --workspace --all-features --locked --output-dir coverage
backend; library and TUI code remain directly measured. ```
The tracked Tarpaulin configuration enforces at least 65% line coverage across
all production code. CLI subprocess tests remain valuable even though
Tarpaulin cannot attribute their child execution, so those adapters stay in the
measured surface. The temporary machine-readable summary is
`coverage/tarpaulin-report.json`. The authoritative version is the `efo`
package version in `bin_efo/Cargo.toml`.
Jenkins archives exactly `coverage/version.svg`, `coverage/test.svg`, and
`coverage/coverage.svg`. Default-branch builds publish them under
`/mnt/assets/coverage/idle-org/epoch_forge/main/`; the public URLs are the three
badge images directly below this README's title. The asset mount should be
read-only to the public server, with directory listing disabled, a restrictive
SVG content security policy, and revalidation or a short cache lifetime for
these mutable URLs.
## Release archives ## Release archives

View File

@ -1 +0,0 @@
<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

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" 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-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></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="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="104" height="18" role="img" aria-label="version: 1.0.228"><title>version: 1.0.228</title><linearGradient id="bms-ed89fff123285f2c" 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-ed89fff123285f2c"><rect width="104" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-ed89fff123285f2c)"><rect width="51" height="18" fill="#555"/><rect x="51" width="53" height="18" fill="#fe7d37"/><rect width="104" height="18" fill="url(#bms-ed89fff123285f2c)"/></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="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="765" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">1.0.228</text><text x="765" y="130" transform="scale(.1)" fill="#fff" textLength="430">1.0.228</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -6,9 +6,11 @@ use clap::{Args, Subcommand};
use lib_efo::{ use lib_efo::{
adjudication::{ adjudication::{
AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec, AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec,
ChosenEffect, StatName, apply_to_world, preview_at_potency, ChosenEffect, StatName,
}, },
entity::EntityIdentifier, entity::EntityIdentifier,
epoch::EpochInfo,
epoch_resolution,
stats::EntityType, stats::EntityType,
workspace::Workspace, workspace::Workspace,
}; };
@ -20,7 +22,7 @@ use crate::error::AppError;
pub enum AdjudicateCmd { pub enum AdjudicateCmd {
/// Preview a ruling without changing the worktree. /// Preview a ruling without changing the worktree.
Preview(AdjudicateArgs), Preview(AdjudicateArgs),
/// Apply a ruling and record it in the worktree. /// Apply an independent ruling against this epoch's starting values.
Apply(AdjudicateArgs), Apply(AdjudicateArgs),
/// List recorded rulings, optionally restricted to one event. /// List recorded rulings, optionally restricted to one event.
List(AdjudicateListArgs), List(AdjudicateListArgs),
@ -29,7 +31,7 @@ pub enum AdjudicateCmd {
/// One external roll and the game master's explicit ruling. /// One external roll and the game master's explicit ruling.
#[derive(Debug, Args)] #[derive(Debug, Args)]
#[command( #[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" after_long_help = "EPOCH SEMANTICS:\n Rulings share the first-resolution baseline until commit or epoch next.\n Each ruling clamps independently; its contribution joins the epoch total.\n\nEXAMPLES:\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 { pub struct AdjudicateArgs {
/// Source event name/prefix or @UUID. /// Source event name/prefix or @UUID.
@ -52,6 +54,9 @@ pub struct AdjudicateArgs {
/// Optional explanation retained in the audit record. /// Optional explanation retained in the audit record.
#[arg(long, default_value = "")] #[arg(long, default_value = "")]
note: String, note: String,
/// Stable occurrence number; change only for an intentional repeated ruling.
#[arg(long, default_value_t = 0, value_name = "NUMBER")]
occurrence: u64,
/// Complete replacement policy JSON. /// Complete replacement policy JSON.
#[arg(long)] #[arg(long)]
config: Option<std::path::PathBuf>, config: Option<std::path::PathBuf>,
@ -103,13 +108,18 @@ fn resolve(args: &AdjudicateArgs, apply: bool) -> Result<(), AppError> {
.collect::<Result<_, _>>()?, .collect::<Result<_, _>>()?,
policy_id: config.policy_id.clone(), policy_id: config.policy_id.clone(),
}; };
let source_potency = workspace let report = epoch_resolution::preview(
.worktree &workspace.worktree.world,
.world &config,
.event_adjudications &spec,
.get(&source) target.id,
.map_or(10_000, |state| state.potency_basis_points); args.occurrence,
let report = preview_at_potency(&config, &spec, target, 0, source_potency)?; )?;
let updated = epoch_resolution::apply(
&workspace.worktree.world,
&config,
&[(target_type, report.clone())],
)?;
let mut output = format!( let mut output = format!(
"Adjudication preview · {} · {} · {}\n├─ External result: {}\n├─ Target: {} (@{})\n", "Adjudication preview · {} · {} · {}\n├─ External result: {}\n├─ Target: {} (@{})\n",
level_label(report.level), level_label(report.level),
@ -136,7 +146,7 @@ fn resolve(args: &AdjudicateArgs, apply: bool) -> Result<(), AppError> {
} }
output.push_str(&format!("└─ Record: @{}\n", report.id)); output.push_str(&format!("└─ Record: @{}\n", report.id));
output.push_str(&format!( output.push_str(&format!(
" Source potency: {}% → {}%{}\n", " Independent source potency: {}% → {}%{}\n",
report.source_potency_before / 100, report.source_potency_before / 100,
report.source_potency_after / 100, report.source_potency_after / 100,
if report.disposition == AdjudicationDisposition::Destroyed { if report.disposition == AdjudicationDisposition::Destroyed {
@ -145,14 +155,13 @@ fn resolve(args: &AdjudicateArgs, apply: bool) -> Result<(), AppError> {
"" ""
} }
)); ));
output.push_str(&epoch_totals(&workspace.worktree.world, &updated)?);
if !apply { if !apply {
output.push_str("Nothing changed. Use `efo adjudicate apply …` to update the worktree.\n"); output.push_str("Nothing changed. Use `efo adjudicate apply …` to update the worktree.\n");
print!("{output}"); print!("{output}");
return Ok(()); return Ok(());
} }
workspace.worktree.world = workspace.apply_resolution(updated)?;
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"); output.push_str("✓ Ruling recorded in the worktree. Undo: efo restore --worktree --all\n");
print!("{output}"); print!("{output}");
Ok(()) Ok(())
@ -288,3 +297,40 @@ fn target_type_label(value: EntityType) -> &'static str {
EntityType::Player => "player", EntityType::Player => "player",
} }
} }
/// Render aggregate effects separately from each independently clamped ruling.
pub(crate) fn epoch_totals(before: &EpochInfo, after: &EpochInfo) -> Result<String, AppError> {
let mut output = String::from("Epoch totals · independent ruling contributions\n");
for change in epoch_resolution::aggregate(after)? {
let current = before.find_entity_strict(change.target, None)?;
let current_value = **current.get_stats().get_field(&change.stat.list_stat());
output.push_str(&format!(
" • {} · {:?}: {} → {} (epoch base {}, contribution {:+})\n",
current.name,
change.stat,
current_value,
change.after,
change.before,
change.contribution
));
}
if let Some(state) = &after.epoch_resolution {
let sources = state
.records
.iter()
.filter_map(|id| after.adjudications.get(id))
.map(|report| report.source)
.collect::<std::collections::BTreeSet<_>>();
for id in sources {
if let Some(source) = after.event_adjudications.get(&id) {
output.push_str(&format!(
" Source @{id} · retained {}%{}\n",
source.potency_basis_points / 100,
if source.destroyed { " (destroyed)" } else { "" }
));
}
}
}
output.push_str("Commit or epoch next starts the next compounding interval.\n");
Ok(output)
}

View File

@ -9,18 +9,21 @@ use clap::{Args, Subcommand, ValueEnum};
use lib_efo::{ use lib_efo::{
adjudication::{ adjudication::{
AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec, AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec,
apply_to_world, preview,
}, },
conflict::{ conflict::{
ConflictKind, ConflictStatus, ParticipantRef, conflict_id, create_conflict, find_conflict, ConflictKind, ConflictStatus, ParticipantRef, conflict_id, create_conflict, find_conflict,
finish_round, finish_round,
}, },
entity::EntityIdentifier, entity::EntityIdentifier,
epoch_resolution,
stats::EntityType, stats::EntityType,
workspace::Workspace, workspace::Workspace,
}; };
use crate::{commands::adjudicate::parse_effect, error::AppError}; use crate::{
commands::adjudicate::{epoch_totals, parse_effect},
error::AppError,
};
/// Generic conflict operations. /// Generic conflict operations.
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@ -31,7 +34,7 @@ pub enum ConflictCmd {
List, List,
/// Show participants and applied rounds. /// Show participants and applied rounds.
Show(ConflictShowArgs), Show(ConflictShowArgs),
/// Preview or adjudicate the next round. /// Adjudicate a round against epoch-start stats; commit to compound rounds.
Advance(ConflictAdvanceArgs), Advance(ConflictAdvanceArgs),
/// Preview or explicitly end a conflict. /// Preview or explicitly end a conflict.
End(ConflictEndArgs), End(ConflictEndArgs),
@ -66,7 +69,7 @@ pub struct ConflictShowArgs {
/// One adjudicated round. /// One adjudicated round.
#[derive(Debug, Args)] #[derive(Debug, Args)]
#[command( #[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" after_long_help = "Round statistics share an epoch baseline until commit or epoch next.\nRound lifecycle still advances explicitly; contributions clamp independently.\n\nEXAMPLE:\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 { pub struct ConflictAdvanceArgs {
/// Name/prefix or @UUID. /// Name/prefix or @UUID.
@ -278,7 +281,13 @@ fn advance(args: &ConflictAdvanceArgs) -> Result<(), AppError> {
effects: effects.clone(), effects: effects.clone(),
policy_id: config.policy_id.clone(), policy_id: config.policy_id.clone(),
}; };
let report = preview(&config, &spec, target, conflict.round + 1)?; let report = epoch_resolution::preview(
&workspace.worktree.world,
&config,
&spec,
target.id,
conflict.round + 1,
)?;
if disposition == AdjudicationDisposition::Destroyed { if disposition == AdjudicationDisposition::Destroyed {
removed.insert(participant.id); removed.insert(participant.id);
} }
@ -302,18 +311,15 @@ fn advance(args: &ConflictAdvanceArgs) -> Result<(), AppError> {
&removed, &removed,
)?; )?;
output.push_str(&format!("Result · {}\n", status_label(&projected.status))); output.push_str(&format!("Result · {}\n", status_label(&projected.status)));
let mut updated = epoch_resolution::apply(&workspace.worktree.world, &config, &reports)?;
output.push_str(&epoch_totals(&workspace.worktree.world, &updated)?);
if !args.apply { if !args.apply {
output.push_str("Nothing changed. Re-run with `--apply` to update the worktree.\n"); output.push_str("Nothing changed. Re-run with `--apply` to update the worktree.\n");
print!("{output}"); print!("{output}");
return Ok(()); 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); updated.conflicts.insert(projected.id, projected);
workspace.worktree.world = updated; workspace.apply_resolution(updated)?;
workspace.save_worktree("advance conflict")?;
output.push_str("✓ Round stored in the worktree. Undo: efo restore --worktree --all\n"); output.push_str("✓ Round stored in the worktree. Undo: efo restore --worktree --all\n");
print!("{output}"); print!("{output}");
Ok(()) Ok(())

View File

@ -6,15 +6,18 @@ use clap::{Args, Subcommand, ValueEnum};
use lib_efo::{ use lib_efo::{
adjudication::{ adjudication::{
AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec, AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec,
apply_to_world, preview_at_potency,
}, },
entity::EntityIdentifier, entity::EntityIdentifier,
epoch_resolution,
simulation::{MobilityState, begin_diffusion, plan_diffusion, tick_diffusion}, simulation::{MobilityState, begin_diffusion, plan_diffusion, tick_diffusion},
stats::EntityType, stats::EntityType,
workspace::Workspace, workspace::Workspace,
}; };
use crate::{commands::adjudicate::parse_effect, error::AppError}; use crate::{
commands::adjudicate::{epoch_totals, parse_effect},
error::AppError,
};
/// Event diffusion operations. /// Event diffusion operations.
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@ -23,7 +26,7 @@ pub enum DiffuseCmd {
Start(DiffuseStartArgs), Start(DiffuseStartArgs),
/// Preview or advance every active event frontier. /// Preview or advance every active event frontier.
Tick(DiffuseTickArgs), Tick(DiffuseTickArgs),
/// Resolve one pending town arrival and its selected characters. /// Resolve an arrival using this epoch's starting target values and potency.
Resolve(DiffuseResolveArgs), Resolve(DiffuseResolveArgs),
} }
@ -43,7 +46,7 @@ pub enum CharacterPolicy {
/// Game-master ruling for one pending arrival. /// Game-master ruling for one pending arrival.
#[derive(Debug, Args)] #[derive(Debug, Args)]
#[command( #[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" after_long_help = "Rulings share an epoch baseline until commit or epoch next; contributions clamp independently.\n\nEXAMPLE:\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 { pub struct DiffuseResolveArgs {
/// Source event name/prefix or @UUID. /// Source event name/prefix or @UUID.
@ -166,20 +169,20 @@ fn resolve(args: &DiffuseResolveArgs) -> Result<(), AppError> {
effects, effects,
policy_id: config.policy_id.clone(), policy_id: config.policy_id.clone(),
}; };
let potency = workspace let baseline = epoch_resolution::inputs(&workspace.worktree.world);
.worktree let town = baseline
.world .find_entity_strict(town.id, Some(EntityType::Town))?
.clone();
let potency = baseline
.event_adjudications .event_adjudications
.get(&event) .get(&event)
.map_or(10_000, |state| state.potency_basis_points); .map_or(10_000, |state| state.potency_basis_points);
let mut targets = vec![(EntityType::Town, town.id, town.name.clone())]; let mut targets = vec![(EntityType::Town, town.id, town.name.clone())];
for character in selected_characters(&workspace.worktree.world, &town, args.characters) { for character in selected_characters(baseline, &town, args.characters) {
targets.push((EntityType::Character, character.id, character.name.clone())); targets.push((EntityType::Character, character.id, character.name.clone()));
} }
targets[1..].sort_unstable_by_key(|target| target.1); targets[1..].sort_unstable_by_key(|target| target.1);
let blockers = workspace let blockers = baseline
.worktree
.world
.blockers .blockers
.iter() .iter()
.filter(|blocker| { .filter(|blocker| {
@ -214,7 +217,13 @@ fn resolve(args: &DiffuseResolveArgs) -> Result<(), AppError> {
.worktree .worktree
.world .world
.find_entity_strict(*id, Some(*kind))?; .find_entity_strict(*id, Some(*kind))?;
let report = preview_at_potency(&config, &spec, target, diffusion.elapsed_ticks, potency)?; let report = epoch_resolution::preview(
&workspace.worktree.world,
&config,
&spec,
target.id,
diffusion.elapsed_ticks,
)?;
output.push_str(&format!("│ • {name} ({kind:?})")); output.push_str(&format!("│ • {name} ({kind:?})"));
if report.changes.is_empty() { if report.changes.is_empty() {
output.push_str(" · no stat changes\n"); output.push_str(" · no stat changes\n");
@ -230,15 +239,13 @@ fn resolve(args: &DiffuseResolveArgs) -> Result<(), AppError> {
reports.push((*kind, report)); reports.push((*kind, report));
} }
output.push_str(&format!("└─ Disposition: {:?}\n", args.disposition)); output.push_str(&format!("└─ Disposition: {:?}\n", args.disposition));
let mut updated = epoch_resolution::apply(&workspace.worktree.world, &config, &reports)?;
output.push_str(&epoch_totals(&workspace.worktree.world, &updated)?);
if !args.apply { if !args.apply {
output.push_str("Nothing changed. Re-run with `--apply` to resolve this arrival.\n"); output.push_str("Nothing changed. Re-run with `--apply` to resolve this arrival.\n");
print!("{output}"); print!("{output}");
return Ok(()); 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(|| { let state = updated.diffusions.get_mut(&event).ok_or_else(|| {
lib_efo::adjudication::AdjudicationError::Invalid( lib_efo::adjudication::AdjudicationError::Invalid(
"diffusion disappeared during resolution".into(), "diffusion disappeared during resolution".into(),
@ -248,8 +255,7 @@ fn resolve(args: &DiffuseResolveArgs) -> Result<(), AppError> {
for (_, report) in &reports { for (_, report) in &reports {
state.resolved.insert(report.target, report.id); state.resolved.insert(report.target, report.id);
} }
workspace.worktree.world = updated; workspace.apply_resolution(updated)?;
workspace.save_worktree("resolve diffusion arrival")?;
output.push_str("✓ Arrival resolved in the worktree. Undo: efo restore --worktree --all\n"); output.push_str("✓ Arrival resolved in the worktree. Undo: efo restore --worktree --all\n");
print!("{output}"); print!("{output}");
Ok(()) Ok(())

View File

@ -60,7 +60,10 @@ pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> {
checked += 1; checked += 1;
} }
} }
println!("✓ Repository format 1.0 is consistent ({checked} epoch(s) checked)."); println!(
"✓ Repository format {} is consistent ({checked} epoch(s) checked).",
workspace.manifest.format_version
);
} }
cli_epoch::EpochCmd::Switch(args) => { cli_epoch::EpochCmd::Switch(args) => {
let target = resolve_epoch(&workspace, &args.target)?; let target = resolve_epoch(&workspace, &args.target)?;

View File

@ -493,7 +493,7 @@ fn init_status_diff_and_fsck_workflow() {
let fsck = efo(&repo, &["epoch", "fsck"]); let fsck = efo(&repo, &["epoch", "fsck"]);
assert_success(&fsck); assert_success(&fsck);
assert!(stdout(&fsck).contains("Repository format 1.0 is consistent (2 epoch(s) checked)")); assert!(stdout(&fsck).contains("Repository format 1.1 is consistent (2 epoch(s) checked)"));
} }
#[test] #[test]
@ -504,7 +504,7 @@ fn native_staging_commit_restore_and_recovery_workflow() {
serde_json::from_slice(&fs::read(repo.path().join(".epoch")).expect("repository manifest")) serde_json::from_slice(&fs::read(repo.path().join(".epoch")).expect("repository manifest"))
.expect("parse repository manifest"); .expect("parse repository manifest");
assert_eq!(manifest["format_version"]["major"], 1); assert_eq!(manifest["format_version"]["major"], 1);
assert_eq!(manifest["format_version"]["minor"], 0); assert_eq!(manifest["format_version"]["minor"], 1);
assert!(repo.path().join(".efo/index.json").is_file()); assert!(repo.path().join(".efo/index.json").is_file());
assert!(repo.path().join(".efo/worktree.json").is_file()); assert!(repo.path().join(".efo/worktree.json").is_file());
@ -1233,3 +1233,137 @@ fn event_diffusion_is_deterministic_previewed_and_not_reapplied() {
.is_empty() .is_empty()
); );
} }
#[test]
fn adjudication_diffusion_and_conflict_share_epoch_inputs_and_restore_atomically() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
for name in ["Haven", "Rival"] {
assert_success(&efo(
&repo,
&[
"town",
"add",
name,
"--position",
"0,0",
"--stats",
"health:110",
],
));
}
for name in ["Blessing", "Storm"] {
assert_success(&efo(&repo, &["event", "add", name, "--position", "0,0"]));
}
assert_success(&efo(&repo, &["diffuse", "start", "Storm", "--apply"]));
assert_success(&efo(&repo, &["diffuse", "tick", "1", "--apply"]));
assert_success(&efo(
&repo,
&[
"conflict",
"start",
"Border",
"--kind",
"war",
"--side",
"red:town:Haven",
"--side",
"blue:town:Rival",
"--apply",
],
));
assert_success(&efo(&repo, &["stage", "--all"]));
assert_success(&efo(&repo, &["commit", "-m", "baseline"]));
let baseline = snapshot(&repo, 0);
let commands: [&[&str]; 3] = [
&[
"adjudicate",
"apply",
"Blessing",
"--target",
"town:Haven",
"--level",
"apocalypse",
"--effect",
"health:20",
],
&[
"diffuse",
"resolve",
"Storm",
"Haven",
"--level",
"apocalypse",
"--effect",
"health:-20",
"--characters",
"none",
"--apply",
],
&[
"conflict",
"advance",
"Border",
"--side-outcome",
"red:apocalypse:applied",
"--side-outcome",
"blue:apocalypse:applied",
"--effect",
"health:-10",
"--apply",
],
];
let mut final_state = None;
for order in [[0, 1, 2], [2, 1, 0], [1, 0, 2]] {
for index in order {
let output = efo(&repo, commands[index]);
assert_success(&output);
assert!(stdout(&output).contains("Epoch totals"));
}
let result = snapshot(&repo, 0);
let haven = result["towns"]
.as_array()
.expect("towns")
.iter()
.find(|town| town["name"] == "Haven")
.expect("Haven");
assert_eq!(haven["stats"]["health"], 90);
if let Some(expected) = &final_state {
assert_eq!(&result, expected);
}
final_state = Some(result.clone());
// Partial metadata operations would orphan contributions and must be refused.
let bytes = fs::read(repo.path().join(".efo/worktree.json")).expect("before");
assert!(
!efo(&repo, &["restore", "--worktree", "--world"])
.status
.success()
);
assert_eq!(
fs::read(repo.path().join(".efo/worktree.json")).expect("after"),
bytes
);
assert!(!efo(&repo, &["stage", "--world"]).status.success());
assert_success(&efo(&repo, &["epoch", "fsck"]));
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
assert_eq!(snapshot(&repo, 0), baseline);
}
// Commit changes the baseline; the same explicit ruling can then run again.
assert_success(&efo(&repo, commands[0]));
let first = snapshot(&repo, 0);
let duplicate = efo(&repo, commands[0]);
assert!(!duplicate.status.success());
assert_eq!(snapshot(&repo, 0), first);
assert_success(&efo(&repo, &["stage", "--all"]));
assert_success(&efo(&repo, &["epoch", "next"]));
assert_success(&efo(&repo, commands[1]));
let next = snapshot(&repo, 0);
let haven = next["towns"]
.as_array()
.expect("towns")
.iter()
.find(|town| town["name"] == "Haven")
.expect("Haven");
assert_eq!(haven["stats"]["health"], 100);
assert_success(&efo(&repo, &["epoch", "fsck"]));
}

View File

@ -15,6 +15,8 @@ behavior clearly.
fuzzing, roads, movement, diffusion, map rendering, and config packaging. fuzzing, roads, movement, diffusion, map rendering, and config packaging.
- [Adjudication/influx, diffusion resolution, and conflict](resolution-conflict-design.md): - [Adjudication/influx, diffusion resolution, and conflict](resolution-conflict-design.md):
implementation contract for tracker issues #9, #8, and #12. implementation contract for tracker issues #9, #8, and #12.
- [Deterministic execution](deterministic-execution-design.md): proposed snapshot
batches, independent RNG, reduction rules, compatibility analysis, and mental checks.
- [Presentation and export](presentation-design.md): remaining buffered, - [Presentation and export](presentation-design.md): remaining buffered,
coherent, saveable output contract for tracker issue #10. coherent, saveable output contract for tracker issue #10.
- [Roadmap](roadmap.md): current work and stretch proposals. - [Roadmap](roadmap.md): current work and stretch proposals.

View File

@ -24,9 +24,9 @@ metadata as the model becomes organisation-agnostic.
Phase 4's approved persistence boundary is specified in the Phase 4's approved persistence boundary is specified in the
[staging, history, and recovery design](staging-design.md). It separates HEAD, [staging, history, and recovery design](staging-design.md). It separates HEAD,
the index, and the editable worktree, and defines the atomic transaction rules the index, and the editable worktree, and defines the atomic transaction rules
that implementation must preserve. The sole pre-release repository format is that implementation must preserve. Repository format 1.1 adds a persisted epoch-resolution baseline; 1.0 remains
version 1.0; its structured major/minor discriminator leaves room for explicit readable and upgrades atomically on resolution publication or new history.
1.x migrations without retaining an unreleased prototype reader. The structured version rejects readers that cannot preserve the new state.
The [TUI contract](tui-design.md) covers browsing and previewed entity editing. The [TUI contract](tui-design.md) covers browsing and previewed entity editing.
`EntityDraft` validates forms in the library; `Workspace::apply_entity_change` `EntityDraft` validates forms in the library; `Workspace::apply_entity_change`
checks the editor snapshot and writes the worktree under one transaction lock. checks the editor snapshot and writes the worktree under one transaction lock.
@ -34,8 +34,17 @@ The TUI retains the prior entity for one-step, conflict-checked undo.
Library tests cover parsing, statistics, display snapshots, entity/epoch Library tests cover parsing, statistics, display snapshots, entity/epoch
behavior, and repository transactions. CLI behavior is covered by subprocess behavior, and repository transactions. CLI behavior is covered by subprocess
integration workflows; Tarpaulin excludes those thin adapters because its integration workflows. Tarpaulin cannot attribute child-process execution to
ptrace backend cannot reliably attribute child-process execution. Routine CI the thin CLI adapters, but keeps all production code in the measured surface.
should run formatting, all-target workspace tests, strict Clippy, and a release Routine CI runs formatting, all-target workspace tests, strict Clippy, a
build. Tarpaulin and `rust_autobadges` remain local significant-release-only release build, and pinned Tarpaulin line coverage with the documented 65%
tools. See [AGENTS.md](../AGENTS.md) for contributor rules. floor. During cleanup, Jenkins generates, archives, and conditionally publishes
the three mutable badges so failed builds cannot leave stale success or
coverage status. See [AGENTS.md](../AGENTS.md) for contributor rules.
`epoch_resolution` owns independent baseline previews and exact contribution
reduction for adjudication, diffusion arrivals, and conflict rounds. CLI handlers
render local and aggregate outcomes and call `Workspace::apply_resolution` for
locked stale-snapshot validation and publication. `event_rng` provides immutable
named ChaCha12 draws from frozen event inputs; adjudication remains externally
rolled. See [the execution contract](deterministic-execution-design.md).

View File

@ -5,7 +5,7 @@ parent directories. `efo <command> --help` is the authoritative syntax.
## Repository and timeline ## Repository and timeline
- `efo init [--force]` creates the format-1.0 manifest, HEAD, index, worktree, - `efo init [--force]` creates the format-1.1 manifest, HEAD, index, worktree,
and `epoch/0/epochinfo.json`. The normal and `epoch/0/epochinfo.json`. The normal
form requires an empty directory; `--force` permits unrelated existing files form requires an empty directory; `--force` permits unrelated existing files
but never overwrites `.epoch` or epoch 0. but never overwrites `.epoch` or epoch 0.
@ -110,6 +110,38 @@ carry their own speed; disconnected characters fall back to slower direct
travel. Characters have explicit resident, roaming, or travelling state. Use travel. Characters have explicit resident, roaming, or travelling state. Use
`efo restore --worktree --all` to discard applied simulation changes. `efo restore --worktree --all` to discard applied simulation changes.
## Epoch-wide resolution semantics
`adjudicate`/`influx`, `diffuse resolve`, and `conflict advance`/`fight`/`war`
share the worktree snapshot frozen by the first applied resolution after each
commit. Each ruling reads those target stats and source potency, clamps its own
result, and contributes `local result - epoch base`. The aggregate adds that
sum to the base once and clamps again. Preview prints both the independent
ruling and the actual combined epoch totals. For health 110, +20 and -20 yield
100 in either order (contributions +10 and -20).
Apply rulings in any order once their explicit arrivals/rounds are ready.
`efo stage --all` followed by `efo commit -m ...` or `efo epoch next` ends the
interval; later rulings read the combined result. Conflict lifecycle, travel,
and diffusion scheduling still advance explicitly. Destroying a source stops
its own frontier immediately, but cannot erase already admitted same-epoch
stat contributions. In-transit/resident selection for arrival resolution uses
the frozen snapshot. Create entities and set up topology before the first
resolution, or commit before resolving newly created targets/sources.
An identical adjudication in the same epoch is rejected as already recorded.
Use `--occurrence NUMBER` on `adjudicate preview/apply` for a deliberate repeated
ruling; keep the number stable when retrying. A new epoch automatically gives
the same ruling a distinct identity. A duplicate error never reapplies effects.
Epoch Forge still does not roll dice or reinterpret external results.
Use `efo restore --worktree --all` to discard a resolution or `efo revert` for
committed history. Partial stage/restore cannot split its statistics and audit.
Commit before manually editing statistics already participating in the interval.
Applying refuses stale repository state; rerun the command for a fresh preview.
See [deterministic execution](deterministic-execution-design.md) and
[format compatibility](repository.md#epoch-resolution-state-11).
## Event diffusion ## Event diffusion
Events propagate from their map position over the same topology. Roads use Events propagate from their map position over the same topology. Roads use

View File

@ -0,0 +1,246 @@
# Deterministic event execution
Status: the serial epoch reducer, persisted baseline, and all three CLI
resolution paths are implemented. Actual worker pools remain future work.
This extends the [resolution design](resolution-conflict-design.md) and
[simulation design](simulation-worldgen-design.md). See the
[implementation checklist](epoch-resolution-tasks.md).
The first applied resolution after a commit freezes the complete worktree.
Further invocations use that baseline until the epoch ID changes on commit or
`epoch next`. Each externally supplied ruling is an independent work item;
its effective contribution is its clamped result minus the baseline. Reports
are enrolled incrementally, with duplicate application refused. A future worker
scheduler must freeze its complete task manifest before dispatch; the current
CLI does not automatically discover or generate event tasks.
## Guarantee and scope
Given the same initial semantic world, seed, explicit rulings, logical batch,
configuration, and versioned rules, execution must produce identical semantic
state and canonical reports regardless of worker count, scheduling, partitioning,
completion order, or task retries. Wall-clock time and transaction bookkeeping
are outside this guarantee and must never feed simulation decisions.
A batch resolves one epoch from an immutable starting snapshot S. Its event
manifest is explicit, not whatever happens to fit in a worker queue. Events
compound across epochs, never through other events in the same epoch. All tasks in a batch read S, including target
stats, source potency, positions, protection, topology, and eligibility. No task
reads another task's proposed writes. Statistical dependencies between rulings require the next epoch. A future
event evaluator may perform ordered internal steps on its own private copy;
the current evaluator treats every supplied ruling independently. Scheduling
arrivals and conflict rounds remains explicit and ordered.
## Randomness and task identity
Use seed plus a stable event hash as a keyed derivation, not arithmetic addition
or Rust's default hash. `event_rng::EventRandom` implements
`epoch-forge/event-rng-chacha12-fnv-v1`: four domain-labelled FNV-1a-64 lanes
derive a 256-bit seed for pinned `rand_chacha` 0.9.0 `ChaCha12Rng`. Each field
has a u64 little-endian byte-length prefix; integer fields and output hash lanes
use little endian, UUIDs use their standard 16-byte representation. Map/set entries use
stable key order; integers have fixed width and byte order. Do not hash display
text, memory addresses, paths, worker numbers, or mutable output fields.
Separate occurrence identity from event contents:
```text
occurrence = (source UUID, logical tick/round, phase, occurrence ordinal)
task = (occurrence, target UUID, effect slot)
key = H("efo/event-rng/v1", seed, occurrence,
canonical event-definition hash, rules/config digest)
draw = RNG(key, target UUID, purpose label, draw index)
```
Ordinals and effect slots must come from stable input identities, never queue
positions or atomic counters. Distinct identical-looking events retain distinct
UUIDs. Retrying an occurrence reuses its draws; a later occurrence has different
draws. An intentionally lifetime-fixed event roll omits tick/round explicitly.
Event-wide shared draws omit the target explicitly; independent target draws
include it. Named substreams prevent a new cosmetic draw or target from shifting
existing outcomes. Pin bounded-integer sampling and rejection behavior as well
as the underlying generator, with golden vectors. The implemented `below`
method rejects draws below `2^64 mod upper`, then returns `draw mod upper`.
Each rejection has an independent retry index, capped at 1024 attempts.
Golden vectors cover both accepted-first and rejected-first draws.
Hash equality must not silently merge different tasks: retain canonical identity
alongside the digest and reject a detected collision. Content identity is not
application identity: two intentional identical rulings need distinct occurrence
IDs, while a retry must retain the original ID.
The high-level `for_event` helper reads the frozen event definition and seed,
combines them with the epoch ID, event UUID, occurrence number, and caller's
rules/configuration, and sorts JSON object keys recursively. Arrays retain
semantic order. `draw(target, purpose, index)` is immutable and random-access;
`None` means an event-wide draw and differs from even a nil target UUID. Event
key derivation is deterministic and noncryptographic; it is not a security API.
The caller owns versioned purpose labels and occurrence IDs. Do not feed worker
indices, current time, or unordered semantic arrays into that identity.
Adjudication remains an external player roll and explicit GM decision. These
RNG rules authorize no automatic adjudication rolls. Current world generation
uses one sequential `StdRng` stream in `worldgen::generate`; its seed alone does
not make generation tasks independently schedulable. Preserve the current
same-binary guarantee until a versioned generation algorithm replaces it.
Thread-local/fuzzy random helpers must not be reachable from replayable tasks.
## Evaluate, reduce, normalize, publish
1. Validate S and freeze a complete, bounded task manifest, rules, and config.
A future worker pool assigns stable batch/task identities before dispatch;
current commands identify reports by epoch, source, target, ruling content,
and explicit occurrence/tick/round.
2. Pure workers return proposals and diagnostics. A numeric proposal is an
**effective signed contribution** against S: the event-local normalized
result minus the original value. Per-ruling and per-event clamping are
allowed inside the isolated event evaluator. Workers perform no repository writes,
output, clock reads, or global RNG calls.
3. Collect exactly one result per expected task. Identical retry results are
deduplicated; conflicting duplicates, missing tasks, or any failure abort
the batch. Completion order cannot decide which results count.
4. Group additive proposals by stable target and primitive field identity:
```text
contribution_i = normalize(f_i(S))[target, field] - S[target, field]
D[target, field] = exact_sum(all event contributions for this key)
raw_after = S[target, field] + D[target, field]
after = normalize(raw_after, target kind, rules)
```
Add the original value once. A percentage effect computes its delta from S,
so two +10% effects on 100 yield 120, not 121. This is simultaneous semantics.
5. Normalize the combined primitive stats again, then recompute derived stats in a
specified dependency order. Initially normalization means the existing
`OverallStats::clamp_for` domains: ordinary population >= 0; event/blocker
population >= -120; growth rate in [-120, 120]; other primitive stats in
[0, 120], or [-120, 120] for events/blockers. Population has no domain upper
cap beyond representation limits. Do not use display-scale conversions.
6. Reduce nonnumeric state with explicit rules below, validate the complete
result, and produce a canonical report. Sort by phase, source, occurrence,
target, effect slot, and diagnostic code as applicable, never arrival order.
7. Under the repository writer lock, verify the entire input snapshot revision
and rules/config digest are still current; abort stale work. Publish the
world and batch receipt together through existing transaction/recovery
mechanisms. The current CLI refuses already-recorded rulings without applying them again.
Deliberate repeated direct rulings use `--occurrence`; future worker-result
retries may be deduplicated before publication.
Use fixed-width checked arithmetic and an exact widened accumulator (for
example i128 with validated magnitude/task limits proving no intermediate
overflow). Reject unsupported ranges deterministically before publication.
Never use saturating partial sums: they are not associative with mixed signs.
Specify signed division as truncation toward zero and round each scaled effect
at a defined step, then sum integers. Preserve the current nested attenuation
rounding when compatibility is required. Floating-point parallel reductions
are outside this initial contract. Scaling and sums now use i128 intermediates, but persisted `isize` ranges
still limit cross-platform replay; no persisted numeric format is changed by this proposal.
Reports retain each requested/scaled delta, event-local clamped contribution, common before value,
aggregate delta, final after value, and normalization adjustment. Do not claim
that each event individually achieved its full delta when the total was clamped.
There is no unique per-event allocation of clamping loss; defer attribution
unless a versioned allocation policy is introduced.
## State that cannot simply be summed
| Operation | Required batch rule |
|---|---|
| Source potency | Minimum of starting potency and all proposed retained potencies; destruction dominates and gives zero. |
| Destroyed/expired flags | Logical OR; no implicit resurrection. |
| Affected/resolved sets | Set union; conflicting values for the same resolution key are an error, not last-writer-wins. |
| Source audit pointer | Select the final record in canonical order, or introduce a batch link; never use completion order. |
| Conflict lifecycle | Compute once after all participant outcomes/removals have been reduced. |
| Replacement, movement, ownership, deletion | Require a versioned conflict policy or reject competing proposals; do not convert arbitrary writes into deltas. |
| Resource transfers | Collect demands, then allocate deterministically against snapshot capacity; preserve both sides of each transfer. |
| Spawned events/entities | Derive IDs from parent occurrence and stable child slot; admit them in the next phase/tick. |
For simultaneous resolution, every admitted target uses the source potency
from S. Destruction reduces retained source potency to zero for the next epoch and
stops that source's own frontier immediately. It does not retroactively cancel
other admitted same-epoch contributions. If destruction should prevent another event, that event belongs to a later
epoch. Earlier logical arrivals must precede later ones;
a multi-tick command cannot collapse dependent ticks into one snapshot.
Define travel/arrival/resolution phase order before integrating simulation
commands: e.g. advance travel, freeze arrival positions, propagate diffusion,
then resolve supplied rulings. This is a proposed order, not existing behavior.
Threshold-triggered follow-up events inspect normalized results in the next
epoch; no same-phase feedback loops. Competing transfers cannot merely debit,
clamp at zero, and credit in full, because that creates resources.
## Comparison with the previous sequential implementation
The previous paths were `adjudication::preview_at_potency`,
`apply_to_target`, and `apply_to_world`, plus CLI arrival/conflict orchestration.
Diffusion ticks themselves mark arrivals/expiry; they do not apply stat effects.
- The low-level legacy preview scales chosen/default deltas, mutates a target clone, and calls
`update_metastats` after each effect. Application checks recorded before
values and writes absolute after-values. Two previews of the same field from
one snapshot cannot safely be applied successively: the second normally
fails its stale check. The implemented `epoch_resolution` API now performs independent preview and
aggregate application instead.
- Previously, separate rulings read the latest world and clamped each time. With health 110,
effects +20 then -20 yield 100; reversing them yields 110. Snapshot summation
of independently clamped contributions yields 100 in either worker order.
At health 5, -10 then +10 yields 10, reversed yields 5, and independent
clamping plus snapshot summation yields 10. Thus this proposal is
**not generally equivalent to sequential adjudication**.
- Fixed additive deltas agree when intermediate clamping/overflow never occurs
and target selection, scaling, source state, and other dependencies stay
unchanged. Percentage compounding is a hypothetical future effect, not the
current explicit signed-delta API.
- An arrival resolution already previews the town and selected characters
against the same snapshot and potency, then applies reports to distinct
targets. A conflict round similarly previews distinct participants. These
paths now share the epoch reducer, including overlapping targets.
- Previously, event rulings could reduce source potency before later defaults were
calculated. Within the implemented epoch interval they all use initial potency. This is
another intentional semantic change. Explicit effects bypass default level
and source scaling, but still undergo disposition attenuation and clamping.
- `apply_to_world` currently overwrites source state from each report and
`apply_to_target` checks changed target fields, not the complete read set.
Those legacy primitives are no longer used by CLI resolution; on their own, a late old report could
overwrite stronger attenuation/destruction. Reduce source state and validate
the snapshot once instead of reusing the per-report application loop.
Historical records retain their existing interpretation. All resolution commands
will adopt the new ruleset using a persisted epoch baseline; see the
[implementation task list](epoch-resolution-tasks.md). The 1.1 schema provides old-data defaults, compatibility fixtures, and atomic
publication/recovery.
Never silently reinterpret old sequential reports as simultaneous contributions.
## Mental soundness checks and implementation gates
| Scenario | Expected result / gap exposed |
|---|---|
| Permute tasks, worker counts, and reduction trees | Identical exact totals, normalized world, IDs, reports, and ordered diagnostics. |
| Retry one +7 task twice | +7 once, not +14; requires manifest identity and deduplication. |
| Two distinct identical +7 occurrences | +14; content hashing alone must not erase an occurrence. |
| +20/-20 at health 110 | 100: independently clamped contributions are +10 and -20. |
| Two -10 demands on a resource balance of 10 | Needs allocation; naive clamping cannot conserve paired credits. |
| Destroy and dampen one source concurrently | Source remains destroyed at potency zero; other admitted events still use S. |
| Target unchanged, blocker/road/source/config edited during evaluation | Entire batch is stale; checking written fields alone is insufficient. |
| A worker fails, or process dies before publication | No partial world; journal recovery handles interrupted publication. |
| Add a target or unrelated random draw | Existing named draws stay unchanged when their declared inputs stay unchanged. |
| Split a dependent ten-tick run into ten one-tick runs | Same result only if both execute the same logical phase barriers. |
| Threshold reached midway through contributions | Trigger next epoch after normalization, once, with a stable child identity. |
| Extreme mixed-sign deltas on different architectures | Same result or same validated range error, never wrapping/saturating by schedule. |
The proof is conditional but simple: pure evaluation fixes each proposal;
deduplication fixes the proposal multiset; exact addition, min, OR, and set union
are associative and commutative; deterministic normalization and lifecycle rules
fix the final world. Any operation outside those conditions needs an explicit
reducer or a phase dependency. A lock alone cannot provide this guarantee.
Before adding threads, turn this table into tests against a serial reference:
permutation/partition properties, golden RNG/encoding vectors, legacy-versus-batch
boundary fixtures, duplicate/missing/conflicting results, stale-read refusal,
limits, crash recovery, and byte-equivalent canonical reports. Then compare real
worker-pool runs with deliberately varied scheduling to that same reference.
Executable tests now cover ruling-order permutations across all three command
families, clamping, source reduction, duplicates, stale snapshots, old data,
corruption, limits, stage/restore/revert, and next-epoch compounding. Worker-pool
scheduling, transfers, spawned events, and integrated tick phases remain design
requirements, not implemented features.

View File

@ -0,0 +1,73 @@
# Epoch resolution implementation plan
Scope: all existing adjudication, diffusion-arrival, and conflict-round commands
adopt simultaneous epoch statistics. Actual worker pools and automated GM rolls
are out of scope. This is a cross-cutting library/persistence/CLI change, not
merely moving a clamp: independent CLI invocations need durable common inputs.
The first resolution after a commit freezes the worktree as the epoch baseline.
Every ruling reads its target and source potency from that baseline. Its local
result is clamped; its contribution is `local_after - baseline`. Contributions
are summed exactly, added to the baseline once, then clamped again. A commit
ends the accumulation interval. `epoch next` also commits, so compounds normally.
Repeated conflict rounds within that interval use the same statistical baseline;
round lifecycle and explicit diffusion arrival bookkeeping remain ordered.
## Incremental commits
- [x] Create `feat/deterministic-epoch-resolution`; revise the execution contract
and record this assessment and task list.
- [x] Add versioned persisted epoch baseline/record membership with old-data
defaults and compatibility fixtures before activating the new schema.
- [x] Implement pure baseline preview and exact reduction of clamped ruling
contributions; merge source potency by minimum and destruction by OR.
- [x] Test permutations, bounds, overlapping targets, duplicates, stale edits,
source state, malformed persisted accumulators, and cross-epoch compounding.
- [x] Integrate all three CLI resolution paths and show epoch aggregate results
separately from independent ruling outcomes.
- [x] Persist resolutions with a full stale-snapshot check under the writer
lock; integrate staging, restore, revert, historical validation, and format
compatibility safeguards.
- [x] Add deterministic event-local named random draws with pinned encoding and
golden vectors, without introducing RNG into externally adjudicated rulings.
- [x] Update command/help/repository documentation and CLI workflow tests; run
formatting, locked all-feature workspace tests, and strict Clippy before each
implementation commit.
## Design decisions and risks
- Older binaries must refuse repositories after the new accumulator is written;
silently dropping it would reintroduce compounding. Use a minor format bump
and atomic manifest/worktree publication on the first new-format write.
- Old records remain sequential audit entries. Only explicitly enrolled records
contribute to the active accumulator; never infer membership from timestamps.
- Manual edits to a contributing field require an epoch boundary or restoring
the resolution. A stale proposal must not overwrite them.
- Exact integer reduction is necessary: saturation during summation is dependent
on order. Retain current stat domains and validate representation limits.
- Source exhaustion cannot cancel already admitted simultaneous effects. Source
potency used by subsequent rulings stays at the epoch baseline.
- Membership and baseline increase snapshot size. Keep only the current interval's
baseline, without recursively embedding earlier accumulators; committed epochs
preserve earlier baselines and audit history.
- Event-local RNG is a foundation API; worldgen's existing sequential stream is
a separate versioned generator and remains unchanged in this feature.
Checkpoint 1: pure reducer and six library tests pass. The schema defaults to
absent on legacy data; ordinary format-1.0 saves explicitly refuse accumulator
state until transactional format publication is integrated in checkpoint 2.
Checkpoint 2: all resolution command families use the reducer; format-1.1
publication validates the full snapshot under lock. Integration tests exercise
mixed-command order, staging/restore, compounding, compatibility, locks,
interrupted transactions, stale input, and revert.
Checkpoint 3: immutable event-local ChaCha12 draws use explicit seed/epoch/event/
occurrence identities and named target/purpose/index keys. Generator and encoding
versions are pinned; golden vectors were cross-checked with an independent
Python FNV/ChaCha12 reference calculation. GM rulings and existing worldgen do
not call this API. No worker pool, transfer allocation, or automatic event
scheduling is introduced by this feature.
Final validation: formatting, 167 locked all-feature workspace tests, and strict
Clippy pass. All implementation increments are committed on the feature branch.

View File

@ -16,12 +16,10 @@
└── … └── …
``` ```
`efo init` creates this layout directly. There is no earlier supported format: `efo init` creates this layout directly. The earlier format-1.0 layout remains readable. Prototype layouts before
Epoch Forge has not made a stable release, so the former prototype layout and 1.0 remain unsupported.
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 manifest currently records format `1.1` as a structured major/minor value.
The application version is separate. Minor format releases (`1.1`, `1.2`, …) The application version is separate. Minor format releases (`1.1`, `1.2`, …)
may use explicit migrations while preserving the major compatibility family; may use explicit migrations while preserving the major compatibility family;
a future breaking layout would increment the major version. Newer minor or a future breaking layout would increment the major version. Newer minor or
@ -67,3 +65,31 @@ repeat.
Keep important repositories in Git or another backup system. For corruption, Keep important repositories in Git or another backup system. For corruption,
copy the complete directory before investigation and run the read-only copy the complete directory before investigation and run the read-only
`efo epoch fsck`; it reports damage but never guesses a repair. `efo epoch fsck`; it reports damage but never guesses a repair.
## Epoch resolution state (1.1)
The optional `epoch_resolution` field stores ruleset
`epoch-forge/epoch-resolution-1`, a complete first-resolution baseline, and the
set of enrolled adjudication IDs. The baseline has no nested resolution state.
Each new adjudication identifies its `epoch_baseline`; absent fields on 1.0
records mean historical sequential semantics. Old records are never enrolled
implicitly; their already-applied effects become part of the first new baseline. Committed snapshots retain the interval's audit inputs; a new
interval replaces the worktree's baseline rather than nesting previous ones.
Existing 1.0 repositories open without writes. Applying a resolution upgrades
the worktree and manifest together under the writer lock in a manifest-last
transaction. A preview never upgrades. New repositories and newly published
history use 1.1. Older binaries reject the newer minor version; there is no
lossy downgrade path. Historical 1.0 epochs remain unmodified. Recovery uses
`efo recover`; restoring a resolution removes its worktree changes while
retaining the protective manifest version. To use an older binary again, restore
an external backup of the entire pre-upgrade repository.
A resolution couples entity statistics, source state, and audit membership.
Stage or restore the complete change with `--all`; partial operations that
would separate those parts fail before writing. `fsck` validates membership,
epoch identity, local clamps, active aggregate statistics, and source reduction.
Manual changes to an actively contributing statistic require committing the
resolution first (or restoring it). Other fields remain editable; a newly
resolved field must still match its frozen baseline. Resolution publication
rejects any repository change since preview, including unrelated metadata.

View File

@ -10,6 +10,13 @@ appearing in this document.
## Product contract ## Product contract
Simultaneous epoch resolution is implemented for all three command families.
The [execution contract](deterministic-execution-design.md) and
[implementation task list](epoch-resolution-tasks.md) cover frozen inputs,
independent clamping, exact reduction, compatibility, and future worker pools.
The first resolution freezes the worktree baseline; commit/epoch-next ends the
interval. Reports distinguish local outcomes from aggregate epoch totals.
An **adjudication** (formerly called an “influx”) is a player-made roll outside An **adjudication** (formerly called an “influx”) is a player-made roll outside
Epoch Forge. The game master interprets that result, chooses its level, Epoch Forge. The game master interprets that result, chooses its level,
disposition, targets, and exact effects, then uses Epoch Forge to preview and disposition, targets, and exact effects, then uses Epoch Forge to preview and
@ -84,8 +91,9 @@ be accidentally applied twice. No RNG exists in this subsystem.
Chosen effects are typed field/stat deltas, not formatted text. Every previewed Chosen effects are typed field/stat deltas, not formatted text. Every previewed
change carries before/applied-delta/projected-after values and the normal change carries before/applied-delta/projected-after values and the normal
clamping policy. clamping policy.
Application verifies the target still has the recorded before value; stale Application verifies reports against the frozen baseline, reduces all enrolled
state aborts the whole transaction with recovery guidance. contributions, and checks the complete repository snapshot under the writer
lock. Stale state aborts the whole transaction with recovery guidance.
### Disposition and attenuation ### Disposition and attenuation
@ -173,8 +181,9 @@ Acceptance gates:
Implemented source behavior: every applied adjudication stores the event's Implemented source behavior: every applied adjudication stores the event's
remaining potency separately from ordinary entity statistics. The configured remaining potency separately from ordinary entity statistics. The configured
level multiplier can only maintain or reduce that potency. Later policy-default level multiplier can only maintain or reduce that potency. Policy-default
effects include the remaining potency in their attenuation, while explicit GM effects in the next epoch include the remaining potency; all rulings within
one epoch use its starting potency. Explicit GM
effects remain exact overrides. A `destroyed` ruling sets potency to zero, effects remain exact overrides. A `destroyed` ruling sets potency to zero,
expires an existing frontier, and prevents a new diffusion from starting. expires an existing frontier, and prevents a new diffusion from starting.
`adjudicate list EVENT` and diffusion output expose the current percentage. `adjudicate list EVENT` and diffusion output expose the current percentage.
@ -278,10 +287,11 @@ record uniqueness, monotonic conflict rounds, resolved-target links, ruleset
IDs, and configured safety limits. `fsck` exercises the same validation for IDs, and configured safety limits. `fsck` exercises the same validation for
every historical epoch. every historical epoch.
These additions remain backward-readable through defaults while the project is Epoch resolution adds a nonrecursive baseline and record membership under
unreleased. Freeze the exact format before the first release; after that point, repository format 1.1. Old data defaults to no accumulator; historical reports
any semantic reinterpretation requires a 1.x migration fixture and previewed retain their sequential meaning. Publication upgrades version protection
upgrade path under issue #17. atomically, so older binaries cannot silently drop the baseline. See the
[repository compatibility contract](repository.md#epoch-resolution-state-11).
## Delivery slices ## Delivery slices

View File

@ -23,7 +23,7 @@ Nerd Font output has a portable build option, relationships are type-validated,
and every mutation has documented and tested recovery guidance. and every mutation has documented and tested recovery guidance.
The [Phase 4 format contract](staging-design.md) is implemented. Native format The [Phase 4 format contract](staging-design.md) is implemented. Native format
1.0 initialization, locking, recovery, staging, immutable commits, revert, and 1.1 initialization, locking, recovery, staging, immutable commits, revert, and
recoverable pruning are implemented. The unreleased prototype reader and its recoverable pruning are implemented. The unreleased prototype reader and its
temporary migration were removed before the first release. Future compatible temporary migration were removed before the first release. Future compatible
changes use 1.x versions and regain explicit migration tooling when needed. changes use 1.x versions and regain explicit migration tooling when needed.
@ -59,3 +59,9 @@ direct terminal printing. PNG map rendering follows those tracker issues.
Completions and structured output are the best first stretch investments. A TUI Completions and structured output are the best first stretch investments. A TUI
and branching should wait until staging, revert, and locking are reliable. and branching should wait until staging, revert, and locking are reliable.
Epoch-wide independent ruling reduction is implemented across adjudication,
diffusion resolution, and conflict rounds, with format-1.0 compatibility reads.
Named event-local RNG is available as a library foundation. Worker pools,
automatic event scheduling, and transfer allocation remain future work; see
[the completed implementation checklist](epoch-resolution-tasks.md).

View File

@ -19,6 +19,7 @@ cli-table = "0.5.0"
colored = {workspace = true} colored = {workspace = true}
uuid = {workspace = true} uuid = {workspace = true}
rand = "0.9.2" rand = "0.9.2"
rand_chacha = "=0.9.0"
once_cell = "1.21.3" once_cell = "1.21.3"
tempfile = "3.23.0" tempfile = "3.23.0"

View File

@ -69,7 +69,7 @@ pub enum AdjudicationDisposition {
} }
/// Supported editable statistic names. /// Supported editable statistic names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum StatName { pub enum StatName {
/// Population count or modifier. /// Population count or modifier.
@ -407,6 +407,9 @@ pub struct AdjudicationReport {
pub target: Uuid, pub target: Uuid,
/// Simulation tick or conflict round. /// Simulation tick or conflict round.
pub tick_or_round: u64, pub tick_or_round: u64,
/// Simultaneous baseline epoch; absent on historical sequential rulings.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub epoch_baseline: Option<crate::epoch::EpochId>,
/// Master-assigned magnitude. /// Master-assigned magnitude.
pub level: AdjudicationLevel, pub level: AdjudicationLevel,
/// Master-selected disposition. /// Master-selected disposition.
@ -490,12 +493,17 @@ pub fn preview_at_potency(
let stat = effect.stat.list_stat(); let stat = effect.stat.list_stat();
let before = **projected.get_stats().get_field(&stat); let before = **projected.get_stats().get_field(&stat);
let applied_delta = scale(effect.delta, attenuation); let applied_delta = scale(effect.delta, attenuation);
let local_after = crate::epoch_resolution::normalize(
effect.stat,
target.entity_type,
before as i128 + applied_delta as i128,
)?;
projected.change_stat_strict( projected.change_stat_strict(
StatPair { StatPair {
stat, stat,
value: applied_delta.into(), value: local_after.into(),
}, },
Modification::Delta, Modification::Replace,
); );
projected.update_metastats(); projected.update_metastats();
let after = **projected.get_stats().get_field(&stat); let after = **projected.get_stats().get_field(&stat);
@ -526,6 +534,7 @@ pub fn preview_at_potency(
source: spec.source, source: spec.source,
target: target.id, target: target.id,
tick_or_round, tick_or_round,
epoch_baseline: None,
level: spec.level, level: spec.level,
disposition: spec.disposition, disposition: spec.disposition,
external_result: spec.external_result.clone(), external_result: spec.external_result.clone(),
@ -716,13 +725,13 @@ fn validate_effects(effects: &[ChosenEffect], max_effects: usize) -> Result<(),
Ok(()) Ok(())
} }
/// Apply a basis-point multiplier with saturating multiplication. /// Scale in widened arithmetic; validated multipliers cannot increase magnitude.
fn scale(value: isize, basis_points: isize) -> isize { fn scale(value: isize, basis_points: isize) -> isize {
value.saturating_mul(basis_points) / 10_000 ((value as i128 * basis_points as i128) / 10_000) as isize
} }
/// Generate a stable UUID from canonical serialized content. /// Generate a stable UUID from canonical serialized content.
fn content_id(bytes: &[u8]) -> Uuid { pub(crate) fn content_id(bytes: &[u8]) -> Uuid {
let mut high = 0xcbf2_9ce4_8422_2325_u64; let mut high = 0xcbf2_9ce4_8422_2325_u64;
let mut low = 0x8422_2325_cbf2_9ce4_u64; let mut low = 0x8422_2325_cbf2_9ce4_u64;
for byte in bytes { for byte in bytes {

View File

@ -110,6 +110,10 @@ pub struct EpochInfo {
#[serde(default)] #[serde(default)]
#[table(skip)] #[table(skip)]
pub conflicts: BTreeMap<Uuid, ConflictState>, pub conflicts: BTreeMap<Uuid, ConflictState>,
/// Frozen inputs and enrolled records for simultaneous epoch resolution.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[table(skip)]
pub epoch_resolution: Option<Box<crate::epoch_resolution::EpochResolution>>,
} }
impl Prettiable for EpochInfo {} impl Prettiable for EpochInfo {}
@ -135,6 +139,7 @@ impl Default for EpochInfo {
adjudications: BTreeMap::new(), adjudications: BTreeMap::new(),
event_adjudications: BTreeMap::new(), event_adjudications: BTreeMap::new(),
conflicts: BTreeMap::new(), conflicts: BTreeMap::new(),
epoch_resolution: None,
} }
} }
} }

View File

@ -0,0 +1,453 @@
//! Simultaneous, independently clamped rulings sharing a durable epoch baseline.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
adjudication::{
AdjudicationConfig, AdjudicationDisposition, AdjudicationError, AdjudicationReport,
AdjudicationSpec, EventAdjudicationState, StatName, preview_at_potency,
},
epoch::EpochInfo,
stats::{EntityType, Modification, StatPair},
};
/// Persisted interpretation of independently clamped epoch contributions.
pub const RULESET: &str = "epoch-forge/epoch-resolution-1";
/// One accumulation interval. Committing changes the epoch ID and closes it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EpochResolution {
/// Explicit ruleset; unknown interpretations are rejected.
pub ruleset: String,
/// Frozen inputs, without recursively embedded resolution state.
pub baseline: Box<EpochInfo>,
/// Only these new records contribute; historical records are not replayed.
pub records: BTreeSet<Uuid>,
}
/// One aggregate result, distinct from an individual ruling's clamped outcome.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AggregateChange {
/// Entity receiving the contributions.
pub target: Uuid,
/// Primitive stat, never a derived summary.
pub stat: StatName,
/// Common epoch starting value.
pub before: isize,
/// Exact total of independently clamped contributions.
pub contribution: i128,
/// Aggregate normalized value.
pub after: isize,
}
/// Inputs for all independent rulings in the current epoch.
pub fn inputs(world: &EpochInfo) -> &EpochInfo {
match &world.epoch_resolution {
Some(state) if state.baseline.epoch_id == world.epoch_id => &state.baseline,
_ => world,
}
}
/// Preview a ruling against the common baseline with an epoch-scoped record ID.
pub fn preview(
world: &EpochInfo,
config: &AdjudicationConfig,
spec: &AdjudicationSpec,
target: Uuid,
tick_or_round: u64,
) -> Result<AdjudicationReport, AdjudicationError> {
validate(world)?;
let baseline = inputs(world);
let target = baseline.find_entity_strict(target, None).map_err(|_| {
invalid(format!("target @{target} is absent from the epoch baseline; commit before resolving newly created entities"))
})?;
let source_is_event = baseline
.find_entity_strict(spec.source, Some(EntityType::Event))
.is_ok();
if !source_is_event && !world.conflicts.contains_key(&spec.source) {
return Err(invalid(format!(
"source @{} is absent from the epoch baseline or conflicts",
spec.source
)));
}
let source_state = baseline.event_adjudications.get(&spec.source);
if source_is_event && source_state.is_some_and(|state| state.destroyed) {
return Err(invalid(format!(
"source @{} was destroyed before this epoch; restore or select another event",
spec.source
)));
}
// Effects are a keyed set; input vector order must not change record identity.
let mut spec = spec.clone();
spec.effects.sort_by_key(|effect| effect.stat);
let mut report = preview_at_potency(
config,
&spec,
target,
tick_or_round,
source_state.map_or(10_000, |state| state.potency_basis_points),
)?;
report.epoch_baseline = Some(world.epoch_id);
report.id = crate::adjudication::content_id(
&serde_json::to_vec(&(RULESET, world.epoch_id, report.id))
.map_err(|error| invalid(format!("cannot identify epoch ruling: {error}")))?,
);
Ok(report)
}
/// Apply a complete set of independent reports without mutating the input.
/// All reports must have been previewed against this epoch's common baseline.
pub fn apply(
world: &EpochInfo,
config: &AdjudicationConfig,
reports: &[(EntityType, AdjudicationReport)],
) -> Result<EpochInfo, AdjudicationError> {
config.validate()?;
validate(world)?;
if reports.is_empty() {
return Err(invalid("cannot apply an empty epoch resolution"));
}
if world
.adjudications
.len()
.checked_add(reports.len())
.is_none_or(|count| count > config.max_records)
{
return Err(AdjudicationError::RecordLimit {
limit: config.max_records,
});
}
let baseline = inputs(world);
let previous = aggregate(world)?;
let mut updated = world.clone();
if baseline.epoch_resolution.is_some() || world.epoch_resolution.is_none() {
let mut frozen = baseline.clone();
frozen.epoch_resolution = None;
canonicalize(&mut frozen);
updated.epoch_resolution = Some(Box::new(EpochResolution {
ruleset: RULESET.into(),
baseline: Box::new(frozen),
records: BTreeSet::new(),
}));
}
// When an active state exists, inputs() returned its nonrecursive baseline.
for (kind, report) in reports {
if updated.adjudications.contains_key(&report.id) {
return Err(AdjudicationError::Duplicate { record: report.id });
}
if report.epoch_baseline != Some(world.epoch_id) {
return Err(invalid(format!(
"record @{} belongs to another epoch; preview it again",
report.id
)));
}
if report.policy_id != config.policy_id {
return Err(invalid(format!(
"record @{} uses a different policy",
report.id
)));
}
let target = baseline.find_entity_strict(report.target, Some(*kind))?;
let current = world.find_entity_strict(report.target, Some(*kind))?;
for change in &report.changes {
let expected = previous
.iter()
.find(|entry| entry.target == report.target && entry.stat == change.stat)
.map_or(change.before, |entry| entry.after);
if **target.get_stats().get_field(&change.stat.list_stat()) != change.before {
return Err(AdjudicationError::Stale {
target: report.target,
});
}
if **current.get_stats().get_field(&change.stat.list_stat()) != expected {
return Err(invalid(format!(
"target @{} {:?} was edited since the epoch baseline; commit or restore the worktree before resolving this field",
report.target, change.stat
)));
}
}
updated.adjudications.insert(report.id, report.clone());
let state = updated
.epoch_resolution
.as_mut()
.ok_or_else(|| invalid("missing epoch baseline"))?;
state.records.insert(report.id);
}
for change in aggregate(&updated)? {
let entity = updated.find_entity_strict_as_mut(change.target, None)?;
entity.change_stat_strict(
StatPair {
stat: change.stat.list_stat(),
value: change.after.into(),
},
Modification::Replace,
);
entity.update_metastats();
}
reduce_sources(&mut updated)?;
canonicalize(&mut updated);
validate(&updated)?;
Ok(updated)
}
/// Compute the exact reduction, in canonical target/stat order.
pub fn aggregate(world: &EpochInfo) -> Result<Vec<AggregateChange>, AdjudicationError> {
let Some(state) = &world.epoch_resolution else {
return Ok(Vec::new());
};
if state.baseline.epoch_id != world.epoch_id {
return Ok(Vec::new());
}
aggregate_state(world, state)
}
/// Reduce the specified accumulator, including when auditing a closed epoch.
fn aggregate_state(
world: &EpochInfo,
state: &EpochResolution,
) -> Result<Vec<AggregateChange>, AdjudicationError> {
let mut totals = BTreeMap::<(Uuid, StatName), i128>::new();
for id in &state.records {
let report = world
.adjudications
.get(id)
.ok_or_else(|| invalid(format!("epoch resolution refers to missing record @{id}")))?;
let target = state.baseline.find_entity_strict(report.target, None)?;
for change in &report.changes {
if **target.get_stats().get_field(&change.stat.list_stat()) != change.before
|| normalize(
change.stat,
target.entity_type,
change.before as i128 + change.applied_delta as i128,
)? != change.after
{
return Err(invalid(format!(
"record @{id} does not match its epoch baseline or local clamp"
)));
}
let total = totals.entry((report.target, change.stat)).or_default();
*total = total
.checked_add(change.after as i128 - change.before as i128)
.ok_or_else(|| invalid("epoch contribution total exceeds i128"))?;
}
}
totals
.into_iter()
.map(|((target, stat), contribution)| {
let entity = state.baseline.find_entity_strict(target, None)?;
let before = **entity.get_stats().get_field(&stat.list_stat());
let raw = (before as i128)
.checked_add(contribution)
.ok_or_else(|| invalid("epoch total exceeds i128"))?;
Ok(AggregateChange {
target,
stat,
before,
contribution,
after: normalize(stat, entity.entity_type, raw)?,
})
})
.collect()
}
/// Clamp before narrowing; population has no gameplay upper bound.
pub(crate) fn normalize(
stat: StatName,
kind: EntityType,
value: i128,
) -> Result<isize, AdjudicationError> {
let minimum = if matches!(kind, EntityType::Event | EntityType::Blocker) {
-120
} else {
0
};
let value = match stat {
StatName::Population => value.max(minimum),
StatName::GrowthRate => value.clamp(-120, 120),
_ => value.clamp(minimum, 120),
};
isize::try_from(value).map_err(|_| {
invalid(format!(
"{stat:?} result {value} exceeds this platform's supported range"
))
})
}
/// Merge source state by minimum/OR rather than report arrival order.
fn source_totals(
world: &EpochInfo,
) -> Result<BTreeMap<Uuid, EventAdjudicationState>, AdjudicationError> {
let state = world
.epoch_resolution
.as_ref()
.ok_or_else(|| invalid("missing epoch baseline"))?;
let mut sources = BTreeMap::<Uuid, EventAdjudicationState>::new();
for id in &state.records {
let report = world
.adjudications
.get(id)
.ok_or_else(|| invalid(format!("missing record @{id}")))?;
if state
.baseline
.find_entity_strict(report.source, Some(EntityType::Event))
.is_err()
{
continue;
}
let original = state.baseline.event_adjudications.get(&report.source);
let source = sources
.entry(report.source)
.or_insert_with(|| EventAdjudicationState {
potency_basis_points: original.map_or(10_000, |entry| entry.potency_basis_points),
destroyed: original.is_some_and(|entry| entry.destroyed),
last_record: *id,
});
source.potency_basis_points = source.potency_basis_points.min(report.source_potency_after);
source.destroyed |= report.disposition == AdjudicationDisposition::Destroyed;
source.last_record = *id;
if source.destroyed {
source.potency_basis_points = 0;
}
}
Ok(sources)
}
/// Publish already reduced source states and stop their own frontiers.
fn reduce_sources(world: &mut EpochInfo) -> Result<(), AdjudicationError> {
for (id, source) in source_totals(world)? {
if source.destroyed
&& let Some(diffusion) = world.diffusions.get_mut(&id)
{
diffusion.expired = true;
}
world.event_adjudications.insert(id, source);
}
Ok(())
}
/// Check persisted accumulator structure and its audit references.
pub fn validate(world: &EpochInfo) -> Result<(), AdjudicationError> {
let active_records = world
.adjudications
.values()
.filter(|report| report.epoch_baseline == Some(world.epoch_id))
.map(|report| report.id)
.collect::<BTreeSet<_>>();
if world.adjudications.values().any(|report| {
report
.epoch_baseline
.is_some_and(|epoch| epoch > world.epoch_id)
}) {
return Err(invalid("adjudication refers to a future epoch baseline"));
}
let Some(state) = &world.epoch_resolution else {
if !active_records.is_empty() {
return Err(invalid("active epoch rulings have no baseline"));
}
return Ok(());
};
crate::adjudication::validate_adjudications(world)?;
if state.ruleset != RULESET
|| state.baseline.epoch_resolution.is_some()
|| state.baseline.epoch_id > world.epoch_id
|| state.records.is_empty()
{
return Err(invalid(
"invalid epoch resolution ruleset, baseline, or record membership",
));
}
let enrolled = world
.adjudications
.values()
.filter(|report| report.epoch_baseline == Some(state.baseline.epoch_id))
.map(|report| report.id)
.collect::<BTreeSet<_>>();
if state.records != enrolled
|| (!active_records.is_empty() && state.baseline.epoch_id != world.epoch_id)
{
return Err(invalid("epoch resolution record membership is incomplete"));
}
crate::adjudication::validate_adjudications(&state.baseline)?;
for id in &state.records {
if state.baseline.adjudications.contains_key(id) {
return Err(invalid(format!(
"record @{id} already belongs to the epoch baseline"
)));
}
let report = world
.adjudications
.get(id)
.ok_or_else(|| invalid(format!("missing epoch resolution record @{id}")))?;
let potency = state
.baseline
.event_adjudications
.get(&report.source)
.map_or(10_000, |entry| entry.potency_basis_points);
if state
.baseline
.find_entity_strict(report.source, Some(EntityType::Event))
.is_err()
&& !world.conflicts.contains_key(&report.source)
{
return Err(invalid(format!(
"source @{} is absent from the epoch baseline",
report.source
)));
}
if report.epoch_baseline != Some(state.baseline.epoch_id)
|| (report.disposition == AdjudicationDisposition::Destroyed
&& report.source_potency_after != 0)
|| report.source_potency_before != potency
|| !(0..=potency).contains(&report.source_potency_after)
{
return Err(invalid(format!(
"record @{id} has inconsistent epoch source potency"
)));
}
}
let changes = aggregate_state(world, state)?;
if state.baseline.epoch_id == world.epoch_id {
for (id, expected) in source_totals(world)? {
if world.event_adjudications.get(&id) != Some(&expected) {
return Err(invalid(format!(
"source @{id} differs from its epoch reduction"
)));
}
}
for change in changes {
let target = world.find_entity_strict(change.target, None)?;
if **target.get_stats().get_field(&change.stat.list_stat()) != change.after {
return Err(invalid(format!(
"target @{} {:?} differs from its epoch resolution; restore the worktree or commit before editing resolved statistics",
change.target, change.stat
)));
}
}
}
Ok(())
}
/// Stable collection order for frozen inputs and published worlds.
fn canonicalize(world: &mut EpochInfo) {
for kind in [
EntityType::Character,
EntityType::Town,
EntityType::Event,
EntityType::Calamity,
EntityType::Organization,
EntityType::Blocker,
] {
world
.vec_entities_mut(&kind)
.sort_by_key(|entity| entity.id);
}
}
/// Construct a domain validation error with caller-provided context.
fn invalid(message: impl Into<String>) -> AdjudicationError {
AdjudicationError::Invalid(message.into())
}

256
lib_efo/src/event_rng.rs Normal file
View File

@ -0,0 +1,256 @@
//! Versioned random-access event randomness, independent of worker scheduling.
//!
//! This is a simulation utility, not a source of adjudication rolls or secrets.
//! It does not change the existing sequential world-generation algorithm.
use rand::{RngCore, SeedableRng};
use rand_chacha::ChaCha12Rng;
use serde::Serialize;
use uuid::Uuid;
use crate::{epoch::EpochInfo, stats::EntityType};
/// Encoding, key derivation, generator, and bounded sampling contract.
pub const ALGORITHM: &str = "epoch-forge/event-rng-chacha12-fnv-v1";
/// Failures preparing or sampling an event-local random stream.
#[derive(Debug, thiserror::Error)]
pub enum EventRandomError {
/// The selected event is not in the frozen inputs.
#[error("cannot prepare event randomness: {0}")]
Event(#[from] crate::error::EpochError),
/// Inputs could not be converted to canonical JSON.
#[error("cannot encode event randomness inputs: {0}")]
Encoding(#[from] serde_json::Error),
/// An empty range has no sample.
#[error("event random upper bound must be greater than zero")]
EmptyRange,
/// The bounded deterministic rejection budget was exceeded.
#[error("event random sampling exceeded its rejection budget")]
RejectionLimit,
}
/// An immutable event key. Clone/share freely; draws never advance shared state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventRandom {
/// Domain-separated 256-bit seed derived from all declared event inputs.
key: [u8; 32],
}
impl EventRandom {
/// Prepare a key from explicit inputs. Definitions must use a caller-owned
/// canonical, versioned encoding; changing their bytes changes the stream.
pub fn new(
seed: u64,
epoch: u64,
event: Uuid,
occurrence: u64,
event_definition: &[u8],
rules_definition: &[u8],
) -> Self {
Self {
key: derive(&[
ALGORITHM.as_bytes(),
b"event",
&seed.to_le_bytes(),
&epoch.to_le_bytes(),
event.as_bytes(),
&occurrence.to_le_bytes(),
event_definition,
rules_definition,
]),
}
}
/// Use this epoch's frozen event and seed plus canonical JSON rule inputs.
/// Object keys sort recursively; array order remains semantically significant.
/// The occurrence must be stable input, never a queue/worker index.
pub fn for_event(
world: &EpochInfo,
event: Uuid,
occurrence: u64,
rules: &impl Serialize,
) -> Result<Self, EventRandomError> {
let baseline = crate::epoch_resolution::inputs(world);
let definition = baseline.find_entity_strict(event, Some(EntityType::Event))?;
Ok(Self::new(
baseline.rng_seed,
world.epoch_id.id,
event,
occurrence,
&canonical_json(definition)?,
&canonical_json(rules)?,
))
}
/// Return one independent u64 draw. `None` requests a shared event-wide draw;
/// `Some(target)` requests an independent target draw. Purpose labels and
/// draw indices are stable identities, not counts of previously consumed draws.
pub fn draw(&self, target: Option<Uuid>, purpose: &str, index: u64) -> u64 {
self.attempt(target, purpose, index, 0)
}
/// Uniform sample in `0..upper`, with a pinned rejection algorithm. Rejections
/// use a separate retry index and cannot shift any other named draw.
pub fn below(
&self,
target: Option<Uuid>,
purpose: &str,
index: u64,
upper: u64,
) -> Result<u64, EventRandomError> {
if upper == 0 {
return Err(EventRandomError::EmptyRange);
}
let threshold = upper.wrapping_neg() % upper;
for retry in 0..1024 {
let value = self.attempt(target, purpose, index, retry);
if value >= threshold {
return Ok(value % upper);
}
}
Err(EventRandomError::RejectionLimit)
}
/// Construct a local generator for exactly this draw/retry identity.
fn attempt(&self, target: Option<Uuid>, purpose: &str, index: u64, retry: u64) -> u64 {
let target_bytes = target.map_or_else(Vec::new, |id| id.as_bytes().to_vec());
let seed = derive(&[
ALGORITHM.as_bytes(),
b"draw",
&self.key,
&target_bytes,
purpose.as_bytes(),
&index.to_le_bytes(),
&retry.to_le_bytes(),
]);
ChaCha12Rng::from_seed(seed).next_u64()
}
}
/// Four independently domain-labelled FNV-1a-64 lanes, wrapping mod 2^64.
/// Each field has an unsigned u64 little-endian byte length prefix. Output lanes
/// use little endian. This fixed noncryptographic derivation is versioned above.
fn derive(fields: &[&[u8]]) -> [u8; 32] {
let mut key = [0; 32];
for lane in 0_u8..4 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for byte in [lane]
.iter()
.copied()
.chain(fields.iter().flat_map(|field| {
(field.len() as u64)
.to_le_bytes()
.into_iter()
.chain(field.iter().copied())
}))
{
hash = (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
}
let start = usize::from(lane) * 8;
key[start..start + 8].copy_from_slice(&hash.to_le_bytes());
}
key
}
/// Canonical JSON object ordering independent of struct/hash-map insertion order.
fn canonical_json(value: &impl Serialize) -> Result<Vec<u8>, serde_json::Error> {
/// Recursively sort object keys without reordering arrays.
fn ordered(value: serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Object(map) => {
let mut entries = map.into_iter().collect::<Vec<_>>();
entries.sort_by(|left, right| left.0.cmp(&right.0));
serde_json::Value::Object(
entries
.into_iter()
.map(|(key, value)| (key, ordered(value)))
.collect(),
)
}
serde_json::Value::Array(values) => {
serde_json::Value::Array(values.into_iter().map(ordered).collect())
}
other => other,
}
}
serde_json::to_vec(&ordered(serde_json::to_value(value)?))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encoding_and_generator_golden_vectors() {
let random = EventRandom::new(42, 7, Uuid::from_u128(3), 2, b"event-v1", b"rules-v1");
assert_eq!(
random.key,
[
59, 161, 175, 176, 219, 77, 18, 217, 100, 254, 201, 122, 52, 168, 156, 156, 133,
24, 87, 25, 184, 42, 90, 28, 118, 222, 184, 90, 0, 5, 189, 57
]
);
assert_eq!(random.draw(None, "weather", 0), 4_793_979_539_177_346_272);
assert_eq!(
random.draw(Some(Uuid::from_u128(9)), "damage", 4),
1_749_970_658_912_152_394
);
assert_eq!(random.below(None, "weather", 0, 6).expect("range"), 2);
assert_eq!(
random
.below(None, "weather", 0, (1_u64 << 63) + 1)
.expect("rejected first draw"),
5_838_915_579_167_874_243
);
}
#[test]
fn named_draws_do_not_depend_on_order_other_targets_or_retries() {
let random = EventRandom::new(42, 7, Uuid::from_u128(3), 2, b"event", b"rules");
let expected = (0..32)
.map(|index| random.draw(None, "weather", index))
.collect::<Vec<_>>();
for index in (0..32).rev() {
random.draw(Some(Uuid::from_u128(9)), "cosmetic", index);
random
.below(None, "other", index, (1_u64 << 63) + 1)
.expect("rejections");
assert_eq!(
random.draw(None, "weather", index),
expected[index as usize]
);
}
assert_ne!(
random.draw(None, "weather", 0),
random.draw(Some(Uuid::nil()), "weather", 0)
);
assert_ne!(
random.draw(None, "weather", 0),
random.draw(None, "damage", 0)
);
assert!(random.below(None, "weather", 0, 0).is_err());
assert_eq!(random.below(None, "weather", 0, 1).expect("singleton"), 0);
}
#[test]
fn field_boundaries_and_occurrence_identity_are_unambiguous() {
assert_ne!(derive(&[b"ab", b"c"]), derive(&[b"a", b"bc"]));
let base = EventRandom::new(1, 2, Uuid::from_u128(3), 4, b"event", b"rules");
for changed in [
EventRandom::new(2, 2, Uuid::from_u128(3), 4, b"event", b"rules"),
EventRandom::new(1, 3, Uuid::from_u128(3), 4, b"event", b"rules"),
EventRandom::new(1, 2, Uuid::from_u128(4), 4, b"event", b"rules"),
EventRandom::new(1, 2, Uuid::from_u128(3), 5, b"event", b"rules"),
EventRandom::new(1, 2, Uuid::from_u128(3), 4, b"event2", b"rules"),
EventRandom::new(1, 2, Uuid::from_u128(3), 4, b"event", b"rules2"),
] {
assert_ne!(base, changed);
}
let left = serde_json::json!({"b": {"y": 2, "x": 1}, "a": [2, 1]});
assert_eq!(
canonical_json(&left).expect("canonical"),
br#"{"a":[2,1],"b":{"x":1,"y":2}}"#
);
}
}

View File

@ -19,6 +19,8 @@ pub mod conflict;
pub mod diff; pub mod diff;
pub mod entity; pub mod entity;
pub mod epoch; pub mod epoch;
pub mod epoch_resolution;
pub mod event_rng;
pub mod naming; pub mod naming;
pub mod output; pub mod output;
pub mod repository_format; pub mod repository_format;

View File

@ -22,10 +22,10 @@ impl std::fmt::Display for FormatVersion {
} }
} }
/// The only repository format supported by this pre-release build. /// Latest writable repository format; older minors in this major remain readable.
pub const CURRENT_FORMAT_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 }; pub const CURRENT_FORMAT_VERSION: FormatVersion = FormatVersion { major: 1, minor: 1 };
/// The version-2 repository manifest. /// The versioned repository manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepositoryManifest { pub struct RepositoryManifest {
/// On-disk format discriminator. /// On-disk format discriminator.
@ -63,7 +63,7 @@ impl RepositoryManifest {
} }
} }
/// A complete version-2 index or worktree snapshot. /// A complete versioned index or worktree snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositorySnapshot { pub struct RepositorySnapshot {
/// Snapshot format discriminator. /// Snapshot format discriminator.

View File

@ -352,7 +352,10 @@ impl OverallStats {
// TODO: Force the use of this ? // TODO: Force the use of this ?
pub fn update(&mut self) { pub fn update(&mut self) {
self.demographics = self.demographics =
(*(self.population + self.growth_rate + self.happiness - self.crime) / 4).into(); (((*self.population as i128 + *self.growth_rate as i128 + *self.happiness as i128
- *self.crime as i128)
/ 4) as isize)
.into();
self.economy = (*(self.food + self.industry + self.trade + self.science) / 4).into(); self.economy = (*(self.food + self.industry + self.trade + self.science) / 4).into();
self.military = self.military =
(*(self.army + self.strength + self.fortification + self.threat) / 4).into(); (*(self.army + self.strength + self.fortification + self.threat) / 4).into();

View File

@ -1,4 +1,4 @@
//! Format-2 HEAD, index, and worktree access. //! Format-1.x HEAD, index, and worktree access.
use std::{ use std::{
collections::{BTreeMap, HashMap}, collections::{BTreeMap, HashMap},
@ -170,7 +170,11 @@ impl Workspace {
let index: RepositorySnapshot = decode(&index_path)?; let index: RepositorySnapshot = decode(&index_path)?;
let worktree: RepositorySnapshot = decode(&worktree_path)?; let worktree: RepositorySnapshot = decode(&worktree_path)?;
for (name, snapshot) in [("index", &index), ("worktree", &worktree)] { for (name, snapshot) in [("index", &index), ("worktree", &worktree)] {
if snapshot.format_version != crate::repository_format::CURRENT_FORMAT_VERSION { if snapshot.format_version.major
!= crate::repository_format::CURRENT_FORMAT_VERSION.major
|| snapshot.format_version.minor
> crate::repository_format::CURRENT_FORMAT_VERSION.minor
{
return Err(WorkspaceError::Inconsistent(format!( return Err(WorkspaceError::Inconsistent(format!(
"{name} has unsupported format {}", "{name} has unsupported format {}",
snapshot.format_version snapshot.format_version
@ -193,6 +197,15 @@ impl Workspace {
"HEAD snapshot ID does not match manifest".into(), "HEAD snapshot ID does not match manifest".into(),
)); ));
} }
if manifest.format_version.minor == 0
&& [&head, &index.world, &worktree.world]
.iter()
.any(|world| world.epoch_resolution.is_some())
{
return Err(WorkspaceError::Inconsistent(
"epoch resolution requires repository format 1.1".into(),
));
}
validate_world("HEAD", &head)?; validate_world("HEAD", &head)?;
validate_world("index", &index.world)?; validate_world("index", &index.world)?;
validate_world("worktree", &worktree.world)?; validate_world("worktree", &worktree.world)?;
@ -218,11 +231,13 @@ impl Workspace {
/// Copy the complete worktree into the index. /// Copy the complete worktree into the index.
pub fn stage_all(&mut self) -> Result<(), WorkspaceError> { pub fn stage_all(&mut self) -> Result<(), WorkspaceError> {
self.index.world = self.worktree.world.clone(); self.index.world = self.worktree.world.clone();
self.index.format_version = self.worktree.format_version;
self.save_index("stage --all") self.save_index("stage --all")
} }
/// Copy world-level metadata from worktree into index. /// Copy world-level metadata from worktree into index.
pub fn stage_world(&mut self) -> Result<(), WorkspaceError> { pub fn stage_world(&mut self) -> Result<(), WorkspaceError> {
require_complete_resolution(&self.worktree.world, &self.index.world, "stage --all")?;
copy_world_metadata(&self.worktree.world, &mut self.index.world); copy_world_metadata(&self.worktree.world, &mut self.index.world);
self.save_index("stage --world") self.save_index("stage --world")
} }
@ -233,6 +248,7 @@ impl Workspace {
kind: EntityType, kind: EntityType,
selectors: &[EntityIdentifier], selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> { ) -> Result<(), WorkspaceError> {
require_complete_resolution(&self.worktree.world, &self.index.world, "stage --all")?;
copy_entities(&self.worktree.world, &mut self.index.world, kind, selectors)?; copy_entities(&self.worktree.world, &mut self.index.world, kind, selectors)?;
self.save_index("stage entities") self.save_index("stage entities")
} }
@ -251,12 +267,18 @@ impl Workspace {
/// Restore staged world metadata from HEAD. /// Restore staged world metadata from HEAD.
pub fn restore_index_world(&mut self) -> Result<(), WorkspaceError> { pub fn restore_index_world(&mut self) -> Result<(), WorkspaceError> {
require_complete_resolution(&self.head, &self.index.world, "restore --staged --all")?;
copy_world_metadata(&self.head, &mut self.index.world); copy_world_metadata(&self.head, &mut self.index.world);
self.save_index("restore --staged --world") self.save_index("restore --staged --world")
} }
/// Restore worktree world metadata from index. /// Restore worktree world metadata from index.
pub fn restore_worktree_world(&mut self) -> Result<(), WorkspaceError> { pub fn restore_worktree_world(&mut self) -> Result<(), WorkspaceError> {
require_complete_resolution(
&self.index.world,
&self.worktree.world,
"restore --worktree --all",
)?;
copy_world_metadata(&self.index.world, &mut self.worktree.world); copy_world_metadata(&self.index.world, &mut self.worktree.world);
self.save_worktree("restore --worktree --world") self.save_worktree("restore --worktree --world")
} }
@ -267,6 +289,7 @@ impl Workspace {
kind: EntityType, kind: EntityType,
selectors: &[EntityIdentifier], selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> { ) -> Result<(), WorkspaceError> {
require_complete_resolution(&self.head, &self.index.world, "restore --staged --all")?;
copy_entities(&self.head, &mut self.index.world, kind, selectors)?; copy_entities(&self.head, &mut self.index.world, kind, selectors)?;
self.save_index("restore --staged") self.save_index("restore --staged")
} }
@ -277,15 +300,67 @@ impl Workspace {
kind: EntityType, kind: EntityType,
selectors: &[EntityIdentifier], selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> { ) -> Result<(), WorkspaceError> {
require_complete_resolution(
&self.index.world,
&self.worktree.world,
"restore --worktree --all",
)?;
copy_entities(&self.index.world, &mut self.worktree.world, kind, selectors)?; copy_entities(&self.index.world, &mut self.worktree.world, kind, selectors)?;
self.save_worktree("restore --worktree") self.save_worktree("restore --worktree")
} }
/// Persist a caller-modified worktree through the transaction layer. /// Persist a caller-modified worktree through the transaction layer.
pub fn save_worktree(&self, command: &str) -> Result<(), WorkspaceError> { pub fn save_worktree(&self, command: &str) -> Result<(), WorkspaceError> {
if self.worktree.world.epoch_resolution.is_some() && self.manifest.format_version.minor == 0
{
return Err(WorkspaceError::Inconsistent(
"epoch resolution requires format 1.1 publication".into(),
));
}
validate_world("worktree", &self.worktree.world)?;
save(&self.root, ".efo/worktree.json", &self.worktree, command) save(&self.root, ".efo/worktree.json", &self.worktree, command)
} }
/// Publish a complete resolution preview only if every repository input still
/// matches. Upgrade format protection in the same manifest-last transaction.
pub fn apply_resolution(&mut self, world: EpochInfo) -> Result<(), WorkspaceError> {
let lock = RepositoryLock::acquire(&self.root, "apply epoch resolution")?;
let mut current = Self::open(&self.root)?;
if encode(&self.manifest, "manifest")? != encode(&current.manifest, "manifest")?
|| encode(&self.index, "index")? != encode(&current.index, "index")?
|| encode(&self.worktree, "worktree")? != encode(&current.worktree, "worktree")?
{
return Err(WorkspaceError::Conflict(
"repository changed since resolution preview; rerun the resolution command".into(),
));
}
if world.epoch_id != current.worktree.world.epoch_id || world.epoch_resolution.is_none() {
return Err(WorkspaceError::Inconsistent(
"resolution must retain the epoch ID and include its baseline".into(),
));
}
validate_world("resolved worktree", &world)?;
current.worktree.world = world;
current.worktree.format_version = crate::repository_format::CURRENT_FORMAT_VERSION;
current.manifest.format_version = crate::repository_format::CURRENT_FORMAT_VERSION;
replace_files_locked(
&self.root,
&[
(
self.root.join(".efo/worktree.json"),
encode(&current.worktree, "worktree")?,
),
(
self.root.join(".epoch"),
encode(&current.manifest, "manifest")?,
),
],
&lock,
)?;
*self = current;
Ok(())
}
/// Apply one previewed entity change, rejecting stale editor snapshots under /// Apply one previewed entity change, rejecting stale editor snapshots under
/// the writer lock. `None` means creation/deletion; swapping arguments undoes /// the writer lock. `None` means creation/deletion; swapping arguments undoes
/// a change. HEAD and index are never written. In-memory state changes only /// a change. HEAD and index are never written. In-memory state changes only
@ -367,6 +442,7 @@ impl Workspace {
/// Persist a caller-modified index through the transaction layer. /// Persist a caller-modified index through the transaction layer.
pub fn save_index(&self, command: &str) -> Result<(), WorkspaceError> { pub fn save_index(&self, command: &str) -> Result<(), WorkspaceError> {
validate_world("index", &self.index.world)?;
save(&self.root, ".efo/index.json", &self.index, command) save(&self.root, ".efo/index.json", &self.index, command)
} }
@ -388,6 +464,7 @@ impl Workspace {
world.epoch_id = new_id; world.epoch_id = new_id;
world.commit_message = message; world.commit_message = message;
let mut manifest = self.manifest.clone(); let mut manifest = self.manifest.clone();
manifest.format_version = crate::repository_format::CURRENT_FORMAT_VERSION;
manifest.epoch_id = new_id; manifest.epoch_id = new_id;
for tag in world for tag in world
.tags .tags
@ -450,6 +527,7 @@ impl Workspace {
} }
let world = self.load_epoch(target)?; let world = self.load_epoch(target)?;
let mut manifest = self.manifest.clone(); let mut manifest = self.manifest.clone();
manifest.format_version = crate::repository_format::CURRENT_FORMAT_VERSION;
manifest.epoch_id = target; manifest.epoch_id = target;
let snapshot = RepositorySnapshot::new(manifest.repository_id, target, world.clone()); let snapshot = RepositorySnapshot::new(manifest.repository_id, target, world.clone());
let replacements = [ let replacements = [
@ -502,6 +580,7 @@ impl Workspace {
.filter(|id| *id > target) .filter(|id| *id > target)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut manifest = self.manifest.clone(); let mut manifest = self.manifest.clone();
manifest.format_version = crate::repository_format::CURRENT_FORMAT_VERSION;
manifest.epoch_id = target; manifest.epoch_id = target;
manifest.next_epoch_id = crate::epoch::EpochId::new(target.id + 1); manifest.next_epoch_id = crate::epoch::EpochId::new(target.id + 1);
manifest.tags.retain(|_, id| *id <= target); manifest.tags.retain(|_, id| *id <= target);
@ -645,6 +724,7 @@ impl Workspace {
fs::rename(&source, &destination).map_err(|source_error| io(&source, source_error))?; fs::rename(&source, &destination).map_err(|source_error| io(&source, source_error))?;
} }
let mut manifest = self.manifest.clone(); let mut manifest = self.manifest.clone();
manifest.format_version = crate::repository_format::CURRENT_FORMAT_VERSION;
manifest.next_epoch_id = crate::epoch::EpochId::new(manifest.epoch_id.id + 1); manifest.next_epoch_id = crate::epoch::EpochId::new(manifest.epoch_id.id + 1);
manifest.tags.retain(|_, id| !ids.contains(id)); manifest.tags.retain(|_, id| !ids.contains(id));
replace_files_locked( replace_files_locked(
@ -695,6 +775,7 @@ impl Workspace {
restored += 1; restored += 1;
} }
let mut manifest = self.manifest.clone(); let mut manifest = self.manifest.clone();
manifest.format_version = crate::repository_format::CURRENT_FORMAT_VERSION;
if let Some(metadata) = metadata { if let Some(metadata) = metadata {
manifest.next_epoch_id = manifest.next_epoch_id.max(metadata.next_epoch_id); manifest.next_epoch_id = manifest.next_epoch_id.max(metadata.next_epoch_id);
for (name, id) in metadata.removed_tags { for (name, id) in metadata.removed_tags {
@ -755,6 +836,16 @@ fn invert_world(
invert_metadata!(adjudications); invert_metadata!(adjudications);
invert_metadata!(event_adjudications); invert_metadata!(event_adjudications);
invert_metadata!(conflicts); invert_metadata!(conflicts);
let before_resolution = encode(&before.epoch_resolution, "epoch baseline")?;
let changed_resolution = encode(&changed.epoch_resolution, "epoch baseline")?;
let current_resolution = encode(&current.epoch_resolution, "epoch baseline")?;
if before_resolution != changed_resolution {
if current_resolution == changed_resolution {
current.epoch_resolution = before.epoch_resolution.clone();
} else if current_resolution != before_resolution {
return Err(WorkspaceError::Conflict("epoch resolution".into()));
}
}
Ok(()) Ok(())
} }
@ -831,6 +922,22 @@ fn copy_entities(
Ok(()) Ok(())
} }
/// Prevent separating a baseline/audit update from its entity contributions.
fn require_complete_resolution(
source: &EpochInfo,
destination: &EpochInfo,
command: &str,
) -> Result<(), WorkspaceError> {
if encode(&source.epoch_resolution, "epoch resolution")?
!= encode(&destination.epoch_resolution, "epoch resolution")?
{
return Err(WorkspaceError::Inconsistent(format!(
"epoch resolution contains coupled statistics and audit records; use `efo {command}`"
)));
}
Ok(())
}
/// Copy mutable metadata not owned by an entity collection. /// Copy mutable metadata not owned by an entity collection.
fn copy_world_metadata(source: &EpochInfo, destination: &mut EpochInfo) { fn copy_world_metadata(source: &EpochInfo, destination: &mut EpochInfo) {
destination.rng_seed = source.rng_seed; destination.rng_seed = source.rng_seed;
@ -839,6 +946,7 @@ fn copy_world_metadata(source: &EpochInfo, destination: &mut EpochInfo) {
destination.adjudications = source.adjudications.clone(); destination.adjudications = source.adjudications.clone();
destination.event_adjudications = source.event_adjudications.clone(); destination.event_adjudications = source.event_adjudications.clone();
destination.conflicts = source.conflicts.clone(); destination.conflicts = source.conflicts.clone();
destination.epoch_resolution = source.epoch_resolution.clone();
} }
/// Validate stable identity, collection type, and relationship targets. /// Validate stable identity, collection type, and relationship targets.
@ -851,6 +959,11 @@ fn validate_world(label: &str, world: &EpochInfo) -> Result<(), WorkspaceError>
.map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?; .map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?;
validate_conflicts(world) validate_conflicts(world)
.map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?; .map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?;
crate::epoch_resolution::validate(world)
.map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?;
if let Some(state) = &world.epoch_resolution {
validate_world("epoch resolution baseline", &state.baseline)?;
}
let index = EntityIndex::build(world); let index = EntityIndex::build(world);
if !index.duplicate_ids().is_empty() { if !index.duplicate_ids().is_empty() {
return Err(WorkspaceError::Inconsistent(format!( return Err(WorkspaceError::Inconsistent(format!(

View File

@ -0,0 +1,506 @@
use lib_efo::{
adjudication::{
AdjudicationConfig, AdjudicationDisposition as Disposition, AdjudicationLevel as Level,
AdjudicationSpec, ChosenEffect, StatName,
},
entity::Entity,
epoch::{EpochId, EpochInfo},
epoch_resolution::{self as resolution, apply, preview},
stats::{EntityType, ListStats, Modification, StatPair},
};
use uuid::Uuid;
fn world(health: isize) -> EpochInfo {
let mut world = EpochInfo::default();
for id in [1, 2] {
let mut event = Entity::default();
event.id = Uuid::from_u128(id);
event.name = format!("event {id}");
event.entity_type = EntityType::Event;
world.events.push(event);
}
let mut target = Entity::default();
target.id = Uuid::from_u128(3);
target.name = "town".into();
target.entity_type = EntityType::Town;
target.change_stat_strict(
StatPair {
stat: ListStats::Health,
value: health.into(),
},
Modification::Replace,
);
target.update_metastats();
world.towns.push(target);
world
}
fn spec(source: u128, delta: isize) -> AdjudicationSpec {
AdjudicationSpec {
level: Level::Apocalypse,
disposition: Disposition::Applied,
source: Uuid::from_u128(source),
external_result: "GM ruling".into(),
note: String::new(),
effects: vec![ChosenEffect {
stat: StatName::Health,
delta,
}],
policy_id: AdjudicationConfig::embedded().expect("config").policy_id,
}
}
fn health(world: &EpochInfo) -> isize {
**world.towns[0].get_stats().get_field(&ListStats::Health)
}
#[test]
fn independent_clamps_are_order_independent_in_batches_and_separate_invocations() {
let config = AdjudicationConfig::embedded().expect("config");
for (base, plus, minus, expected) in [
(110, 20, -20, 100),
(5, 10, -10, 10),
(100, 10, 10, 120),
(100, 100, 100, 120),
] {
let initial = world(base);
let a = preview(&initial, &config, &spec(1, plus), Uuid::from_u128(3), 0).expect("a");
let b = preview(&initial, &config, &spec(2, minus), Uuid::from_u128(3), 0).expect("b");
let first = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("first");
// Simulate another process opening persisted state before previewing b.
let first: EpochInfo =
serde_json::from_slice(&serde_json::to_vec(&first).expect("encode")).expect("decode");
assert_eq!(
preview(&first, &config, &spec(2, minus), Uuid::from_u128(3), 0)
.expect("same baseline"),
b
);
let ab = apply(&first, &config, &[(EntityType::Town, b.clone())]).expect("second");
let ba = apply(
&initial,
&config,
&[(EntityType::Town, b), (EntityType::Town, a)],
)
.expect("reversed batch");
assert_eq!(health(&ab), expected);
assert_eq!(
serde_json::to_value(&ab).expect("ab"),
serde_json::to_value(&ba).expect("ba")
);
}
}
#[test]
fn next_epoch_compounds_and_identical_ruling_has_new_identity() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("a");
let mut next = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("apply");
next.epoch_id = EpochId::new(1);
let b = preview(&next, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("next");
assert_ne!(a.id, b.id);
assert_eq!(b.changes[0].before, 90);
let next = apply(&next, &config, &[(EntityType::Town, b)]).expect("compound");
assert_eq!(health(&next), 80);
assert!(
next.epoch_resolution
.as_ref()
.expect("state")
.baseline
.epoch_resolution
.is_none()
);
}
#[test]
fn duplicate_and_stale_reports_are_atomic_and_do_not_overwrite_edits() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("a");
assert!(
apply(
&initial,
&config,
&[(EntityType::Town, a.clone()), (EntityType::Town, a.clone())]
)
.is_err()
);
assert_eq!(health(&initial), 100);
let mut updated = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("apply");
assert!(apply(&updated, &config, &[(EntityType::Town, a)]).is_err());
updated.towns[0].change_stat_strict(
StatPair {
stat: ListStats::Health,
value: 40.into(),
},
Modification::Replace,
);
assert!(preview(&updated, &config, &spec(2, -10), Uuid::from_u128(3), 0).is_err());
assert_eq!(health(&updated), 40);
}
#[test]
fn source_state_reduces_by_minimum_and_destruction_dominates() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let mut destroy = spec(1, -10);
destroy.disposition = Disposition::Destroyed;
let a = preview(&initial, &config, &destroy, Uuid::from_u128(3), 0).expect("destroy");
let mut defaults = spec(1, 0);
defaults.effects.clear();
defaults.level = Level::Bad;
let b = preview(&initial, &config, &defaults, Uuid::from_u128(3), 1).expect("defaults");
let first = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("destroy first");
assert_eq!(
preview(&first, &config, &defaults, Uuid::from_u128(3), 1).expect("same-epoch default"),
b
);
let ab = apply(&first, &config, &[(EntityType::Town, b.clone())]).expect("default next");
let ba = apply(
&initial,
&config,
&[(EntityType::Town, b), (EntityType::Town, a)],
)
.expect("batch");
assert_eq!(
serde_json::to_value(&ab).expect("ab"),
serde_json::to_value(&ba).expect("ba")
);
assert_eq!(health(&ab), 85);
assert_eq!(
ab.event_adjudications[&Uuid::from_u128(1)].potency_basis_points,
0
);
assert!(ab.event_adjudications[&Uuid::from_u128(1)].destroyed);
let mut next = ab;
next.epoch_id = EpochId::new(1);
assert!(preview(&next, &config, &defaults, Uuid::from_u128(3), 1).is_err());
}
#[test]
fn legacy_fixture_and_corrupt_state_are_handled_explicitly() {
let legacy: EpochInfo =
serde_json::from_str(include_str!("fixtures/epoch-resolution/legacy.json"))
.expect("old epoch");
assert!(legacy.epoch_resolution.is_none());
resolution::validate(&legacy).expect("legacy validation");
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("a");
let updated = apply(&initial, &config, &[(EntityType::Town, a)]).expect("apply");
let mut bad = updated.clone();
bad.epoch_resolution.as_mut().expect("state").ruleset = "future".into();
assert!(resolution::validate(&bad).is_err());
let mut bad = updated.clone();
bad.adjudications.clear();
assert!(resolution::validate(&bad).is_err());
let mut bad = updated.clone();
bad.epoch_resolution
.as_mut()
.expect("state")
.baseline
.epoch_resolution = updated.epoch_resolution;
assert!(resolution::validate(&bad).is_err());
}
#[test]
fn extreme_deltas_clamp_without_intermediate_overflow() {
let initial = world(100);
let config = AdjudicationConfig::embedded().expect("config");
let a = preview(
&initial,
&config,
&spec(1, isize::MAX),
Uuid::from_u128(3),
0,
)
.expect("positive");
let b = preview(
&initial,
&config,
&spec(2, isize::MIN),
Uuid::from_u128(3),
0,
)
.expect("negative");
assert_eq!(a.changes[0].applied_delta, isize::MAX);
assert_eq!(b.changes[0].applied_delta, isize::MIN);
let updated = apply(
&initial,
&config,
&[(EntityType::Town, a), (EntityType::Town, b)],
)
.expect("exact sum");
assert_eq!(health(&updated), 20);
}
#[test]
fn repository_publication_upgrades_legacy_format_and_rejects_stale_snapshots() {
use lib_efo::workspace::Workspace;
let dir = tempfile::tempdir().expect("dir");
let mut workspace = Workspace::initialize(dir.path(), "test").expect("init");
workspace.worktree.world = world(110);
workspace.save_worktree("setup").expect("setup");
workspace.stage_all().expect("stage");
workspace.commit("initial".into()).expect("commit");
// Compatibility fixture: all pre-existing state layers use 1.0 and no baseline.
for path in [".epoch", ".efo/index.json", ".efo/worktree.json"] {
let path = dir.path().join(path);
let mut value: serde_json::Value =
serde_json::from_slice(&std::fs::read(&path).expect("read")).expect("json");
value["format_version"]["minor"] = 0.into();
std::fs::write(path, serde_json::to_vec(&value).expect("encode")).expect("write fixture");
}
let mut workspace = Workspace::open(dir.path()).expect("legacy reader");
let mut stale = workspace.clone();
let config = AdjudicationConfig::embedded().expect("config");
let a = preview(
&workspace.worktree.world,
&config,
&spec(1, 20),
Uuid::from_u128(3),
0,
)
.expect("a");
let projected =
apply(&workspace.worktree.world, &config, &[(EntityType::Town, a)]).expect("project");
workspace
.apply_resolution(projected.clone())
.expect("publish");
assert_eq!(workspace.manifest.format_version.minor, 1);
assert_eq!(workspace.worktree.format_version.minor, 1);
let bytes = std::fs::read(dir.path().join(".efo/worktree.json")).expect("bytes");
assert!(stale.apply_resolution(projected).is_err());
assert_eq!(
std::fs::read(dir.path().join(".efo/worktree.json")).expect("bytes"),
bytes
);
// A reload recovers the baseline, and partial staging cannot orphan its audit.
let mut workspace = Workspace::open(dir.path()).expect("reload");
assert!(workspace.stage_world().is_err());
workspace.stage_all().expect("stage complete");
workspace.commit("resolution".into()).expect("commit");
let next = preview(
&workspace.worktree.world,
&config,
&spec(2, -20),
Uuid::from_u128(3),
0,
)
.expect("next epoch");
assert_eq!(next.changes[0].before, 120);
workspace
.check_epoch(workspace.head.epoch_id)
.expect("historical validation");
workspace
.revert_to_worktree(workspace.head.epoch_id)
.expect("revert complete resolution");
assert_eq!(
health(
&Workspace::open(dir.path())
.expect("reverted")
.worktree
.world
),
110
);
}
#[test]
fn writer_lock_and_interrupted_transaction_leave_resolution_unpublished() {
use lib_efo::{transaction::RepositoryLock, workspace::Workspace};
let dir = tempfile::tempdir().expect("dir");
let mut workspace = Workspace::initialize(dir.path(), "test").expect("init");
workspace.worktree.world = world(100);
workspace.save_worktree("setup").expect("save");
let config = AdjudicationConfig::embedded().expect("config");
let a = preview(
&workspace.worktree.world,
&config,
&spec(1, -10),
Uuid::from_u128(3),
0,
)
.expect("a");
let projected =
apply(&workspace.worktree.world, &config, &[(EntityType::Town, a)]).expect("project");
let before = std::fs::read(dir.path().join(".efo/worktree.json")).expect("before");
let lock = RepositoryLock::acquire(dir.path(), "other writer").expect("lock");
assert!(workspace.apply_resolution(projected.clone()).is_err());
drop(lock);
std::fs::write(dir.path().join(".efo/transaction.json"), "{}").expect("journal");
assert!(workspace.apply_resolution(projected).is_err());
assert_eq!(
std::fs::read(dir.path().join(".efo/worktree.json")).expect("after"),
before
);
assert_eq!(health(&workspace.worktree.world), 100);
}
#[test]
fn stale_epoch_identity_and_population_overflow_are_rejected() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let report = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("report");
let mut next = initial.clone();
next.epoch_id = EpochId::new(1);
assert!(apply(&next, &config, &[(EntityType::Town, report)]).is_err());
let mut initial = initial;
initial.towns[0].change_stat_strict(
StatPair {
stat: ListStats::Population,
value: isize::MAX.into(),
},
Modification::Replace,
);
initial.towns[0].update_metastats();
let mut population = spec(1, 1);
population.effects[0].stat = StatName::Population;
assert!(preview(&initial, &config, &population, Uuid::from_u128(3), 0).is_err());
}
#[test]
fn event_rng_reads_frozen_inputs_and_compounds_its_identity_only_next_epoch() {
use lib_efo::event_rng::EventRandom;
let mut initial = world(100);
initial.rng_seed = 42;
let config = AdjudicationConfig::embedded().expect("config");
let original = EventRandom::for_event(&initial, Uuid::from_u128(1), 0, &config).expect("rng");
let mut unrelated = initial.clone();
let mut town = unrelated.towns[0].clone();
town.id = Uuid::from_u128(9);
unrelated.towns.push(town);
assert_eq!(
EventRandom::for_event(&unrelated, Uuid::from_u128(1), 0, &config).expect("rng"),
original
);
let ruling =
preview(&initial, &config, &spec(2, 30), Uuid::from_u128(1), 0).expect("event as target");
let mut updated = apply(&initial, &config, &[(EntityType::Event, ruling)]).expect("apply");
updated.rng_seed = 77; // A metadata edit must not alter already-frozen draws.
assert_eq!(
EventRandom::for_event(&updated, Uuid::from_u128(1), 0, &config).expect("frozen rng"),
original
);
updated.epoch_id = EpochId::new(1);
assert_ne!(
EventRandom::for_event(&updated, Uuid::from_u128(1), 0, &config).expect("next rng"),
original
);
}
#[test]
fn three_way_reduction_never_clamps_partial_sums() {
let initial = world(100);
let config = AdjudicationConfig::embedded().expect("config");
let reports = [100, -200, 10]
.into_iter()
.enumerate()
.map(|(occurrence, delta)| {
(
EntityType::Town,
preview(
&initial,
&config,
&spec(1, delta),
Uuid::from_u128(3),
occurrence as u64,
)
.expect("report"),
)
})
.collect::<Vec<_>>();
let expected = apply(&initial, &config, &reports).expect("batch");
assert_eq!(health(&expected), 30);
for order in [
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
] {
let mut updated = initial.clone();
for index in order {
updated = apply(&updated, &config, &[reports[index].clone()]).expect("incremental");
}
assert_eq!(
serde_json::to_value(updated).expect("updated"),
serde_json::to_value(&expected).expect("expected")
);
}
}
#[test]
fn legacy_rulings_are_baseline_history_and_never_reenrolled() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let old = lib_efo::adjudication::preview(&config, &spec(1, -10), &initial.towns[0], 0)
.expect("legacy report");
let old_world =
lib_efo::adjudication::apply_to_world(&initial, &config, &old, EntityType::Town)
.expect("legacy apply");
let old_bytes = serde_json::to_vec(&old_world).expect("legacy representation");
let old_world: EpochInfo = serde_json::from_slice(&old_bytes).expect("read legacy record");
let next =
preview(&old_world, &config, &spec(2, -10), Uuid::from_u128(3), 0).expect("new ruling");
let next_id = next.id;
let updated = apply(&old_world, &config, &[(EntityType::Town, next)]).expect("apply");
assert_eq!(health(&updated), 80);
assert_eq!(updated.adjudications[&old.id], old);
assert_eq!(
updated.epoch_resolution.as_ref().expect("state").records,
[next_id].into_iter().collect()
);
let mut corrupt = updated.clone();
corrupt.epoch_resolution = None;
assert!(resolution::validate(&corrupt).is_err());
let mut corrupt = updated.clone();
corrupt
.event_adjudications
.get_mut(&Uuid::from_u128(2))
.expect("source")
.potency_basis_points = 1;
assert!(resolution::validate(&corrupt).is_err());
let mut corrupt = updated;
corrupt
.epoch_resolution
.as_mut()
.expect("state")
.records
.clear();
assert!(resolution::validate(&corrupt).is_err());
}
#[test]
fn record_limits_and_population_aggregate_overflow_leave_inputs_untouched() {
let mut config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, 5), Uuid::from_u128(3), 0).expect("a");
let b = preview(&initial, &config, &spec(2, 5), Uuid::from_u128(3), 0).expect("b");
config.max_records = 1;
assert!(
apply(
&initial,
&config,
&[(EntityType::Town, a), (EntityType::Town, b)]
)
.is_err()
);
assert_eq!(health(&initial), 100);
config.max_records = 10;
let reports = [1, 2]
.into_iter()
.map(|source| {
let mut ruling = spec(source, isize::MAX);
ruling.effects[0].stat = StatName::Population;
(
EntityType::Town,
preview(&initial, &config, &ruling, Uuid::from_u128(3), 0)
.expect("local population"),
)
})
.collect::<Vec<_>>();
assert!(apply(&initial, &config, &reports).is_err());
assert!(initial.epoch_resolution.is_none());
}

View File

@ -0,0 +1 @@
{"epoch_id":{"id":0},"rng_seed":0,"tags":{"inner":[]},"summary":"legacy epoch without resolution state","events":[],"characters":[],"towns":[],"calamities":[],"blockers":[]}

270
scripts/ci-coverage-badges.sh Executable file
View File

@ -0,0 +1,270 @@
#!/bin/sh
set -eu
usage() {
cat >&2 <<'EOF'
usage: $0 <version|test|coverage> [options]
Render one deterministic SVG badge. Defaults:
version --text version --value unknown --color #007ec6
test --text tests --value passing --color #4c1
coverage --text coverage --value - --color #9f9f9f --suffix %
Options:
--text TEXT left-hand label
--value VALUE right-hand value
--color COLOR value background (#RGB or #RRGGBB)
--size PX font size, from 6 through 24 (default: 11)
--height PX badge height, from 14 through 64 (default: 20)
--label-width PX fixed label width instead of automatic sizing
--value-width PX fixed value width instead of automatic sizing
--suffix TEXT text appended to the displayed value
--output PATH output file (default: coverage/<kind>.svg)
-h, --help show this help
Examples:
./ci-coverage-badges.sh version --value 1.2.3
./ci-coverage-badges.sh test --value failing
./ci-coverage-badges.sh coverage --value 87.4
./ci-coverage-badges.sh version --text release --value rc.12 --size 12 --color '#8a2be2'
EOF
exit "${1:-2}"
}
[ "$#" -ge 1 ] || usage
kind=$1
shift
case "$kind" in
version)
text=version
value=unknown
color='#007ec6'
suffix=
output=coverage/version.svg
;;
test)
text=tests
value=passing
color=
suffix=
output=coverage/test.svg
;;
coverage)
text=coverage
value=-
color=
suffix=%
output=coverage/coverage.svg
;;
-h|--help) usage 0 ;;
*)
echo "unsupported badge kind: $kind" >&2
usage
;;
esac
font_size=11
height=20
label_width=
value_width=
color_set=false
while [ "$#" -gt 0 ]; do
option=$1
case "$option" in
--text|--value|--color|--size|--height|--label-width|--value-width|--suffix|--output)
[ "$#" -ge 2 ] || {
echo "missing value for $option" >&2
exit 2
}
option_value=$2
shift 2
case "$option" in
--text) text=$option_value ;;
--value) value=$option_value ;;
--color) color=$option_value; color_set=true ;;
--size) font_size=$option_value ;;
--height) height=$option_value ;;
--label-width) label_width=$option_value ;;
--value-width) value_width=$option_value ;;
--suffix) suffix=$option_value ;;
--output) output=$option_value ;;
esac
;;
-h|--help) usage 0 ;;
*)
echo "unknown option: $option" >&2
usage
;;
esac
done
validate_text() {
field_name=$1
field_value=$2
if ! printf '%sX\n' "$field_value" | LC_ALL=C awk '
BEGIN { valid = 1 }
NR != 1 || $0 !~ /^[ -~]+X$/ || length($0) <= 1 { valid = 0 }
END { exit(valid == 0 ? 1 : 0) }
'; then
echo "$field_name must contain printable ASCII characters: $field_value" >&2
exit 2
fi
}
validate_integer() {
field_name=$1
field_value=$2
minimum=$3
maximum=$4
case "$field_value" in
''|*[!0-9]*)
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
;;
esac
if [ "$field_value" -lt "$minimum" ] || [ "$field_value" -gt "$maximum" ]; then
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
fi
}
validate_text text "$text"
validate_text value "$value"
if [ -n "$suffix" ]; then
validate_text suffix "$suffix"
fi
validate_integer size "$font_size" 6 24
validate_integer height "$height" 14 64
if [ -n "$label_width" ]; then
validate_integer label-width "$label_width" 20 1000
fi
if [ -n "$value_width" ]; then
validate_integer value-width "$value_width" 20 1000
fi
case "$output" in
''|*/) echo "output must name an SVG file: $output" >&2; exit 2 ;;
esac
case "$kind" in
test)
if [ "$color_set" = false ]; then
case "$value" in
passing) color='#4c1' ;;
failing) color='#e05d44' ;;
*) color='#9f9f9f' ;;
esac
fi
;;
coverage)
if [ "$value" = '-' ]; then
[ "$color_set" = true ] || color='#9f9f9f'
else
if ! awk -v candidate="$value" 'BEGIN {
valid = candidate ~ /^[0-9]+([.][0-9]+)?$/ && candidate >= 0 && candidate <= 100
exit(valid ? 0 : 1)
}'; then
echo "coverage value must be - or a number from 0 through 100: $value" >&2
exit 2
fi
value=$(awk -v candidate="$value" 'BEGIN { printf "%.0f", candidate }')
if [ "$color_set" = false ]; then
if [ "$value" -ge 90 ]; then
color='#4c1'
elif [ "$value" -ge 70 ]; then
color='#dfb317'
else
color='#e05d44'
fi
fi
fi
;;
esac
case "$color" in
\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]|\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]) ;;
*) echo "color must be #RGB or #RRGGBB: $color" >&2; exit 2 ;;
esac
display_value=$value$suffix
if [ -z "$label_width" ]; then
label_width=$(printf '%s\\n' "$text" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
if [ -z "$value_width" ]; then
value_width=$(printf '%s\\n' "$display_value" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
badge_width=$((label_width + value_width))
label_center=$(awk -v width="$label_width" 'BEGIN { printf "%.1f", width / 2 }')
value_center=$(awk -v left="$label_width" -v width="$value_width" 'BEGIN {
printf "%.1f", left + width / 2
}')
vertical_center=$(awk -v badge_height="$height" 'BEGIN { printf "%.1f", badge_height / 2 }')
xml_escape() {
sed \
-e 's/&/\&amp;/g' \
-e 's/</\&lt;/g' \
-e 's/>/\&gt;/g' \
-e 's/"/\&quot;/g'
}
sed_replacement_escape() {
sed -e 's/[\\&|]/\\&/g'
}
escaped_text=$(printf '%s' "$text" | xml_escape | sed_replacement_escape)
escaped_value=$(printf '%s' "$display_value" | xml_escape | sed_replacement_escape)
escaped_title=$(printf '%s: %s' "$text" "$display_value" | xml_escape | sed_replacement_escape)
output_dir=${output%/*}
if [ "$output_dir" != "$output" ]; then
mkdir -p "$output_dir"
fi
temporary="${output}.tmp.$$"
trap 'rm -f "$temporary"' EXIT HUP INT TERM
sed \
-e "s/@BADGE_WIDTH@/$badge_width/g" \
-e "s/@HEIGHT@/$height/g" \
-e "s/@LABEL_WIDTH@/$label_width/g" \
-e "s/@VALUE_WIDTH@/$value_width/g" \
-e "s/@LABEL_CENTER@/$label_center/g" \
-e "s/@VALUE_CENTER@/$value_center/g" \
-e "s/@VERTICAL_CENTER@/$vertical_center/g" \
-e "s/@FONT_SIZE@/$font_size/g" \
-e "s/@COLOR@/$color/g" \
-e "s|@TITLE@|$escaped_title|g" \
-e "s|@TEXT@|$escaped_text|g" \
-e "s|@VALUE@|$escaped_value|g" \
>"$temporary" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" width="@BADGE_WIDTH@" height="@HEIGHT@" role="img" aria-label="@TITLE@">
<title>@TITLE@</title>
<linearGradient id="s" 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-opacity=".3"/>
<stop offset="1" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r"><rect width="@BADGE_WIDTH@" height="@HEIGHT@" rx="3"/></clipPath>
<g clip-path="url(#r)">
<rect width="@LABEL_WIDTH@" height="@HEIGHT@" fill="#555"/>
<rect x="@LABEL_WIDTH@" width="@VALUE_WIDTH@" height="@HEIGHT@" fill="@COLOR@"/>
<rect width="@BADGE_WIDTH@" height="@HEIGHT@" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" dominant-baseline="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="@FONT_SIZE@">
<text x="@LABEL_CENTER@" y="@VERTICAL_CENTER@">@TEXT@</text>
<text x="@VALUE_CENTER@" y="@VERTICAL_CENTER@">@VALUE@</text>
</g>
</svg>
EOF
mv "$temporary" "$output"
trap - EXIT HUP INT TERM

View File

@ -0,0 +1,103 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 ROOT OWNER PROJECT DEFAULT_BRANCH BADGE..." >&2
exit 2
}
[ "$#" -ge 5 ] || usage
root=$1
owner=$2
project=$3
default_branch=$4
shift 4
case "$root" in
/*) ;;
*) echo "publication root must be absolute: $root" >&2; exit 2 ;;
esac
[ -d "$root" ] || { echo "publication root is not a directory: $root" >&2; exit 2; }
[ -w "$root" ] || { echo "publication root is not writable: $root" >&2; exit 2; }
validate_component() {
component_name=$1
component_value=$2
case "$component_value" in
''|.|..|*[!A-Za-z0-9._-]*)
echo "$component_name is not a safe path component: $component_value" >&2
exit 2
;;
esac
}
validate_component owner "$owner"
validate_component project "$project"
validate_component default-branch "$default_branch"
badges=
for name in "$@"; do
case "$name" in
coverage|test|version) ;;
*) echo "unsupported badge name: $name" >&2; exit 2 ;;
esac
case " $badges " in
*" $name "*) echo "duplicate badge name: $name" >&2; exit 2 ;;
esac
source_file="coverage/$name.svg"
if [ -L "$source_file" ] || [ ! -f "$source_file" ] || [ ! -s "$source_file" ]; then
echo "badge source must be a regular, nonempty, non-symlink file: $source_file" >&2
exit 2
fi
badges="$badges $name"
done
ensure_directory() {
directory=$1
description=$2
if [ -L "$directory" ]; then
echo "$description must not be a symlink: $directory" >&2
exit 2
fi
if [ -e "$directory" ] && [ ! -d "$directory" ]; then
echo "$description is not a directory: $directory" >&2
exit 2
fi
if [ ! -d "$directory" ]; then
mkdir "$directory"
fi
chmod 0755 "$directory"
}
owner_dir="$root/$owner"
ensure_directory "$owner_dir" "owner path"
project_dir="$owner_dir/$project"
ensure_directory "$project_dir" "project path"
destination="$project_dir/$default_branch"
if [ -L "$destination" ]; then
rm -f "$destination"
elif [ -e "$destination" ] && [ ! -d "$destination" ]; then
echo "default-branch path is not a directory: $destination" >&2
exit 2
fi
ensure_directory "$destination" "default-branch path"
temporary=
cleanup() {
if [ -n "$temporary" ]; then
rm -f "$temporary"
fi
}
trap cleanup EXIT HUP INT TERM
for name in $badges; do
source_file="coverage/$name.svg"
temporary="$destination/.$name.svg.tmp.$$"
cp "$source_file" "$temporary"
chmod 0644 "$temporary"
mv "$temporary" "$destination/$name.svg"
temporary=
done
trap - EXIT HUP INT TERM

View File

@ -1,12 +1,10 @@
[coverage] [coverage]
workspace = true workspace = true
all-features = true all-features = true
exclude-files = ["bin_efo/src/*"] fail-under = 65
[report] [report]
out = ["Html"] out = ["Json"]
# CLI behavior is exercised through subprocess integration tests. Tarpaulin's # Keep all production code in the measured surface. CLI subprocess tests are
# ptrace backend cannot attribute those child executions reliably (and its # still valuable even though Tarpaulin cannot attribute their child execution.
# follow-exec mode currently segfaults), so measure the directly instrumented
# library and TUI code rather than reporting every CLI adapter as uncovered.