Compare commits

...
Author SHA1 Message Date
faumaray e5464784f5 Record verified migration of thirteen historical colony states 2026-12-02 23:37:52 +03:00
faumaray e348a4291d Cross-check active work, retired receipts and storage claims 2026-12-02 23:34:58 +03:00
faumaray d613b73e1f Check source and capacity claims in authentic gathering and canceled work 2026-12-02 23:34:58 +03:00
faumaray 120db6cfa0 Canonicalize custody outcomes and enforce operation-specific work phases 2026-12-02 23:34:58 +03:00
faumaray 67fba6e3df Reject impossible terminal and travel states in authenticated checkpoints 2026-12-02 23:30:23 +03:00
faumaray 7d5fbeb349 Exercise receipt uniqueness on a real split-input carpenter job 2026-12-02 23:26:10 +03:00
faumaray 4f4c038051 Keep generic job phases and checked ID allocation consistent across loads 2026-12-02 23:23:51 +03:00
faumaray ccd50ec40c Validate persisted operations against live custody invariants 2026-12-02 23:19:06 +03:00
faumaray a76bf87787 Bound save expansion and test authentic custody migration and journal wrap 2026-12-02 23:19:06 +03:00
faumaray 9e20f99a66 Validate work phases and retain exact refusal and consumption receipts 2026-12-02 23:19:05 +03:00
faumaray 539cea0608 Exercise modern saves against live transfer and reservation accounting
# Conflicts:
#	CMakeLists.txt
2026-12-02 23:11:05 +03:00
faumaray 6c6f4e7857 Track transfers, reservations and item owners through colony work 2026-12-02 23:10:35 +03:00
faumaray f1b8d41bb4 Persist item custody and restore in-flight work from historical saves 2026-12-02 23:10:35 +03:00
faumaray 4f42488d54 Define durable custody contracts shared by the world and checkpoint codec 2026-12-02 23:01:43 +03:00
faumaray f6493e2d1c Specify durable cargo ownership and preserve atomic pickup evidence 2026-12-02 22:50:34 +03:00
faumaray 66af7c5bb9 Integrate atomic stock pickups into M01 2026-12-02 22:45:22 +03:00
faumaray 3c997ed236 Transfer reserved meal and construction pickups as one checked operation 2026-12-02 22:45:22 +03:00
faumaray e6a01bedcc Record client integration and the live Windows application checks 2026-12-02 22:39:56 +03:00
faumaray db0a8720a6 Integrate the snapshot-driven Win32 client into M01 2026-12-02 22:36:12 +03:00
faumaray b7f18c094b Drive the Win32 client from committed simulation snapshots and receipts 2026-12-02 22:36:08 +03:00
faumaray 535424196e Record order and profile verification and link voxel library gaps 2026-12-02 22:35:11 +03:00
faumaray a8cd7bb415 Integrate durable production orders and checkpoint schema 2 into M01
# Conflicts:
#	CMakeLists.txt
2026-12-02 22:30:29 +03:00
faumaray 2a3ec924de Preserve production order identities and preflight whole placement batches 2026-12-02 22:30:07 +03:00
faumaray 9a248c31ac Integrate selectable colony rules into M01 2026-12-02 22:28:09 +03:00
faumaray 275956395d Compile selectable colony rules into real bed construction recipes 2026-12-02 22:28:05 +03:00
faumaray 2a5df1a18b Record integrated LAN verification and the next dependency checks 2026-12-02 22:21:33 +03:00
faumaray aa4e271ab4 Integrate runtime-owned LAN compatibility into M01 2026-12-02 22:13:55 +03:00
faumaray eef69caa0e Connect the reviewed LAN owner adapter to the client branch 2026-12-02 22:13:39 +03:00
faumaray 09545bfe85 Serve legacy LAN clients through the authoritative runtime 2026-12-02 22:13:39 +03:00
faumaray 60154bd5f0 Track verified file loading and persistent logistics references 2026-12-02 22:09:36 +03:00
faumaray 4ba64f7e62 Integrate bounded checkpoint reads with stable logistics identities 2026-12-02 22:05:11 +03:00
faumaray ce814767fb Integrate the checkpoint file adapter for the Win32 client 2026-12-02 22:04:58 +03:00
faumaray a063894637 Prepare bounded checkpoint reads and immutable saves off the client thread 2026-12-02 22:04:58 +03:00
faumaray c2d9d8d51a Integrate persistent logistics references with the simulation owner 2026-12-02 22:02:47 +03:00
faumaray 8260e09be7 Keep logistics targets stable through storage and resource removal 2026-12-02 22:02:29 +03:00
faumaray 512c9ef033 Record fixed-clock verification and client integration boundaries 2026-12-02 21:55:49 +03:00
faumaray 8c4c1fe235 Integrate the single-owner clock, publications and recovery 2026-12-02 21:52:31 +03:00
faumaray a4cf99c265 Track durable identity and quantity reservation gaps in VoidLibrary 2026-12-02 21:47:12 +03:00
faumaray ce3a7dc937 Record M01 system verification, upstream issues and review branches 2026-12-02 21:43:34 +03:00
84 changed files with 9360 additions and 484 deletions

No files matched your search

+23 -3
View File
@@ -23,7 +23,7 @@ function(add_void_library)
set(BUILD_SHARED_LIBS OFF)
set(VOID_ENABLE_TESTING OFF)
set(VOID_ENABLE_BENCHMARKS OFF)
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Text Time)
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Math Text Time)
set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON)
if(BUILD_TESTING)
list(APPEND VOID_ENABLED_MODULES Testing)
@@ -39,9 +39,13 @@ endif()
find_package(Threads REQUIRED)
add_library(settlement_core
engine/src/custody.cpp
engine/src/checkpoint.cpp
engine/src/checkpoint_files.cpp
engine/src/colony_profile.cpp
engine/src/command_dispatcher.cpp
engine/src/first_colony.cpp
engine/src/inventory_transaction.cpp
engine/src/rules_manifest.cpp
engine/src/save_service_win32.cpp
engine/src/simulation_runtime.cpp
@@ -58,7 +62,7 @@ target_include_directories(settlement_core
target_compile_features(settlement_core PUBLIC cxx_std_23)
target_link_libraries(settlement_core
PUBLIC Threads::Threads Void::Async Void::Core Void::Time
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Text
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Math Void::Text
)
if(MSVC)
@@ -87,16 +91,21 @@ target_link_libraries(settlement_lan
)
enable_language(RC)
add_library(settlement_client STATIC app/viewer_session.cpp)
target_include_directories(settlement_client PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
target_link_libraries(settlement_client PUBLIC settlement_core)
add_executable(settlement_viewer WIN32
app/d3d_scene_win32.cpp
app/viewer_win32.cpp
app/house_icons.rc
)
target_link_libraries(settlement_viewer PRIVATE settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
if(MSVC)
target_compile_options(settlement_client PRIVATE /W4 /permissive-)
target_compile_options(settlement_lan PRIVATE /W4 /permissive-)
target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
else()
target_compile_options(settlement_client PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
target_compile_options(settlement_lan PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
target_link_options(settlement_viewer PRIVATE -municode)
target_compile_options(settlement_viewer PRIVATE
@@ -112,8 +121,15 @@ endif()
if(BUILD_TESTING)
add_executable(settlement_core_tests
tests/checkpoint_tests.cpp
tests/checkpoint_file_tests.cpp
tests/custody_tests.cpp
tests/custody_migration_tests.cpp
tests/core_tests.cpp
tests/executor_tests.cpp
tests/identity_tests.cpp
tests/production_identity_tests.cpp
tests/profile_tests.cpp
tests/quantity_transaction_tests.cpp
tests/replay_tests.cpp
tests/rules_tests.cpp
tests/runtime_tests.cpp
@@ -128,4 +144,8 @@ if(BUILD_TESTING)
add_executable(settlement_lan_tests tests/lan_tests.cpp tests/test_main.cpp)
target_link_libraries(settlement_lan_tests PRIVATE settlement_lan Void::Testing)
add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests)
add_executable(settlement_viewer_tests tests/viewer_session_tests.cpp tests/test_main.cpp)
target_link_libraries(settlement_viewer_tests PRIVATE settlement_client Void::Testing)
add_test(NAME settlement_viewer_tests COMMAND settlement_viewer_tests)
endif()
+18
View File
@@ -7,6 +7,8 @@
#include <optional>
#include <string>
namespace settlement { class SimulationRuntime; }
namespace settlement::viewer {
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
@@ -20,6 +22,15 @@ struct LanRejection {
GridPosition destination;
};
struct LanCommandResult {
CommandStatus status;
CommandKind kind;
GridPosition cell;
std::uint8_t value;
GridPosition destination;
AgentId resident;
};
class LanSession {
public:
LanSession();
@@ -39,7 +50,14 @@ public:
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
GridPosition destination = {}, AgentId resident = 0);
[[nodiscard]] std::optional<LanRejection> take_rejection() noexcept;
// poll_guest pauses further sends until this one retained result is drained.
[[nodiscard]] std::optional<LanCommandResult> take_result() noexcept;
[[nodiscard]] std::unique_ptr<World> poll(World& world);
// Protocol 11 accepts the compiled default rules and a 32x32 active colony.
// Calls never wait for the owner. An admitted guest operation survives peer
// turnover, so poll_host must continue with the same owner until it settles.
void poll_host(SimulationRuntime& runtime);
[[nodiscard]] std::unique_ptr<World> poll_guest();
private:
struct Impl;
+180 -31
View File
@@ -6,6 +6,7 @@
#include "lan_session.hpp"
#include "lan_wire.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <algorithm>
#include <array>
@@ -153,6 +154,12 @@ struct Action {
} // namespace
struct LanSession::Impl {
struct PendingCommand {
std::future<RuntimeResult> completion;
Void::Uuid::Uuid session;
std::uint64_t peer_generation;
};
bool winsock = false;
Socket listener;
Channel peer;
@@ -167,12 +174,18 @@ struct LanSession::Impl {
std::string notice;
std::deque<Action> actions;
std::optional<LanRejection> rejected_command;
std::optional<LanCommandResult> command_result;
bool result_backpressure = false;
std::uint64_t guest_sequence = 0;
Clock::time_point last_ping{};
Clock::time_point last_snapshot{};
std::uint64_t sent_tick = 0;
std::uint64_t sent_host_sequence = 0;
std::uint64_t sent_guest_sequence = 0;
std::uint64_t peer_generation = 0;
std::optional<Void::Uuid::Uuid> runtime_session;
std::optional<RulesManifest> compatibility_rules;
std::optional<PendingCommand> pending_command;
Impl() {
WSADATA data{};
@@ -185,14 +198,18 @@ struct LanSession::Impl {
}
void drop_peer() noexcept {
++peer_generation;
peer = Channel{};
connecting = authenticated = reject_pending = false;
awaiting_receipt.reset();
guest_sequence = 0;
actions.clear();
rejected_command.reset();
command_result.reset();
last_snapshot = {};
last_ping = {};
// pending_command belongs to the authenticated guest slot, even after
// its socket disappears. A later peer waits for this result to settle.
}
void accept_guest() {
@@ -223,17 +240,21 @@ struct LanSession::Impl {
connecting = false;
}
void authenticate(Message message, std::string_view payload) {
if (reject_pending) return;
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
peer.queue(Message::Reject);
reject_pending = true;
return;
}
authenticated = true;
notice.clear();
}
void handle_host(World& world, Message message, std::string_view payload) {
if (!authenticated) {
if (reject_pending) return;
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
peer.queue(Message::Reject);
reject_pending = true;
return;
}
authenticated = true;
notice.clear();
authenticate(message, payload);
return;
}
if (message == Message::Ping && payload.empty()) return;
@@ -244,6 +265,83 @@ struct LanSession::Impl {
peer.queue(Message::Receipt, std::string_view(reply));
}
void reply(CommandStatus status, const World& world) {
const auto bytes = lan_wire::encode_receipt({status, world.next_command_sequence(guest_player)});
peer.queue(Message::Receipt, std::string_view(bytes));
}
void handle_runtime_host(SimulationRuntime& runtime, const PublishedSnapshot& snapshot,
Message message, std::string_view payload) {
if (!authenticated) {
authenticate(message, payload);
return;
}
if (message == Message::Ping && payload.empty()) return;
const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt;
if (!command) throw std::runtime_error("Invalid guest command.");
if (pending_command) throw std::runtime_error("A guest command is already pending.");
if (command->sequence != snapshot.world->next_command_sequence(guest_player)) {
reply(CommandStatus::WrongSequence, *snapshot.world);
return;
}
const auto& identity = snapshot.identity;
const CommandEnvelope envelope{
command_envelope_version, identity.world, identity.session, identity.city,
snapshot.next_requests[guest_player - 1],
CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident}
};
auto submitted = runtime.try_submit({guest_player}, envelope);
if (submitted.admission == RuntimeAdmission::Accepted) {
pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation);
} else if (submitted.admission == RuntimeAdmission::Busy) {
reply(CommandStatus::Busy, *snapshot.world);
} else {
throw std::runtime_error("The authoritative owner cannot accept guest commands.");
}
}
void complete_runtime_command() {
if (!pending_command || pending_command->completion.wait_for(0s) != std::future_status::ready) return;
auto pending = std::move(*pending_command);
pending_command.reset();
const auto result = pending.completion.get();
if (pending.peer_generation != peer_generation || !authenticated ||
!runtime_session || pending.session != *runtime_session) return;
if (result.outcome != RuntimeOutcome::Completed || !result.receipt || !result.snapshot ||
result.snapshot->identity.session != pending.session) {
throw std::runtime_error("The authoritative guest command did not commit.");
}
const auto& receipt = *result.receipt;
if (receipt.status == DispatchStatus::Completed) {
reply(receipt.command_status, *result.snapshot->world);
} else if (receipt.status == DispatchStatus::Busy) {
reply(CommandStatus::Busy, *result.snapshot->world);
} else {
throw std::runtime_error("The guest command belongs to an obsolete or conflicting request.");
}
}
void bind_runtime(const RuntimeView& view) {
if (!compatibility_rules) {
auto rules = default_rules_manifest();
if (!rules) throw std::runtime_error("Could not resolve the legacy LAN rules.");
compatibility_rules = std::move(*rules);
}
if (view.state != RuntimeState::Running || !view.snapshot) {
throw std::runtime_error("The authoritative owner is unavailable.");
}
const auto& snapshot = *view.snapshot;
if (!snapshot.rules || *snapshot.rules != *compatibility_rules) {
throw std::runtime_error("Protocol 11 requires the compiled default rules.");
}
if (!snapshot.world->scenario_active() || snapshot.world->width() != first_colony_map_size ||
snapshot.world->height() != first_colony_map_size) {
throw std::runtime_error("Protocol 11 requires a supported 32x32 colony.");
}
if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer();
runtime_session = snapshot.identity.session;
}
void handle_guest(std::unique_ptr<World>& latest, Message message, std::string_view payload) {
if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version.");
if (message == Message::Snapshot) {
@@ -264,6 +362,8 @@ struct LanSession::Impl {
}
const auto status = receipt->status;
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
command_result = LanCommandResult{status, awaiting_receipt->kind, awaiting_receipt->cell,
awaiting_receipt->value, awaiting_receipt->destination, awaiting_receipt->resident};
if (status != CommandStatus::Accepted) {
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell,
awaiting_receipt->value, awaiting_receipt->destination};
@@ -291,6 +391,7 @@ struct LanSession::Impl {
void send_action() {
if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return;
if (result_backpressure && command_result) return;
const Action action = actions.front();
const auto payload = lan_wire::encode_command(
{guest_player, guest_sequence, action.kind, action.cell, action.value, action.destination, action.resident});
@@ -298,6 +399,31 @@ struct LanSession::Impl {
actions.pop_front();
awaiting_receipt = action;
}
template<class Receive, class SendHost>
void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) {
if (listener && accept_allowed) accept_guest();
if (!peer.socket) return;
const auto now = Clock::now();
if ((!authenticated && now - peer.opened > 8s) ||
(authenticated && now - peer.last_received > 15s)) {
throw std::runtime_error("The peer did not respond.");
}
if (connecting) finish_connection();
if (connecting) return;
peer.receive(receive);
if (authenticated && guest) {
send_action();
if (!peer.pending() && now - last_ping >= 2s) {
peer.queue(Message::Ping);
last_ping = now;
}
} else if (authenticated) {
send_host(now);
}
peer.flush();
if (reject_pending && !peer.pending()) drop_peer();
}
};
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
@@ -397,34 +523,57 @@ std::optional<LanRejection> LanSession::take_rejection() noexcept {
return std::exchange(impl_->rejected_command, std::nullopt);
}
std::optional<LanCommandResult> LanSession::take_result() noexcept {
return std::exchange(impl_->command_result, std::nullopt);
}
std::unique_ptr<World> LanSession::poll(World& world) {
auto& connection = *impl_;
connection.result_backpressure = false;
std::unique_ptr<World> latest;
try {
if (connection.listener) connection.accept_guest();
if (!connection.peer.socket) return nullptr;
const auto now = Clock::now();
if ((!connection.authenticated && now - connection.peer.opened > 8s) ||
(connection.authenticated && now - connection.peer.last_received > 15s)) {
throw std::runtime_error("The peer did not respond.");
}
if (connection.connecting) connection.finish_connection();
if (connection.connecting) return nullptr;
connection.peer.receive([&](Message message, std::string_view payload) {
if (connection.pending_command) throw std::runtime_error("Continue polling the authoritative owner.");
connection.poll_network([&](Message message, std::string_view payload) {
if (connection.guest) connection.handle_guest(latest, message, payload);
else connection.handle_host(world, message, payload);
});
if (connection.authenticated && connection.guest) {
connection.send_action();
if (!connection.peer.pending() && now - connection.last_ping >= 2s) {
connection.peer.queue(Message::Ping);
connection.last_ping = now;
}
} else if (connection.authenticated) {
connection.send_snapshot(world, now);
}
connection.peer.flush();
if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer();
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); });
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
latest.reset();
}
return latest;
}
void LanSession::poll_host(SimulationRuntime& runtime) {
auto& connection = *impl_;
if (!connection.listener || connection.guest) return;
try {
connection.complete_runtime_command();
// Completion may have published a newer next-request number. Re-read it
// before admitting a reconnect or decoding any further guest intent.
const auto view = runtime.view();
connection.bind_runtime(view);
connection.poll_network([&](Message message, std::string_view payload) {
connection.handle_runtime_host(runtime, *view.snapshot, message, payload);
}, [&](Clock::time_point now) {
if (!connection.pending_command) connection.send_snapshot(*view.snapshot->world, now);
}, !connection.pending_command);
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
}
}
std::unique_ptr<World> LanSession::poll_guest() {
auto& connection = *impl_;
connection.result_backpressure = true;
std::unique_ptr<World> latest;
if (!connection.guest) return nullptr;
try {
connection.poll_network([&](Message message, std::string_view payload) {
connection.handle_guest(latest, message, payload);
}, [](Clock::time_point) {});
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
+324
View File
@@ -0,0 +1,324 @@
#include "viewer_session.hpp"
#include <chrono>
#include <limits>
#include <stdexcept>
#include <utility>
namespace settlement::viewer {
namespace {
template<class T>
bool ready(std::future<T>& completion) {
return completion.valid() && completion.wait_for(std::chrono::seconds{0}) == std::future_status::ready;
}
RulesManifest supported_rules() {
auto manifest = default_rules_manifest();
if (!manifest) throw std::runtime_error(manifest.error().message);
return std::move(*manifest);
}
void validate_supported(const WorldCheckpoint& candidate, const RulesManifest& rules) {
if (!candidate.world || candidate.world->width() != first_colony_map_size ||
candidate.world->height() != first_colony_map_size) {
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
}
if (candidate.rules != rules) {
throw std::runtime_error("This viewer requires the installed default colony rules.");
}
}
WorldCheckpoint validated_initial(WorldCheckpoint candidate, const RulesManifest& rules) {
validate_supported(candidate, rules);
return candidate;
}
WorldCheckpoint initial_colony(std::size_t workers) {
auto identity = Void::Uuid::try_v4();
if (!identity) throw std::runtime_error("Could not create a world identity.");
return {make_first_colony(workers), *identity, 1, supported_rules()};
}
RuntimeOptions suspended(RuntimeOptions options) {
options.ticking = false;
return options;
}
std::string exception_message() {
try { throw; }
catch (const std::exception& error) { return error.what(); }
catch (...) { return "The operation failed."; }
}
} // namespace
ViewerSession::ViewerSession(std::size_t workers, ViewerSessionOptions options)
: ViewerSession(initial_colony(workers), workers, std::move(options)) {}
ViewerSession::ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options)
: workers_(workers), command_capacity_(options.command_capacity),
supported_rules_(supported_rules()),
runtime_(validated_initial(std::move(initial), supported_rules_), suspended(std::move(options.runtime))),
files_(std::move(options.files)) {
if (command_capacity_ == 0) throw std::invalid_argument("The command queue must have capacity.");
}
ViewerSession::~ViewerSession() = default;
std::shared_ptr<const World> ViewerSession::world() const {
return guest_ || (changing_world_ && guest_view_) ? guest_view_ : runtime_.latest()->world;
}
bool ViewerSession::can_submit() const {
return !guest_ && !changing_world_ && runtime_.view().state == RuntimeState::Running;
}
std::optional<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
if (!can_submit()) return std::nullopt;
for (const auto& intent : intents_) {
if (intent.payload == payload) return intent.id;
}
if (intents_.size() == command_capacity_ || next_intent_ == std::numeric_limits<std::uint64_t>::max()) {
return std::nullopt;
}
const auto id = next_intent_;
intents_.push_back({id, std::move(payload)});
++next_intent_;
return id;
}
bool ViewerSession::pending(std::uint64_t id) const noexcept {
for (const auto& intent : intents_) if (intent.id == id) return true;
return false;
}
LoadTicket ViewerSession::begin_change() {
if (generation_ == std::numeric_limits<std::uint64_t>::max()) {
throw std::overflow_error("The client operation counter is exhausted.");
}
auto ticket = runtime_.begin_load();
if (!ticket) throw std::runtime_error("The simulation cannot accept a world change.");
++generation_;
intents_.clear();
command_completion_ = {};
preparing_.reset();
installing_.reset();
install_completion_ = {};
events_.clear();
changing_world_ = true;
return *ticket;
}
void ViewerSession::validate_candidate(const WorldCheckpoint& candidate) const {
validate_supported(candidate, supported_rules_);
}
void ViewerSession::replace(WorldCheckpoint candidate) {
validate_candidate(candidate);
const auto ticket = begin_change();
installing_.emplace(Installing{ticket, std::move(candidate)});
}
void ViewerSession::new_colony() {
replace(initial_colony(workers_));
}
void ViewerSession::load(const std::filesystem::path& path) {
if (guest_) throw std::runtime_error("Only the host can load a world.");
const auto ticket = begin_change();
try {
auto operation = files_.try_load(path, workers_);
if (operation.admission != CheckpointLoadAdmission::Accepted) {
throw std::runtime_error("The file reader is busy or unavailable. Try again.");
}
preparing_.emplace(Preparing{ticket, std::move(operation.completion)});
} catch (...) {
changing_world_ = false;
throw;
}
}
void ViewerSession::save(const std::filesystem::path& path) {
if (guest_ || changing_world_) throw std::runtime_error("The current world cannot be saved yet.");
poll_saves();
const auto snapshot = runtime_.snapshot_for_save();
if (!snapshot) throw std::runtime_error("Load a valid world before saving after a simulation failure.");
// Reserve result tracking before accepting a write so allocation cannot lose
// the newest request's completion or its originating session.
saving_.reserve(saving_.size() + 1);
auto operation = files_.try_save(path, *snapshot);
if (operation.admission != SaveAdmission::Accepted) {
throw std::runtime_error("The save queue is busy or unavailable. Try again.");
}
latest_save_ = operation.request_id;
saving_.push_back({generation_, operation.request_id, (*snapshot)->identity.session,
std::move(operation.completion)});
}
void ViewerSession::enter_guest() {
static_cast<void>(begin_change());
guest_ = true;
changing_world_ = false;
guest_world_.reset();
guest_view_.reset();
}
void ViewerSession::receive_guest(std::unique_ptr<World> world) {
if (!guest_ || !world) return;
auto view = world->capture();
guest_world_ = std::move(world);
guest_view_ = std::move(view);
}
void ViewerSession::leave_guest() {
if (!guest_) return;
if (guest_world_) {
auto id = Void::Uuid::try_v4();
if (!id) throw std::runtime_error("Could not create a world identity.");
if (guest_world_->width() != first_colony_map_size || guest_world_->height() != first_colony_map_size) {
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
}
// All fallible preparation precedes moving the last received world.
auto rules = supported_rules_;
const auto ticket = begin_change();
installing_.emplace(Installing{ticket, {std::move(guest_world_), *id, 1, std::move(rules)}});
} else {
static_cast<void>(begin_change());
changing_world_ = false;
}
guest_ = false;
if (!changing_world_) guest_view_.reset();
}
void ViewerSession::fail_change(std::string message) {
preparing_.reset();
installing_.reset();
install_completion_ = {};
changing_world_ = false;
if (!guest_) guest_view_.reset();
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable, std::move(message)});
}
void ViewerSession::poll_changes() {
if (preparing_ && ready(preparing_->completion)) {
const auto ticket = preparing_->ticket;
auto prepared = preparing_->completion.get();
preparing_.reset();
if (runtime_.latest()->identity.session != ticket.expected_session) {
fail_change("The load belongs to an earlier session.");
return;
}
if (!prepared) {
fail_change(prepared.error().message);
return;
}
validate_candidate(*prepared);
installing_.emplace(Installing{ticket, std::move(*prepared)});
}
if (installing_) {
auto result = runtime_.try_install(installing_->ticket, installing_->candidate);
if (result.admission == RuntimeAdmission::Accepted) {
install_completion_ = std::move(result.completion);
installing_.reset();
} else if (result.admission != RuntimeAdmission::Busy) {
fail_change("The simulation could not install this world.");
}
}
if (ready(install_completion_)) {
const auto result = install_completion_.get();
changing_world_ = false;
if (result.outcome == RuntimeOutcome::Completed && result.snapshot &&
result.snapshot->identity.session == runtime_.latest()->identity.session) {
guest_view_.reset();
fault_reported_ = false;
events_.push_back({ViewerEventKind::Replaced, 0, {}, CommandStatus::Unavailable, {}});
} else {
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable,
"The world change failed or was superseded. The current view is retained."});
}
}
}
void ViewerSession::poll_commands() {
if (ready(command_completion_)) {
auto result = command_completion_.get();
if (!intents_.empty()) {
auto intent = std::move(intents_.front());
intents_.pop_front();
const auto status = result.outcome == RuntimeOutcome::Completed && result.receipt &&
result.receipt->status == DispatchStatus::Completed
? result.receipt->command_status : CommandStatus::Unavailable;
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), status, {}});
}
}
if (command_completion_.valid() || intents_.empty() || !can_submit()) return;
const auto current = runtime_.latest();
const CommandEnvelope command{command_envelope_version, current->identity.world, current->identity.session,
current->identity.city, current->next_requests[colony_host - 1], intents_.front().payload};
auto result = runtime_.try_submit({colony_host}, command);
if (result.admission == RuntimeAdmission::Accepted) {
command_completion_ = std::move(result.completion);
} else if (result.admission != RuntimeAdmission::Busy) {
auto intent = std::move(intents_.front());
intents_.pop_front();
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), CommandStatus::Unavailable, {}});
}
}
void ViewerSession::poll_saves() {
for (auto item = saving_.begin(); item != saving_.end();) {
if (!ready(item->completion)) {
++item;
continue;
}
const auto result = item->completion.get();
if (item->generation == generation_ && item->request == latest_save_ &&
item->session == runtime_.latest()->identity.session && !guest_) {
events_.push_back({result.succeeded() ? ViewerEventKind::Saved : ViewerEventKind::Error,
0, {}, CommandStatus::Unavailable,
result.succeeded() ? "" : result.visible_on_disk
? "The new save is visible, but its final disk status could not be confirmed."
: "The save failed. The previous slot remains available."});
}
item = saving_.erase(item);
}
}
void ViewerSession::poll_ticking() {
if (ready(ticking_completion_)) {
const auto result = ticking_completion_.get();
// The owner applies its ticking flag even while its world is faulted.
if (result.outcome == RuntimeOutcome::Completed || result.outcome == RuntimeOutcome::Faulted) {
applied_ticking_ = requested_ticking_;
}
}
const bool desired = desired_ticking_ && !guest_ && !changing_world_;
if (ticking_completion_.valid() || desired == applied_ticking_) return;
auto result = runtime_.set_ticking(desired);
if (result.admission == RuntimeAdmission::Accepted) {
requested_ticking_ = desired;
ticking_completion_ = std::move(result.completion);
}
}
std::vector<ViewerEvent> ViewerSession::poll() {
try {
poll_changes();
poll_commands();
poll_saves();
poll_ticking();
} catch (...) {
fail_change(exception_message());
}
if (!guest_ && runtime_.view().state == RuntimeState::Faulted && !fault_reported_) {
fault_reported_ = true;
intents_.clear();
command_completion_ = {};
events_.push_back({ViewerEventKind::Fault, 0, {}, CommandStatus::Unavailable,
"The simulation stopped at its last completed state. Load a save to continue."});
}
return std::exchange(events_, {});
}
} // namespace settlement::viewer
+109
View File
@@ -0,0 +1,109 @@
#pragma once
#include "settlement/core/checkpoint_files.hpp"
#include <deque>
#include <filesystem>
#include <optional>
#include <string>
#include <vector>
namespace settlement::viewer {
enum class ViewerEventKind { Replaced, Command, Saved, Error, Fault };
struct ViewerEvent {
ViewerEventKind kind;
std::uint64_t command = 0;
std::optional<SessionPayload> payload;
CommandStatus status = CommandStatus::Unavailable;
std::string message;
};
struct ViewerSessionOptions {
RuntimeOptions runtime;
CheckpointFilesOptions files;
std::size_t command_capacity = 64;
};
// Called only by the UI thread. Polling owns completion delivery; rendering holds
// an immutable view independently of owner progress and nested window messages.
class ViewerSession {
public:
explicit ViewerSession(std::size_t workers, ViewerSessionOptions options = {});
ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options = {});
~ViewerSession();
[[nodiscard]] SimulationRuntime& runtime() noexcept { return runtime_; }
[[nodiscard]] std::shared_ptr<const World> world() const;
[[nodiscard]] bool guest() const noexcept { return guest_; }
[[nodiscard]] bool changing_world() const noexcept { return changing_world_; }
[[nodiscard]] bool can_submit() const;
[[nodiscard]] std::uint64_t generation() const noexcept { return generation_; }
[[nodiscard]] std::optional<std::uint64_t> submit(SessionPayload payload);
[[nodiscard]] bool pending(std::uint64_t id) const noexcept;
void set_ticking(bool enabled) noexcept { desired_ticking_ = enabled; }
[[nodiscard]] std::vector<ViewerEvent> poll();
void new_colony();
void load(const std::filesystem::path& path);
void save(const std::filesystem::path& path);
void enter_guest();
void receive_guest(std::unique_ptr<World> world);
void leave_guest();
private:
struct Intent {
std::uint64_t id;
SessionPayload payload;
};
struct Preparing {
LoadTicket ticket;
std::future<CheckpointLoadResult> completion;
};
struct Installing {
LoadTicket ticket;
WorldCheckpoint candidate;
};
struct Saving {
std::uint64_t generation;
std::uint64_t request;
Void::Uuid::Uuid session;
std::future<SaveResult> completion;
};
[[nodiscard]] LoadTicket begin_change();
void replace(WorldCheckpoint candidate);
void validate_candidate(const WorldCheckpoint& candidate) const;
void fail_change(std::string message);
void poll_changes();
void poll_commands();
void poll_saves();
void poll_ticking();
std::size_t workers_;
std::size_t command_capacity_;
RulesManifest supported_rules_;
SimulationRuntime runtime_;
CheckpointFiles files_;
std::shared_ptr<const World> guest_view_;
std::unique_ptr<World> guest_world_;
std::deque<Intent> intents_;
std::future<RuntimeResult> command_completion_;
std::optional<Preparing> preparing_;
std::optional<Installing> installing_;
std::future<RuntimeResult> install_completion_;
std::vector<Saving> saving_;
std::vector<ViewerEvent> events_;
std::future<RuntimeResult> ticking_completion_;
bool requested_ticking_ = false;
bool applied_ticking_ = false;
bool desired_ticking_ = false;
bool guest_ = false;
bool changing_world_ = false;
bool fault_reported_ = false;
std::uint64_t generation_ = 1;
std::uint64_t next_intent_ = 1;
std::uint64_t latest_save_ = 0;
};
} // namespace settlement::viewer
+352 -190
View File
@@ -11,6 +11,7 @@
#include "map_camera.hpp"
#include "lan_session.hpp"
#include "title_screen_win32.hpp"
#include "viewer_session.hpp"
#include "settlement/core/world.hpp"
#include <algorithm>
@@ -22,6 +23,7 @@
#include <fstream>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <memory>
#include <optional>
#include <span>
@@ -116,7 +118,8 @@ struct DockLayout {
};
DockLayout dock_layout;
std::array<HWND, 3> dock_section_buttons{};
std::unique_ptr<settlement::World> world;
std::shared_ptr<const settlement::World> world;
std::unique_ptr<settlement::viewer::ViewerSession> session;
namespace title = settlement::viewer;
title::TitleScreen title_screen;
bool showing_title = true;
@@ -132,8 +135,9 @@ constexpr const wchar_t* building_view_labels[] = {
L"Вид: полный", L"Вид: без крыш", L"Вид: без стен и крыш",
};
using settlement::viewer::LanState;
settlement::viewer::LanSession lan;
auto lan = std::make_unique<settlement::viewer::LanSession>();
LanState displayed_lan_state = LanState::Offline;
std::uint64_t lan_generation = 1;
const auto local_worker_count = std::clamp<std::size_t>(
std::thread::hardware_concurrency(), settlement::min_worker_count, 8);
enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room };
@@ -244,6 +248,25 @@ ResidentRoster roster;
std::optional<settlement::BedBase> selected_bed_base;
std::vector<settlement::viewer::BlueprintPart> blueprint;
std::vector<settlement::RoomPlan> room_blueprints;
struct PendingDraft {
std::uint64_t command;
std::uint64_t revision;
settlement::SessionPayload payload;
std::optional<settlement::RoomPlan> room;
std::optional<settlement::viewer::BlueprintPart> part;
bool guest;
};
std::vector<PendingDraft> pending_drafts;
struct GuestIntent {
std::uint64_t command;
std::uint64_t generation;
settlement::SessionPayload payload;
};
std::vector<GuestIntent> guest_intents;
constexpr std::size_t guest_intent_capacity = 64;
std::uint64_t draft_revision = 0;
std::uint64_t guest_command_id = 0;
bool host_after_replacement = false;
std::optional<settlement::GridPosition> room_anchor;
settlement::RoomTemplate selected_room_template = settlement::RoomTemplate::Empty;
std::optional<settlement::RoomSide> preferred_room_entrance;
@@ -266,6 +289,9 @@ std::optional<settlement::GridPosition> hover_cell;
std::optional<settlement::AgentId> selected_resident;
std::wstring placement_message;
void pump_session(HWND window);
void reconcile_ticking();
int dock_pixels(int pixels) {
return MulDiv(pixels, dock_layout.scale, 100);
}
@@ -798,7 +824,7 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) {
}
bool can_give_orders() {
return !lan.is_guest() || lan.state() == LanState::GuestConnected;
return world && session && (lan->is_guest() ? lan->state() == LanState::GuestConnected : session->can_submit());
}
void update_roster_details() {
@@ -974,6 +1000,8 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message
}
void clear_blueprints() {
++draft_revision;
pending_drafts.clear();
blueprint.clear();
room_blueprints.clear();
room_anchor.reset();
@@ -988,15 +1016,16 @@ void toggle_work_panel(HWND window, WorkPanel panel) {
}
bool can_resume_session() {
return has_session && lan.state() != LanState::Connecting && lan.state() != LanState::GuestDisconnected;
return has_session && lan->state() != LanState::Connecting && lan->state() != LanState::GuestDisconnected;
}
void update_title_controls() {
title_screen.update(can_resume_session(), lan.state() == LanState::Offline);
title_screen.update(can_resume_session(), lan->state() == LanState::Offline);
}
void show_title_screen(HWND window, bool visible) {
showing_title = visible;
reconcile_ticking();
if (visible) {
if (roster.window) DestroyWindow(roster.window);
set_work_panel(window, WorkPanel::None);
@@ -1025,15 +1054,11 @@ void show_title_screen(HWND window, bool visible) {
}
void reset_world(HWND window) {
world = settlement::make_first_colony(local_worker_count);
session->new_colony();
host_after_replacement = false;
clear_blueprints();
camera = {};
selected_resident.reset();
sync_resident_roster(true);
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None);
show_title_screen(window, false);
update_status();
placement_message = L"Создаём поселение…";
reconcile_ticking();
invalidate_scene(window);
}
@@ -1062,59 +1087,28 @@ std::optional<std::filesystem::path> choose_save_file(HWND window, bool saving)
return std::nullopt;
}
void save_world_file(const std::filesystem::path& path) {
// Stage the complete file beside its destination before replacing an existing save.
wchar_t temporary[MAX_PATH]{};
if (GetTempFileNameW(path.parent_path().c_str(), L"stl", 0, temporary) == 0) {
throw std::runtime_error("Could not create a temporary save in this folder.");
}
try {
std::ofstream stream(std::filesystem::path(temporary), std::ios::binary | std::ios::trunc);
if (!stream) throw std::runtime_error("Could not open the temporary save for writing.");
world->write_save(stream);
stream.close();
if (!stream) throw std::runtime_error("Could not finish writing the temporary save.");
if (!MoveFileExW(temporary, path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
throw std::runtime_error("Could not move the completed save into place.");
}
} catch (...) {
DeleteFileW(temporary);
throw;
}
}
void handle_save_menu(HWND window, bool saving, std::optional<std::filesystem::path> selected = std::nullopt) {
if (file_dialog_active || (saving && !world)) return;
if (lan.is_guest() || (!saving && lan.state() != LanState::Offline)) return;
if (lan->is_guest() || (!saving && lan->state() != LanState::Offline)) return;
file_dialog_active = true;
reconcile_ticking();
struct RestoreTimer {
~RestoreTimer() { file_dialog_active = false; }
~RestoreTimer() { file_dialog_active = false; reconcile_ticking(); }
} restore_timer;
try {
const auto path = selected ? std::move(selected) : choose_save_file(window, saving);
if (!path) return;
if (saving) {
save_world_file(*path);
placement_message = L"Поселение сохранено.";
invalidate_scene(window);
return;
session->save(*path);
placement_message = L"Сохраняем поселение…";
} else {
session->load(*path);
host_after_replacement = false;
clear_blueprints();
placement_message = L"Загружаем поселение…";
}
std::ifstream stream(*path, std::ios::binary);
if (!stream) throw std::runtime_error("Could not open the requested save.");
auto loaded = settlement::World::read_save(stream, local_worker_count);
if (loaded->width() != map_size || loaded->height() != map_size) {
throw std::runtime_error("This viewer opens saves with a 32 by 32 map.");
}
world = std::move(loaded);
clear_blueprints();
camera = {};
selected_resident.reset();
sync_resident_roster(true);
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None, L"Поселение загружено.");
show_title_screen(window, false);
update_status();
invalidate_scene(window);
} catch (const std::exception& error) {
const std::string_view details(error.what());
const std::wstring message = std::wstring(saving ? L"Не удалось сохранить поселение.\n" :
@@ -1217,14 +1211,15 @@ void show_lan_info(HWND window) {
const auto addresses = settlement::viewer::local_lan_addresses();
const auto text = L"Передайте другу IPv4 вашего компьютера и код партии.\n\nIPv4: " +
(addresses.empty() ? std::wstring(L"см. ipconfig") : widen_ascii(addresses)) +
L"\nКод партии: " + widen_ascii(lan.join_code()) +
L"\nПорт TCP: " + std::to_wstring(lan.port()) +
L"\nКод партии: " + widen_ascii(lan->join_code()) +
L"\nПорт TCP: " + std::to_wstring(lan->port()) +
L"\n\nДруг в той же сети выбирает «Кооператив → Подключиться к другу…» в главном меню.";
MessageBoxW(window, text.c_str(), L"Кооператив по локальной сети", MB_OK | MB_ICONINFORMATION);
}
void refresh_lan_controls(HWND window) {
const auto state = lan.state();
const auto state = lan->state();
if (state != displayed_lan_state) ++lan_generation;
displayed_lan_state = state;
const bool disconnected = state == LanState::GuestDisconnected;
const wchar_t* suffix = L"";
@@ -1258,48 +1253,65 @@ void refresh_lan_controls(HWND window) {
void handle_lan_menu(HWND window, int command) {
if (!showing_title) return;
try {
if (command == lan_host_id && lan.state() == LanState::Offline) {
auto colony = !has_session || !world || !world->scenario_active()
? settlement::make_first_colony(local_worker_count) : nullptr;
lan.host();
if (colony) {
world = std::move(colony);
if (command == lan_host_id && lan->state() == LanState::Offline) {
if (!has_session || !world || !world->scenario_active()) {
session->new_colony();
host_after_replacement = true;
clear_blueprints();
camera = {};
selected_resident.reset();
placement_message = L"Создаём сетевую колонию…";
reconcile_ticking();
invalidate_scene(window);
return;
}
lan->host();
has_session = true;
placement_message = L"Сетевая колония открыта. Нажмите «Продолжить», чтобы войти.";
refresh_lan_controls(window);
show_lan_info(window);
return;
} else if (command == lan_join_id &&
(lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) {
(lan->state() == LanState::Offline || lan->state() == LanState::GuestDisconnected)) {
const auto request = ask_join_address(window);
if (!request) return;
if (!world) world = settlement::make_first_colony(local_worker_count);
lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data()));
// Stage networking first. A rejected address or owner admission must
// retain the previous disconnected replica and connection state.
auto incoming = std::make_unique<settlement::viewer::LanSession>();
incoming->join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data()));
session->enter_guest();
lan.swap(incoming);
guest_intents.clear();
world = session->world();
host_after_replacement = false;
clear_blueprints();
enter_game_on_snapshot = true;
selected_resident.reset();
sync_resident_roster(true);
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None, L"Подключаемся к хозяину…");
} else if (command == lan_info_id && !lan.is_guest() && lan.state() != LanState::Offline) {
} else if (command == lan_info_id && !lan->is_guest() && lan->state() != LanState::Offline) {
show_lan_info(window);
return;
} else if (command == lan_reconnect_id && lan.state() == LanState::GuestDisconnected) {
lan.reconnect();
} else if (command == lan_reconnect_id && lan->state() == LanState::GuestDisconnected) {
lan->reconnect();
enter_game_on_snapshot = true;
placement_message = L"Подключаемся к хозяину…";
} else if (command == lan_leave_id) {
lan.leave();
const bool was_guest = lan->is_guest();
if (was_guest) session->leave_guest();
lan->leave();
guest_intents.clear();
if (was_guest) {
clear_blueprints();
world = session->world();
}
enter_game_on_snapshot = false;
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None, L"Сетевая игра завершена.");
}
refresh_lan_controls(window);
reconcile_ticking();
} catch (const std::exception& error) {
if (session->guest() && !lan->is_guest()) session->leave_guest();
const auto text = L"Не удалось выполнить действие.\n" + widen_ascii(error.what());
MessageBoxW(window, text.c_str(), L"Кооператив", MB_OK | MB_ICONERROR);
}
@@ -1316,7 +1328,7 @@ void handle_title_command(HWND window, int command, int notification) {
open_coop_menu(window);
return;
}
const bool offline = lan.state() == LanState::Offline;
const bool offline = lan->state() == LanState::Offline;
if (command == title::title_continue_id && notification == BN_CLICKED && can_resume_session()) {
show_title_screen(window, false);
refresh_lan_controls(window);
@@ -1352,19 +1364,36 @@ const settlement::ResourceNode* berry_source(settlement::GridPosition cell) {
return nullptr;
}
settlement::CommandStatus submit_command(settlement::CommandKind kind, settlement::GridPosition cell,
std::uint8_t value, settlement::GridPosition destination = {},
settlement::AgentId resident = 0) {
if (lan.is_guest()) {
return lan.submit(kind, cell, value, destination, resident) ? settlement::CommandStatus::Accepted :
settlement::CommandStatus::Unavailable;
std::optional<std::uint64_t> enqueue_command(settlement::SessionPayload payload) {
if (!can_give_orders()) return std::nullopt;
if (lan->is_guest()) {
const auto* command = std::get_if<settlement::CommandPayload>(&payload);
for (const auto& pending : guest_intents) {
if (pending.payload == payload) return pending.command;
}
if (!command || guest_intents.size() == guest_intent_capacity ||
guest_command_id == std::numeric_limits<std::uint64_t>::max()) return std::nullopt;
guest_intents.reserve(guest_intents.size() + 1);
if (!lan->submit(command->kind, command->cell, command->value, command->destination, command->resident)) {
return std::nullopt;
}
const auto id = ++guest_command_id;
guest_intents.push_back({id, session->generation(), std::move(payload)});
return id;
}
constexpr auto host = settlement::colony_host;
return world->apply_command({host, world->next_command_sequence(host), kind, cell, value, destination, resident}).status;
return session->submit(std::move(payload));
}
bool submit_command(settlement::CommandKind kind, settlement::GridPosition cell,
std::uint8_t value, settlement::GridPosition destination = {},
settlement::AgentId resident = 0) {
const bool queued = enqueue_command(settlement::CommandPayload{kind, cell, value, destination, resident}).has_value();
placement_message = queued ? L"Команда ожидает подтверждения…" : L"Очередь занята. Попробуйте ещё раз.";
return queued;
}
bool send_command(settlement::CommandKind kind, settlement::GridPosition cell = {}, std::uint8_t value = 0) {
return submit_command(kind, cell, value) == settlement::CommandStatus::Accepted;
return submit_command(kind, cell, value);
}
bool valid_edit_cell(settlement::GridPosition cell) {
@@ -1455,6 +1484,12 @@ void rotate_room_preview(HWND window, int direction) {
void edit_room_blueprint(HWND window, settlement::GridPosition cell, bool shift) {
if (!can_give_orders()) return;
if (std::any_of(pending_drafts.begin(), pending_drafts.end(),
[cell](const auto& pending) { return pending.room && pending.room->contains(cell); })) {
placement_message = L"Комната ожидает подтверждения.";
invalidate_scene(window);
return;
}
using settlement::RoomSide;
if (room_draft_move) {
auto& original = room_blueprints[room_draft_move->index];
@@ -1534,6 +1569,12 @@ std::optional<settlement::viewer::BlueprintPart> preview_blueprint(settlement::G
void edit_blueprint(HWND window, settlement::GridPosition cell) {
if (!can_give_orders()) return;
if (std::any_of(pending_drafts.begin(), pending_drafts.end(),
[cell](const auto& pending) { return pending.part && pending.part->cell == cell; })) {
placement_message = L"Объект ожидает подтверждения.";
invalidate_scene(window);
return;
}
if (std::erase_if(blueprint, [cell](const auto& part) { return part.cell == cell; }) != 0) {
placement_message = L"Объект убран из чертежа.";
} else if (const auto part = preview_blueprint(cell);
@@ -1552,47 +1593,184 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) {
void submit_blueprint(HWND window) {
if (!world || !has_blueprint() || room_draft_move || !can_give_orders()) return;
using settlement::CommandKind;
using settlement::CommandPayload;
using settlement::RecipeId;
const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) {
return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first,
room.placement_value(), room.last) == settlement::CommandStatus::Accepted;
});
const auto objects_sent = std::erase_if(blueprint, [](const auto& part) {
const auto queue = [&](settlement::SessionPayload payload, std::optional<settlement::RoomPlan> room,
std::optional<settlement::viewer::BlueprintPart> part) {
if (std::any_of(pending_drafts.begin(), pending_drafts.end(),
[&](const auto& pending) { return pending.payload == payload; })) return;
pending_drafts.reserve(pending_drafts.size() + 1);
if (const auto id = enqueue_command(payload)) {
pending_drafts.push_back({*id, draft_revision, std::move(payload), room, part, lan->is_guest()});
}
};
for (const auto& room : room_blueprints) {
if (world->can_place_room(room)) {
queue(CommandPayload{CommandKind::PlaceRoom, room.first, room.placement_value(), room.last}, room, {});
}
}
for (const auto& part : blueprint) {
switch (part.recipe) {
case RecipeId::BuildBed:
return world->can_place_bed(part.cell) &&
send_command(CommandKind::PlaceBed, part.cell, static_cast<std::uint8_t>(part.base));
case RecipeId::WeaveCloth:
return world->can_place_storage(part.cell) && send_command(CommandKind::PlaceLoom, part.cell);
case RecipeId::BuildCabin:
try {
world->queue_cabin(part.cell, sawmill, stonecutter);
return true;
} catch (const std::invalid_argument&) {
return false;
if (world->can_place_bed(part.cell)) {
queue(CommandPayload{CommandKind::PlaceBed, part.cell, static_cast<std::uint8_t>(part.base)}, {}, part);
}
default:
return false;
break;
case RecipeId::WeaveCloth:
if (world->can_place_storage(part.cell)) queue(CommandPayload{CommandKind::PlaceLoom, part.cell}, {}, part);
break;
case RecipeId::BuildCabin:
queue(settlement::LegacyCabinPayload{part.cell, sawmill, stonecutter}, {}, part);
break;
default: break;
}
}
placement_message = pending_drafts.empty() ? L"Проверьте свободные клетки и доступ к площадке." :
L"Ожидают подтверждения мест: " + std::to_wstring(pending_drafts.size()) + L".";
update_blueprint_controls(window);
invalidate_scene(window);
}
void complete_command(std::uint64_t id, const settlement::SessionPayload& payload,
settlement::CommandStatus status, bool guest) {
const bool accepted = status == settlement::CommandStatus::Accepted;
auto pending = std::find_if(pending_drafts.begin(), pending_drafts.end(), [&](const auto& entry) {
return entry.guest == guest && entry.command == id;
});
const std::wstring count = std::to_wstring(rooms_sent + objects_sent);
if (has_blueprint()) {
placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " +
std::to_wstring(blueprint.size() + room_blueprints.size()) +
(lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." :
L". Проверьте, свободны ли клетки и есть ли к ним проход.");
if (pending != pending_drafts.end()) {
if (accepted && pending->revision == draft_revision) {
if (pending->room) {
const auto room = *pending->room;
const auto removed = std::find_if(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) {
return other.first == room.first && other.last == room.last &&
other.entrance == room.entrance && other.layout == room.layout;
});
if (removed != room_blueprints.end()) {
const auto index = static_cast<std::size_t>(removed - room_blueprints.begin());
if (room_draft_move) {
if (room_draft_move->index == index) room_draft_move.reset();
else if (room_draft_move->index > index) --room_draft_move->index;
}
room_blueprints.erase(removed);
}
}
if (pending->part) {
const auto part = *pending->part;
std::erase_if(blueprint, [&](const auto& other) {
return other.cell == part.cell && other.recipe == part.recipe && other.base == part.base;
});
}
}
pending_drafts.erase(pending);
}
if (accepted) {
placement_message = L"Команда выполнена.";
if (const auto* command = std::get_if<settlement::CommandPayload>(&payload)) {
if (command->kind == settlement::CommandKind::MoveObject && move_source == command->cell) {
move_source.reset();
}
if (command->kind == settlement::CommandKind::AssignProfession && selected_resident == command->resident &&
roster.pending_role == static_cast<Profession>(command->value)) {
roster.pending_role.reset();
if (roster.notice) SetWindowTextW(roster.notice, L"Профессия назначена. Житель закончит поручение.");
}
}
} else {
placement_message = (lan.is_guest() ? L"Передано хозяину мест: " : L"Утверждено мест: ") + count + L".";
placement_message = status == settlement::CommandStatus::Busy
? L"Объект занят. Дождитесь окончания работы или сна."
: L"Команда отклонена. Проверьте клетку и доступ к ней. Чертёж сохранён.";
}
if (rooms_sent != 0 && world->scenario_active() && !has_carpenter()) {
placement_message += L" Деревянные двери изготавливает плотник. Его можно назначить в списке «Жители».";
}
void reconcile_ticking() {
if (!session) return;
const bool network_host = lan->state() == LanState::Hosting || lan->state() == LanState::HostConnected;
session->set_ticking(!lan->is_guest() && !file_dialog_active &&
(network_host || (has_session && !showing_title && !pause_menu_open)));
}
void pump_session(HWND window) {
static bool pumping = false;
if (!session || pumping) return;
pumping = true;
struct Finish { ~Finish() { pumping = false; } } finish;
reconcile_ticking();
auto events = session->poll();
if (lan->is_guest()) {
if (auto incoming = lan->poll_guest()) {
session->receive_guest(std::move(incoming));
has_session = true;
}
} else if (lan->state() != LanState::Offline) {
lan->poll_host(session->runtime());
}
world = session->world();
for (const auto& event : events) {
switch (event.kind) {
case settlement::viewer::ViewerEventKind::Replaced:
clear_blueprints();
camera = {};
selected_resident.reset();
has_session = true;
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None, L"Поселение готово.");
if (std::exchange(host_after_replacement, false)) {
lan->host();
placement_message = L"Сетевая колония открыта. Адрес и код доступны в меню кооператива.";
} else {
show_title_screen(window, false);
}
sync_resident_roster(true);
refresh_lan_controls(window);
break;
case settlement::viewer::ViewerEventKind::Command:
if (event.payload) complete_command(event.command, *event.payload, event.status, false);
break;
case settlement::viewer::ViewerEventKind::Saved:
placement_message = L"Поселение сохранено.";
if (showing_title) title_screen.reload_saves();
break;
case settlement::viewer::ViewerEventKind::Fault:
case settlement::viewer::ViewerEventKind::Error:
host_after_replacement = false;
placement_message = widen_ascii(event.message);
break;
}
}
while (const auto result = lan->take_result()) {
const settlement::SessionPayload payload = settlement::CommandPayload{result->kind, result->cell,
result->value, result->destination, result->resident};
if (!guest_intents.empty()) {
const auto intent = std::move(guest_intents.front());
guest_intents.erase(guest_intents.begin());
if (intent.generation == session->generation() && intent.payload == payload) {
complete_command(intent.command, payload, result->status, true);
}
}
}
if (showing_title && enter_game_on_snapshot && !coop_menu_open &&
lan->state() == LanState::GuestConnected && world) show_title_screen(window, false);
if (lan->state() != displayed_lan_state) {
if (lan->state() == LanState::GuestDisconnected) {
pending_drafts.clear();
guest_intents.clear();
}
refresh_lan_controls(window);
}
if (world) sync_resident_roster();
update_blueprint_controls(window);
update_status();
reconcile_ticking();
invalidate_scene(window);
}
void edit_at_cell(HWND window, settlement::GridPosition cell) {
if (!can_give_orders()) return;
const auto held_world = world;
const auto generation = session->generation();
const auto installed_session = session->runtime().latest()->identity.session;
const auto network_generation = lan_generation;
const auto* connection = lan.get();
using settlement::CommandKind;
using settlement::CommandStatus;
using settlement::StorageKind;
@@ -1625,6 +1803,9 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) {
world->object_status(cell, false) == CommandStatus::Accepted &&
MessageBoxW(window, L"Снести склад вместе с его запасами?", L"Снос склада",
MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) != IDYES) return;
if (generation != session->generation() ||
installed_session != session->runtime().latest()->identity.session ||
network_generation != lan_generation || connection != lan.get() || !can_give_orders()) return;
} else if (placement_mode == PlacementMode::BerryField) {
command = CommandKind::PlaceBerryField;
} else if (placement_mode == PlacementMode::FlaxField) {
@@ -1639,17 +1820,8 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) {
StorageKind::Materials);
}
const auto result = submit_command(command, source, value, destination);
if (result == CommandStatus::Accepted) {
move_source.reset();
placement_message = lan.is_guest() ? L"Команда отправлена хозяину." : L"Готово.";
} else if (result == CommandStatus::Busy) {
placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна.";
} else {
if (command == CommandKind::MoveObject && world->object_status(source, true) != CommandStatus::Accepted) {
move_source.reset();
}
placement_message = L"Действие недоступно для выбранной клетки.";
if (submit_command(command, source, value, destination)) {
placement_message = L"Команда ожидает подтверждения…";
}
update_status();
invalidate_scene(window);
@@ -1671,22 +1843,17 @@ HMENU create_work_menu() {
void apply_resident_role(HWND owner) {
const auto* resident = selected_agent();
if (!resident || !roster.pending_role || *roster.pending_role == resident->profession || !can_give_orders()) return;
using settlement::CommandStatus;
const auto result = submit_command(settlement::CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(*roster.pending_role), {}, resident->id);
if (result == CommandStatus::Accepted) {
roster.pending_role.reset();
SetWindowTextW(roster.notice, lan.is_guest() ? L"Назначение отправлено хозяину." :
L"Профессия назначена. Житель закончит текущее поручение.");
} else {
SetWindowTextW(roster.notice, L"Не удалось назначить профессию.");
}
const bool queued = submit_command(settlement::CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(*roster.pending_role), {}, resident->id);
SetWindowTextW(roster.notice, queued ? L"Назначение ожидает подтверждения…" : L"Очередь занята.");
sync_resident_roster();
update_roster_details();
invalidate_scene(owner);
}
LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
const auto held_world = world;
try {
const auto owner = GetWindow(window, GW_OWNER);
switch (message) {
case WM_CREATE: {
@@ -1797,6 +1964,14 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam,
return 0;
}
return DefWindowProcW(window, message, wparam, lparam);
} catch (const std::exception& error) {
placement_message = widen_ascii(error.what());
InvalidateRect(window, nullptr, FALSE);
return 0;
} catch (...) {
placement_message = L"Не удалось выполнить действие.";
return 0;
}
}
void show_resident_roster(HWND owner) {
@@ -1879,14 +2054,13 @@ std::wstring resident_details() {
profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%";
if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой";
else if (resident->state == settlement::AgentState::Eating) text += L" Ест";
else if (resident->production_index != settlement::no_entity_index &&
settlement::is_carpentry_recipe(world->production_orders()[resident->production_index].recipe)) {
else if (world->find_production(resident->production_id) != nullptr &&
settlement::is_carpentry_recipe(world->find_production(resident->production_id)->recipe)) {
text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" :
L" Везёт материалы в мастерскую";
}
else if (resident->resource_node_index != settlement::no_entity_index &&
resident->storage_index == settlement::no_entity_index) {
const auto& site = world->resource_nodes()[resident->resource_node_index];
else if (resident->resource_node_id != 0 && resident->storage_id == 0) {
const auto& site = *world->find_resource_node(resident->resource_node_id);
const bool trees = site.site == settlement::ResourceSite::TreePlot;
if (resident->state == settlement::AgentState::Travelling) {
text += trees ? L" Идёт на посадку деревьев" : L" Идёт засевать поле";
@@ -2079,6 +2253,8 @@ settlement::viewer::SceneView scene_view(int width, int height) {
}
LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
const auto held_world = world;
try {
if (message == WM_NCHITTEST) return HTTRANSPARENT;
if (message == WM_ERASEBKGND) return 1;
if (message == WM_PAINT) {
@@ -2099,6 +2275,14 @@ LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPA
return 0;
}
return DefWindowProcW(window, message, wparam, lparam);
} catch (const std::exception& error) {
placement_message = widen_ascii(error.what());
InvalidateRect(window, nullptr, FALSE);
return 0;
} catch (...) {
placement_message = L"Не удалось выполнить действие.";
return 0;
}
}
struct MenuAction {
@@ -2249,17 +2433,18 @@ void open_pause_menu(HWND window) {
if (!world || showing_title || pause_menu_open) return;
camera_drag.reset();
if (GetCapture() == window) ReleaseCapture();
const bool offline = lan.state() == LanState::Offline;
const bool offline = lan->state() == LanState::Offline;
const auto interface_caption = L"Масштаб панели · " + std::to_wstring(interface_scale) + L"%…";
const MenuAction actions[] = {
{IDOK, L"Продолжить"},
{save_menu_id, L"Сохранить поселение…", !lan.is_guest()},
{save_menu_id, L"Сохранить поселение…", !lan->is_guest()},
{load_menu_id, L"Загрузить поселение…", offline},
{interface_scale_id, interface_caption.c_str()},
{title_menu_id, L"Главное меню"},
{exit_menu_id, L"Выйти из игры"},
};
pause_menu_open = true;
reconcile_ticking();
const auto action = choose_menu_action(window, offline ? L"Меню паузы" : L"Меню игры", actions);
switch (action) {
case IDOK:
@@ -2283,12 +2468,13 @@ void open_pause_menu(HWND window) {
break;
}
pause_menu_open = false;
reconcile_ticking();
if (IsWindow(window)) SetFocus(window);
}
void open_coop_menu(HWND window) {
std::vector<MenuAction> actions;
switch (lan.state()) {
switch (lan->state()) {
case LanState::Offline:
actions.push_back({lan_host_id, has_session && world && world->scenario_active()
? L"Открыть текущую колонию для друга…" : L"Создать сетевую колонию…"});
@@ -2316,10 +2502,9 @@ void open_coop_menu(HWND window) {
const auto action = choose_menu_action(window, L"Кооператив", actions);
coop_menu_open = false;
if (action == pause_button_id &&
(lan.state() == LanState::Hosting || lan.state() == LanState::HostConnected)) {
(lan->state() == LanState::Hosting || lan->state() == LanState::HostConnected)) {
static_cast<void>(send_command(settlement::CommandKind::SetPaused, {},
static_cast<std::uint8_t>(!world->paused())));
placement_message = world->paused() ? L"Сетевая колония на паузе." : L"Сетевая колония продолжает работу.";
InvalidateRect(window, nullptr, FALSE);
} else if (action >= lan_host_id && action <= lan_leave_id) {
handle_lan_menu(window, action);
@@ -2327,6 +2512,8 @@ void open_coop_menu(HWND window) {
}
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
const auto held_world = world;
try {
switch (message) {
case WM_GETMINMAXINFO: {
auto& size = *reinterpret_cast<MINMAXINFO*>(lparam);
@@ -2448,11 +2635,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
world && world->carpenter_workshop() && can_give_orders()) {
const bool is_furniture_order = LOWORD(wparam) != craft_door_id;
const int furniture_index = static_cast<int>(LOWORD(wparam)) - first_furniture_craft_id;
const bool accepted = is_furniture_order ? send_command(settlement::CommandKind::CraftFurniture, {},
const bool queued = is_furniture_order ? send_command(settlement::CommandKind::CraftFurniture, {},
static_cast<std::uint8_t>(furniture_products[static_cast<std::size_t>(furniture_index)])) :
send_command(settlement::CommandKind::CraftDoor);
if (accepted) {
placement_message = lan.is_guest() ? L"Заказ отправлен хозяину." : L"Заказ принят мастерской.";
if (queued) {
placement_message = L"Заказ ожидает подтверждения…";
}
SetFocus(window);
invalidate_scene(window);
@@ -2470,12 +2657,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
HIWORD(wparam) == BN_CLICKED) {
const auto choices = work_choices();
const auto index = static_cast<std::size_t>(LOWORD(wparam) - first_work_choice_id);
if (index >= choices.size() || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0;
if (index >= choices.size() || (lan->is_guest() && lan->state() != LanState::GuestConnected)) return 0;
SendMessageW(window, WM_COMMAND, static_cast<WPARAM>(choices[index].command), 0);
return 0;
}
if (LOWORD(wparam) >= berry_field_id && LOWORD(wparam) <= demolish_id) {
if (!world || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0;
if (!world || (lan->is_guest() && lan->state() != LanState::GuestConnected)) return 0;
constexpr PlacementMode modes[] = {PlacementMode::BerryField, PlacementMode::TreePlot,
PlacementMode::Mine, PlacementMode::Storage, PlacementMode::Pantry, PlacementMode::Move,
PlacementMode::Demolish};
@@ -2550,7 +2737,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
return 0;
}
if (LOWORD(wparam) == forage_action_id && HIWORD(wparam) == BN_CLICKED && world &&
(!lan.is_guest() || lan.state() == LanState::GuestConnected)) {
(!lan->is_guest() || lan->state() == LanState::GuestConnected)) {
set_placement_mode(window, placement_mode == PlacementMode::Foraging ?
PlacementMode::None : PlacementMode::Foraging);
SetFocus(window);
@@ -2729,49 +2916,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
}
break;
case WM_TIMER:
if (wparam == timer_id && world) {
const auto state = lan.state();
if (showing_title && (state == LanState::Offline || state == LanState::GuestDisconnected)) return 0;
if (!file_dialog_active && !lan.is_guest() &&
(state != LanState::Offline || (!showing_title && !pause_menu_open))) world->step();
if (auto snapshot = lan.poll(*world)) {
world = std::move(snapshot);
has_session = true;
}
if (showing_title && enter_game_on_snapshot && !coop_menu_open && lan.state() == LanState::GuestConnected) {
show_title_screen(window, false);
}
sync_resident_roster();
if (lan.state() != displayed_lan_state) refresh_lan_controls(window);
if (const auto rejection = lan.take_rejection()) {
using settlement::CommandKind;
using settlement::RecipeId;
const bool bed = rejection->kind == CommandKind::PlaceBed;
if (rejection->kind == CommandKind::PlaceRoom) {
const auto room = settlement::RoomPlan::from_placement(
rejection->cell, rejection->destination, rejection->value);
if (room.valid_size() && std::none_of(room_blueprints.begin(), room_blueprints.end(),
[&](const auto& other) { return other.first == room.first && other.last == room.last; })) {
room_blueprints.push_back(room);
update_blueprint_controls(window);
}
placement_message = L"Хозяин отклонил площадку. Комната возвращена в чертёж.";
} else if (bed || rejection->kind == CommandKind::PlaceLoom) {
if (std::none_of(blueprint.begin(), blueprint.end(),
[&](const auto& part) { return part.cell == rejection->cell; })) {
blueprint.push_back({rejection->cell, bed ? RecipeId::BuildBed : RecipeId::WeaveCloth,
static_cast<settlement::BedBase>(rejection->value)});
update_blueprint_controls(window);
}
placement_message = L"Клетка отклонена хозяином и оставлена в чертеже.";
} else {
placement_message = rejection->status == settlement::CommandStatus::Busy
? L"Объект занят. Дождитесь окончания работы или сна."
: L"Хозяин отклонил команду. Проверьте выбранную клетку.";
}
}
update_status();
invalidate_scene(window);
if (wparam == timer_id) {
pump_session(window);
return 0;
}
break;
@@ -2810,7 +2956,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
}
case WM_DESTROY:
KillTimer(window, timer_id);
lan.leave();
lan->leave();
graphics.reset();
if (dock_font) DeleteObject(std::exchange(dock_font, nullptr));
scene_window = nullptr;
@@ -2818,11 +2964,26 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
return 0;
}
return DefWindowProcW(window, message, wparam, lparam);
} catch (const std::exception& error) {
placement_message = widen_ascii(error.what());
InvalidateRect(window, nullptr, FALSE);
return 0;
} catch (...) {
placement_message = L"Не удалось выполнить действие.";
return 0;
}
}
} // namespace
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
try {
session = std::make_unique<settlement::viewer::ViewerSession>(local_worker_count);
} catch (const std::exception& error) {
const auto text = widen_ascii(error.what());
MessageBoxW(nullptr, text.c_str(), L"Не удалось открыть поселение", MB_OK | MB_ICONERROR);
return 1;
}
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES};
InitCommonControlsEx(&controls);
WNDCLASSEXW window_class_info{};
@@ -2853,5 +3014,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
session.reset();
return static_cast<int>(message.wParam);
}
+18
View File
@@ -75,3 +75,21 @@ wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag
```
Далее в M01 входят исполнитель Void с проверкой отказов, манифесты правил, авторитетный диспетчер команд, фоновый такт, снимки и транзакционная загрузка/запись. Приёмка этих систем ведётся отдельными коммитами.
### Ветки разработки и запросы на слияние
Для этапов используются ветки `milestone/*`, для систем — `system/*`. По поручению пользователя ветка [integration/roadmap](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/src/branch/integration/roadmap) содержит `chore/integrate-void-library`, `chore/plans` и принятые изменения каждой ветки этапа и системы. После проверки совместной сборки ответственный обновляет накопительную ветку. Она служит для получения всей работы одним checkout.
У каждой опубликованной рабочей ветки есть свой запрос в `main`. Описание ссылается на более ранние запросы этой серии. При параллельной работе подписи ссылок указывают, какие изменения послужили базой и какие развивались независимо. Новые коммиты ветки попадают в уже открытый запрос. Первыми открыты [VoidLibrary #3](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/3), [план #4](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/4), [M00 #5](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/5), [M01 #6](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/6), [модули правил S19 #7](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/7), [исполнитель S01 #8](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/8), [диспетчер S16 #9](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) и [сохранения S15 #10](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/10).
В `2224299` вместе собраны снимки мира, диспетчер команд, служба записи и кодек контрольных точек. Windows x64 Release под Wine прошла 82 из 82 случаев ядра и 4 из 4 LAN. Отдельная ветка S15 на `db4ac30` прошла 59 из 59 и 4 из 4 соответственно. По трём прогонам на поле 80×80 с шестью потоками медианы p50/p95 захвата снимка составили 2/4 мкс для 50 жителей и 23/68 мкс для 500. После 32 тактов прогрева каждый прогон измерял 240 захватов. При подключении службы записи к окну лимит одного файла должен вмещать `max_checkpoint_bytes`. Частота тактов, отзывчивость окна во время записи и работа на физической Windows проверяются отдельно. [Проверка команд и записи](tasks/M01-V4.md) · [Проверка снимка и контрольной точки](tasks/M01-V5.md) · [Совместная сборка](tasks/M01-V6.md) · [План постоянных ссылок](tasks/M01-P3.md)
В `cf0cc2f` объединены проверенные коммиты S19 `de38aff` и S01 `68f91a2`. После объединения под Wine 11 прошли 51 из 51 теста ядра и 4 из 4 тестов LAN, включая формат сохранений 13 и протокол 11. Независимый проверяющий сверил обе родительские версии, наследование параметров компиляции и встроенную реализацию SHA-256. [План владельца симуляции](tasks/M01-P2.md) · [Проверка библиотеки](tasks/M01-R2.md) · [Разбор отказов](tasks/M01-F2.md) · [Принятые контракты](tasks/M01-F3.md) · [Проверка S01 и S19](tasks/M01-V2.md) · [Проверка интеграции](tasks/M01-V3.md)
Срез S06 сохранил ссылки на склады и источники при удалении более раннего элемента. Два контрольных набора из 738 386 и 393 857 байтов совпали со старой сборкой в последовательном режиме и на 2/6/12 потоках. Второй набор включает разбор склада во время многоэтапной доставки. Изменения опубликованы отдельно в [S06 #11](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11). В `4ba64f7` также вошла фоновая подготовка старых и новых сохранений. В объединённой Windows x64-сборке под Wine прошли 106 тестов ядра и 4 LAN. Публичный аналог ограниченного чтения в Windows отслеживается в [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). [Проверка двух компонентов](tasks/M01-V8.md) · [Интеграционная проверка](tasks/M01-V9.md)
Хост протокола 11 теперь передаёт приказы авторитетной симуляции, а гость получает подтверждение и снимок завершённого состояния. После смены сеанса старому гостю требуется новое подключение. Старая и новая сборки обменялись приказами в обеих ролях. В `aa4e271` под Wine прошли 106 из 106 тестов ядра и 9 из 9 LAN. Отдельно проверены переподключение при незавершённом приказе и разные правила нумерации отклонённых приказов у старого клиента и нового владельца. [Ветка S16](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) · [Проверка интеграции](tasks/M01-V10.md)
В `a8cd7bb` объединены заказы с постоянными ID и два варианта правил строительства кровати. Формат контрольной точки 2 сохраняет ID заказов и следующий свободный ID. Прежние контрольные точки и обычные сохранения версии 13 продолжают загружаться. Оба варианта правил прошли строительство реальных кроватей, сохранение во время доставки и сравнение продолжений на 1/2/6/12 исполнителях. В объединённой сборке под Wine прошли 122 теста ядра и 9 LAN. Аппаратная Windows ещё не проверена. [Заказы S04](../plan/systems/S04.md) · [Правила S19](../plan/systems/S19.md) · [Интеграционная проверка](tasks/M01-V11.md)
Клиент Windows в `db0a872` обрабатывает действия игрока по квитанциям владельца и рисует из неизменяемого снимка. Три отдельных процесса под Wine проверили создание партии, паузу в меню и окне выбора файла, запись, современное и прежнее сохранения и отказ при повреждении файла. Отдельно проверены подтверждение разбора при смене партии, сохранение гостевой колонии после неудачного переподключения и возобновление тактов после восстановления. В общей сборке прошли 122 теста ядра, 9 LAN и 10 клиента. [Клиент S18](../plan/systems/S18.md) · [Проверка с обеими родительскими ветками](tasks/M01-V10.md)
+48
View File
@@ -0,0 +1,48 @@
# Preflight the rules, executor and authoritative runtime packages
Task ID: M01-F2
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home on milestone/m01-authoritative-simulation, M00 at 904bdf8, M01 serial tranche under separate final review. User authorized the entire roadmap with remote pushes by milestone/system.
## 2. Objective and deliverables
Check next M01 system contracts before implementation. Prioritize a verdict for independent S19 rules and S01 Void pool migration, then S16 authority, S15 persistence and S01 viewer runtime.
## 3. Scope and non-goals
Review technical design/failure boundaries and independent branch ownership. Later M02+ behavior is outside this preflight; the existing prototype remains runnable while these staged features integrate.
## 4. Files to inspect
Inspect plans M01, S01/S15/S16/S19, world.hpp/cpp, world_save.cpp, app/viewer_win32.cpp, app/lan_session_win32.cpp, engine/include/settlement/core/worker_pool.hpp, CMakeLists.txt. For Void check docs/plan/void-library.md and exact pin headers selected below.
## 5. Write ownership and coordination
Write scope: none
Root owns checkout and branches. Separate system worktrees will isolate CMake/test changes; no new child agents.
## 6. Implementation or investigation approach
S19 proposed bounded UTF-8 strict JSON manifest with namespaced IDs, schema+SemVer versions, definitions/references, dependencies, exclusive capabilities and recomputed per-package SHA256. A selected installed set is transitively resolved, duplicates/missing/range incompatibility/cycles/exclusive conflicts/unknown definitions rejected. Canonical encoding sorted by stable IDs plus exact SemVer incl build and digest frozen with a world/save/network. Reuse Void::Json::Strict, Semver, Algorithms graph and Crypto or report target blockers. Test actual input, deterministic permutation, malformed bounds, meaningful differences. S01 worker migration uses exact-pinned ThreadExecutor and FuturePool with overload retention, startup failure cleanup, draining accepted futures before captured locals unwind, reference and pressure tests plus measured useful work.
## 7. Interfaces and data contracts
S16 proposal: single host dispatcher, trusted transport identity separate from payload, world/session/city/request identity, exact repeat receipt for same payload, conflicting replay/stale epoch has no effect; validation and mutation on owner thread. S01 timer runs fixed interval and publishes shared immutable completed state, live local/guest commands and read-only viewer no longer step/mutate an authoritative World from WM_TIMER. S15 validated candidate swap increments epoch even on rollback, bounded asynchronous immutable snapshot writing, atomic same-volume publication leaves previous data after failure. Rule selection persists + validated before live replacement. Existing sav13/LAN11 continue only by explicit compatibility surfaces.
## 8. Dependencies and integration
M01-P2 maps game code, M01-R2 verifies APIs: SemVer == ignores build so frozen identity uses exact version; Graph input ordering must be canonical. FileSystem atomic_write is unsupported on Windows: an upstream gap issue precedes local fallback. Root integrates M01 branches; public pushes separately authorized.
## 9. Edge cases security and performance
Consider also capturing mutable UI references/exceptions, pool draining and useful equality after queue pressure, concurrent load/save identity and stale worker results, bounded journal/receipt identity/windows old files. Identify native-only checks explicitly.
## 10. Acceptance criteria
1. Prioritized READY or blockers for S19, S01 pool, and architecture for S01 runtime/S15/S16. 2. Concrete failure/ownership/test requirements and needed refinements. 3. Distinguish M01 goals from M09 public coop/1.0 packaging.
## 11. Verification commands and evidence
From game root git diff 904bdf8 --stat; rg -n 'WM_TIMER|read_save|write_save|try_submit|worker_pool_|apply_command' engine app; consult actual upstream pinned StrictJson/Semver/Graph/Crypto/FuturePool public APIs and local source as needed. No writes or builds.
## 12. Constraints and stop conditions
Send S19 and pool verdicts early; flag material decisions and applicability. No file edits, external actions, or child agents.
## 13. Authorization and decisions
The user authorized implementing the full plan with subagents, commits and pushes. Root retains integration and system approval.
## 14. Return format
Return M01-F2 priority verdicts per package, actionable severity/location/contract fix, tests required, deferred compatibility/work. Do not review your own implementation.
+48
View File
@@ -0,0 +1,48 @@
# Confirm the exact authority, failure and publication boundaries
Task ID: M01-F3
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation 8d2870a. M01-F2 identified four gaps. S01 pool and S19 running in separate worktrees. Upstream issues 3/4/5/6 are registered in Void/Library.
## 2. Objective and deliverables
Verify the root's concrete decisions below close F2's open failure/identity/order points for starting S16 dispatcher, S15 writer and dependent runtime. Design review only.
## 3. Scope and non-goals
Cover S16/s15 independent modules and next runtime ownership, preserved legacy behavior. No release or M09 network exposure.
## 4. Files to inspect
Read docs/agent-workflow/tasks/M01-F2.md, docs/plan/milestones/M01.md, S01/S15/S16, World::apply_command, worker submissions, app/viewer_win32.cpp legacy save/poll/queue cabin and LAN11.
## 5. Write ownership and coordination
Write scope: none
Root owns decisions; no child or shared mutation.
## 6. Implementation or investigation approach
S16 per active epoch: trusted transport passes known client slot separately from payload. World/session are nonnil Void UUIDs, city ID checked. Each authenticated client has monotonically contiguous request numbers starting at 1. Retain every completed result (including rejections) for the active epoch; reserve the record before mutating; check status/city/kind/entire payload equality. On capacity there is backpressure on NEW requests before effects, older cached receipts remain replayable, no eviction/reexecution. Requests behind missing/out-of-order and wrong epoch have distinct transient/nonmutating errors. Envelope ID maps to existing World next sequence only after validation, preserving legacy rejected-reusable sequence behavior. Clients choose new numbers for revised intents. Per-session ledger cap is configurable and explicit. Fresh session discards old history after successful replacement; old envelopes fenced.
## 7. Interfaces and data contracts
S15 independent FIFO bounded single-writer service accepts materialization from a held immutable snapshot, serializes in background, bounded admission returns busy, Windows same-directory exclusive temp + write/flush/close + atomic publication; distinguish before/after visibility. Queue is serialized at admission across slots, so older same-slot save cannot finish after a newer one. Each completion identifies request/tick/epoch; latest UI state checks request ID. Shutdown drains accepted work. Input prepare/validate outside owner; replace only when matching expected old epoch and most recent load request. Corrupt/superseded load changes nothing.
## 8. Dependencies and integration
S01 runtime single simulation owner processes bounded requests also during pause and publishes an immutable independent World copy tagged with world, session, tick and publication revision including changes at the same tick. Stage tasks all drained before stack unwind. On ANY tick, command or snapshot preparation failure keep previous published snapshot and discard faulted mutable candidate; no success receipts are exposed for uncommitted changes. Runtime enters faulted and rejects saves/commands until an explicitly validated load restores coherent state under a fresh epoch. UI direct queue_cabin and LAN mutations route through owner; legacy wire stays separate. S19 immutable manifest part of checkpoint compatibility. Root owns interfaces.
## 9. Edge cases security and performance
Do not silently evict exact-repeat results or claim power-loss guarantees. Check constraints for denial of access or unsupported administrative features. Long-session journal storage beyond M01 replaceable bound documented. Root will record recovery outcome and tests.
## 10. Acceptance criteria
1. Return READY or scoped correction for S16 and S15 first, followed by runtime. 2. List exact stalled/failed operation behavior. 3. Identify remaining prospective tests in rollback, queue capacity, duplicate and concurrency scopes.
## 11. Verification commands and evidence
From game root git show -s --format=%H, rg -n 'save_world_file|queue_cabin|World::apply_command|World::step' app engine, inspect referenced existing contracts; no runtime build needed.
## 12. Constraints and stop conditions
No edits, branch changes, external writes, children or duplicate investigation. Send early if S16/S15 ready.
## 13. Authorization and decisions
Full roadmap approved. Root requested this follow-up specifically to resolve M01-F2 before starting those packages.
## 14. Return format
Return M01-F3 READY/CHANGES_REQUIRED per scope with any remaining actionable failures and tests; no edits.
+48
View File
@@ -0,0 +1,48 @@
# Preflight the real Win32 client, file and LAN owner adapters
Task ID: M01-F4
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root a4cf99c contains all independently reviewed primitives. S01-04 implementation in /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 at 2224299 awaiting review; public header and 10 tests exist. Planner M01-P2 and preflight F3 defined owner; current WM_TIMER still steps mutable world, saves synchronously and LAN11 poll writes directly.
## 2. Objective and deliverables
Check precise adapter design for normal Win32 UI, asynchronous checkpoint files and existing two-slot LAN11, then give per-package green lights or bounded corrective requirements.
## 3. Scope and non-goals
Read-only M01 client wiring; existing public co-op compatibility and file use. No new public transport, encryption protocol or broad SDK. Existing S16 modern envelopes can be exercised with 2 internal clients; public network roadmap continues later.
## 4. Files to inspect
Inspect actual runtime public header + owner implementation in s01 checkout; viewer_win32.cpp WM_TIMER, start/stop/menus/new/load, local command reporters/blueprint rejection, title_screen; lan_session.hpp/.cpp protocol11 command/sequence/reconnect/send_snapshot, lan_wire; S15 checkpoint/save_service, initial rules catalog and document plan M01.
## 5. Write ownership and coordination
Write scope: none
No mutations, builds, shared Serena switches, branch/remote ops or children. Parent owns produced contracts and commits.
## 6. Implementation or investigation approach
File adapter (S15) uses one bounded Void background reader and approved SaveService (max_checkpoint_bytes). Caller obtains healthy published snapshot once; producer owns it and encodes on writer thread. Asynchronous load prepare from path/catalog only, with bounded bytes/check signatures, read one open file, legacy World::read_save migrates to new stable UUID/city+default rules; current envelope validates exact installed closure. Keep current 32x32 viewer dimension gate outside generic codec and validate before install. Futures retain immutable data, no background Win32 calls or raw runtime/viewer pointers. Shutdown drains. UI binds a runtime LoadTicket to each admitted load and rejects stale completions by epoch+latest request; report latest save/load per UI slot/request and older save completions must not overwrite newer status.
## 7. Interfaces and data contracts
LAN11 adapter (S16) keep existing poll(World&) entry/test; add preferred asynchronous host path driven by SimulationRuntime and a guest-only poll requiring no mutable authority. Maintain same exact frames/signature/2 trusted slots. Check authenticated wire request. Legacy numeration is World::next_command_sequence and ordinary domain rejections leave it live, while new envelopes use runtime published next_requests per slot including rejections. Compare incoming wire seq and use authenticated guest slot, serialize per-peer in-flight command so no stale snapshot mapping/multiple executions; return receipt only after committed outcome, current correct next wire sequence. Disconnect/generation/guest changes discard pending network completions without moving effects into new session. Never block network/UI waiting for owner. Exclude new public endpoint. Add verified real host/guest loopback via async path including wrong sequence, rejection and subsequent corrected same old number, reconnect. Keep original fixtures/binary interoperability.
## 8. Dependencies and integration
Viewer milestone adapter: one shared_ptr<const World> consistent view (hold for entire frame including nested messages), one SimulationRuntime for offline/host. Guest consumes incoming const views only, transient old host connection fenced. WM_TIMER polls completions/views/network rather than advancing world. New colony/reset creates valid UUID+selected default-compatible manifest; expose real choice where alternative installed packages materially alter game creation (no cosmetic selector). Existing host authority/pause/title/file-dialog gating via set_ticking independent of World::paused; retries when Busy and don't flood queue. Local mutations incl legacy cabin route through runtime. UI needs acknowledged result before applying accepted-only changes; queue/futures and pending metadata reinsert blueprint or report typed rejection, FIFO contiguous modern IDs, handled Busy/OutOfOrder; snapshots can lag while multiple local inputs are pending. Ensure reads and command submission never block on a long tick. Keep modern save normal UI path; legacy saves still load deliberately.
## 9. Edge cases security and performance
Pay particular attention to Win32 reentrancy, old futures crossing reset/load, modal pickers, latest load after failed reading vs superseded earlier good, rollover UI state if save job from old session finishes, in-flight bounds and trusted peer rebind. A non-default rules subset must be truly compatible with hard-coded prototype game until more rule-driven mechanics land. Avoid accepting incompatible content silently or rejecting legacy corrected retries.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per file adapter, LAN and UI. 2. Concrete interface+tests for each, required handoff order and where existing code enforces assumptions. 3. Clarify what is safe to dispatch immediately and any consequence requiring product choices.
## 11. Verification commands and evidence
git status --short --branch, scoped rg -n 'WM_TIMER|world->step|handle_save_menu|submit_command|queue_cabin|handle_host|poll\(' app, read targeted actual source. No builds needed. Existing combined 82 core+4 LAN, S01-04 adds ten. Current CLI old baseline cross-version harness /tmp/stoneheart-verify.KoZwE4o8/interop.cpp.
## 12. Constraints and stop conditions
No edits, external actions or other agents; no extension to public LAN protocol or unwanted UI. Report any ambiguous scope to parent rather than blocking independent file service.
## 13. Authorization and decisions
User authorizes all milestones, prior planner/preflight resolved ownership; this concerns concrete client integration choices within M01. Parent handles branches and git operations.
## 14. Return format
Return M01-F4 verdict per package, exact corrections and compatibility tests, optional future distinction where implementation depends on another unbuilt seam.
+48
View File
@@ -0,0 +1,48 @@
# Recheck concrete client and peer lifecycle contracts
Task ID: M01-F5
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Main at 512c9ef, previous F4 approved S15 and identified two LAN and three UI gates. Revisions are in /home/faumaray/Projects/stoneheart_at_home-worktrees/{s16,s18}/docs/agent-workflow/tasks/{S16-02,S18-01}.md. Runtime header is integrated; CheckpointFiles header is real in s15.
## 2. Objective and deliverables
Check added conditions against F4 findings for early per-package approval before implementation.
## 3. Scope and non-goals
Read-only recheck of contract adequacy, no review of future LAN/UI implementation. S15 already implementing.
## 4. Files to inspect
Read two task documents, M01-F4, normal Win32 title/timer/guest reset and LAN drop_peer lifecycle and actual runtime/CheckpointFiles headers. Match earlier evidence.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote requests/Git actions/children.
## 6. Implementation or investigation approach
Verify LAN default-only manifest gate, epoch reconnect, independent receipt tracking across peer turnover, legacy next sequence vs modern committed id and nonblocking completions. Verify viewer completion pump precedes all title returns, no old runtime joins blocking reset/new/join, one writer, receipt-driven bounded one-in-flight queue and profile guard, load supersession and safe guest/offline transition.
## 7. Interfaces and data contracts
Review exact contract not summaries. Flag any missing precondition or undefined API behavior that prevents a worker from safely implementing a nonblocking compatible host/client.
## 8. Dependencies and integration
F4 read-only reviewer pre-existing; parent will perform integration after independent implementation. Root ensures reviewed sibling dependencies available to S18.
## 9. Edge cases security and performance
Watch stale future from disconnected client, latest failed load, modal reentrancy, old/new slot file ordering and unsupported manifest advertising. Genuine alternative module selection and texture/keyboard features are independently scheduled.
## 10. Acceptance criteria
1. Separate READY/targeted correction per S16/S18. 2. Bound any remaining actual gap and verification needed. 3. No implied release or approval to merge remotely.
## 11. Verification commands and evidence
Read actual tasks including ownership, tests and stop gates and inspect relevant source from F4. git show 512c9ef --stat optional; no build required.
## 12. Constraints and stop conditions
Read only. Return LAN early if adequately scoped. Stop only for a material remaining omission.
## 13. Authorization and decisions
Root requests this F4 follow-up after exact corrections and user has authorized roadmap. No remote writes.
## 14. Return format
Return M01-F5 S16 and S18 READY/CHANGES_REQUIRED with evidence and residual concrete runtime/native checks.
+48
View File
@@ -0,0 +1,48 @@
# Recheck production identity safety and preflight a selectable colony rule
Task ID: M01-F6
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root at 60154bd. S04-01 contract in s04 checkout (4ba64f7) includes the two M01-V9 findings. In S19 M01-P4 examines new world profile selection reusing existing simple vs staged bed paths. Default built-in manifest content must remain compatible.
## 2. Objective and deliverables
Immediately recheck S04 exact guards and, separately, preflight the first selectable rules behavior with a validated default/legacy compatibility policy. No actual code review or implementation.
## 3. Scope and non-goals
Read-only S04-01 revised contract and S19 feature preflight. Exclude further stack/transfer/production implementation.
## 4. Files to inspect
Inspect s04/docs/agent-workflow/tasks/S04-01.md sections 6–10 and World::edit_object/CommandDispatcher::apply. For S19 read M01-P4, world.cpp bed construction, legacy codec/staged flag, generator/first_colony, rules_manifest, runtime/file/load and default-only LAN contracts. Implementation worktrees outside main have direct read evidence.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children or shared Serena activation. Other workers continue on their own files.
## 6. Implementation or investigation approach
S04 confirm hypothetical exhaustion guards precompute post-demolition totals exactly across all affected supplies before erasing or queue changes, preserve accepted receipt semantics for proved cabin preflight Busy separately from mutation faults. Genuine v1/body1–13 and current2/14 mapping, negative checks and older file test version. Send scoped approval immediately if corrected.
## 7. Interfaces and data contracts
S19 proposal: compiled default first-colony behavior stays staged recipes and two-package original frozen manifest, content digest unchanged; optional exact pinned, additive package selects existing simple/plank recipe path at world creation. Encode enacted policy in World at initialization, existing staged_beds state and manifest saved, normal creation can choose default/alternative. Add game-specific supported profile compiler using actual typed data and package closure; reject unsupported modified digest before installation by viewer, generic resolver/decoder retains broad catalog tools behavior. Important: previous v1 checkpoints and imported historical worlds could legitimately carry DEFAULT manifest with staged_beds=false, and inactive world is valid. Describe migration rule that preserves these old states/bytes; distinguish strict alternate invariant from accepted old default data, and verify clean subsequent saves on current envelope. Future S19/UI APIs and compatibility choices from M01-P4 confirmed by root prior to implementation.
## 8. Dependencies and integration
S04 and S19 can use isolated branches; parent serializes shared World/factory/file semantics and S18 normal UI selector after core approval. Keep legacy LAN default-profile-only and preserve old default digest/test fixtures. Do not equate illustrative board ticks=8 with actual compiled tick count.
## 9. Edge cases security and performance
Check nonempty real colony resources/producer/receipt for both bed paths, UI stone vs wood selection, immutable held snapshot and save-load continuation, partial bed materials, old format 1–13 valid imports, malformed optional profile/default unknown package gate, credible negative tests. No fabricated ACE parity.
## 10. Acceptance criteria
1. Separate S04 corrected or material outstanding. 2. S19 preflight verdict with explicit compatibility and required exact negative/normal tests. 3. Record what can proceed with certainty and facts needing further root commitment.
## 11. Verification commands and evidence
Read actual source/contract targets and M01-P4; compare default manifests/code and World legacy flags; no build required. Check git status/refs to identify exact code.
## 12. Constraints and stop conditions
Read only. Return S04 verdict immediately then S19. No new external service or changes to accepted user scope.
## 13. Authorization and decisions
Root requests follow-up after exact S04 corrections and planner-backed S19 technical preflight. User authorizes signed-off coding only through root.
## 14. Return format
Return M01-F6 two scoped verdicts with evidence, precise blockers/solutions and pending real integration tests.
+50
View File
@@ -0,0 +1,50 @@
# Check the contract for atomic reserved pickups and client rule selection
Task ID: M01-F7
Role: astra_reviewer
Status: READY
## 1. Context and baseline
M01 parent 9a248c3 has S19-02 compiled profile and S06-ID data. S04-01 adds production identities and body14 in isolated s04. S18-01 canonical client still in isolated s18 resolving modal input findings. M01-P5 proposed a bounded reserved-quantity pickup used by actual meal and construction stops.
## 2. Objective and deliverables
Preflight the first S06 quantity transaction and bounded S18 followup that wires approved profile to the New/Load/Host UI. Return separate actionable corrections before component implementation.
## 3. Scope and non-goals
The S06 step preflights a single existing storage→resident pickup atomically, including all materials at one construction stop. Later stack identity, cancel, site ownership and replay ledger remain P5-dependent. S18 selection is only New colony and coherent support/legacy compatibility; no new game settings or traffic.
## 4. Files to inspect
Read root world.hpp, world.cpp functions finish_meal_step/advance_construction_delivery/take_reserved_material/finish_production, profile public API/first_colony/tests, s04 working diff and actual s18 viewer_session/viewer_win32/title_screen, LAN default gate, docs S04/S06/S18/S19 and M01-F6.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posts/other agents or Serena switch. Root decides subsequent contracts and serializes worktrees/CMake changes.
## 6. Implementation or investigation approach
S06 proposed NEW internal bounded reserved pickup with one validated StorageId per operation, max item_type_count distinct items (all lines at stop aggregated before any mutation), reject zero/None/unknown ID, reserved>physical, insufficient reserved/quantity or target sum overflow using Void::Numeric; commit all source counts/reserve/zero-stack removal/destination changes without further allocation or throwable effects. Success keeps meal, route cursor, order/worker behavior and v13 projection/corpora unchanged. Failure immediately leaves source+inventory and stop/actor bookkeeping unchanged; impossible invariant failure may fault owner while preserving last healthy publication. Existing non-pickup recipe paths must be accounted for. Identify any missing edge or side effect.
## 7. Interfaces and data contracts
S18 followup proposed initial selector defaults staged, allows existing alternative single plank profile in title New, Continue/Open ignores current selection; factory+validator before runtime construct and after latest load prepared, preserve exact default old simple/inactive, refuse forged/extra or optional staged, both immediate and deferred legacy-host gates require exact default, failed admission leaves world/guest unchanged. Rename/conditionally hide staged base UI choices in plank-only worlds; confirm existing placement validation behavior. Verify title keyboard/mouse handling and no accidental persisted settings.
## 8. Dependencies and integration
Depends on S19-02 and S18-01 review, S06-02 first consumer should merge after S04-01 with tests and version untouched. Root will own separate follow-up schema migration and M01-P5 final decisions; legacy cancellation compatibility remains.
## 9. Edge cases security and performance
Check non-throwing commit including vector erase/multi-type and destination Inventory bounds, zeros/duplicates, capacity reserve for carpentry and any work cursor mutation. Check modal callbacks/error feedback, unsupported profiles advertised to LAN, save/restore exact active legacy mode.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per contract before dispatch. 2. Concrete trigger and correction for any inconsistency. 3. Exact tests that would fail on a partial batch and incorrect selection or post-load gate. The stages do not approve future implementation.
## 11. Verification commands and evidence
Read-only git status/rev-parse at each worktree, scoped rg and direct source/graph coverage. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{tag,ctest}.log and existing client-session/GUI smoke source if needed. No new builds.
## 12. Constraints and stop conditions
No new general inventory database, domain mechanics or UI expansion, no duplicate library issues. Report prerequisites immediately; defer review of actual changes until implemented. No charges/remote operations.
## 13. Authorization and decisions
User authorizes all milestones, including stable single-owner items, selectable new rules, per-branch publishing and generic Void issues. Root retains mutation authority.
## 14. Return format
Return M01-F7 PREFLIGHT disposition for S06 and S18 separately; exact invariants/tests and any blocking oversight backed by existing source.
Preflight required the pickup owner to validate the post-withdrawal occupancy and the carpentry output slot together, aggregate repeated lines, and preserve the state at pickup entry on rejection. Direct storage-to-recipe conversion keeps its own path. For profile selection, deny starting a legacy host while a replacement is pending, recheck after a modal menu, then check the installed authoritative default manifest immediately before either host call. The simple-bed house preview must describe the actual one-plank recipe for every house type.
+48
View File
@@ -0,0 +1,48 @@
# Preflight durable custody, legacy projections and replay limits
Task ID: M01-F8
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root e6a01be includes production IDs, current14/outer2, compiled profiles and verified initial viewer. Quantity batch now ready in isolated s06 at a8cd7bb + changes. Detailed operational proposal from M01-P5 in NEW docs/plan/custody.md. This prescreen concerns the next persistent state model, not approval of implementation.
## 2. Objective and deliverables
Examine the complete proposed data/operation/migration contract and find contradictions before assigning parallel core/codec/command owners. Provide first specific corrections quickly and feasible independent interfaces.
## 3. Scope and non-goals
Only S06/S04 custody, bounded receipts, migration from raw1–14, v15/outer3, cancel and LAN legacy projection. Existing numeric/ID tickets #7/#8, duplicate support and preflight-before-mutation apply. No new gameplay or schema publishing yet.
## 4. Files to inspect
Read root docs/plan/custody.md, tasks M01-P5/F6/F7, world.hpp, world.cpp, world_save.cpp (codecs, route/phase validation, old limits), checkpoint*, command_dispatcher*, simulation_runtime, actual app/lan_session_win32.cpp legacy publication and viewer costs; s06 new transaction source/consumers. Check existing fixtures and acceptance corpus.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posts/other agents or Serena switch. Root owns public actions and serializes source. Look at actual code, modern replay and schema context, consulting direct worktree sources for S06.
## 6. Implementation or investigation approach
Check embedded unique stack identities, split/merge and reservation movement, checked monotonic world counters and batch preflight, one owner including production input, exact custody for resources, all recipes, grants, meals, canceled work and demolition, capacity claim backed by claimed input, no double-used space. Verify same-type lines and multiple source warehouses vs number-of-item-types limit; coordinate strict modern validation with real legacy accepted data. Specify robust migration for Working site, completed orders still carrying outputs without inventing supplies, raw import opening balance and modern projection of unrepresentable payloads.
## 7. Interfaces and data contracts
Admitted execution TransferId with ordinal, retained exact input+result 4096 entries <=1KiB each part, remaining earlier ordinals stale forever under high-water; root accepts schema15/outer3, checked before-effect refusal vs stored admitted rejection. Establish how an exact retry of *creation/admission itself* is recognized across crashes if caller has not yet been given a TransferId; when legitimate repeated blocked work consumes ordinals; persisted capacity/hash checks, session/world identity during timeline rollback and monitor snapshot cost.
## 8. Dependencies and integration
Core/registry implementation may be parallel with fixtures/validator/serializers only after exact public/internal data shapes agreed. Recommend useful checkpoints and ownership for S06 main data, S04 ledger/cancel and S16 unsupported legacy state. Normal v13/LAN11 baseline must match; unsafe-fallback exception must be caught before session UI/network effects, preserving live host. Choose measurable memory/latency acceptance.
## 9. Edge cases security and performance
Watch O(N²) owner+claim search, cross-transaction side effects after allocations fail, receipts shallow copies shared mutable in published snapshots, reparent/merge alias lifetime, callable external mutation through current prototype Inventory/Storage APIs, new IDs exhausted during split/recovery. Inspect resource-harvesting branch and raw1-8 sleep import logic. Legacy loader may accept snapshots with unused/trailing projected route metadata; avoid pathological blanket rejection of genuine saves.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED plus specific contract amendments. 2. Bound request/replay/IDs and failure atomicity at ordinary world hot paths. 3. Identify data-shape necessities for accurate P5 legacy import and modern pollution rejection. 4. Specify earliest branch-safe real end-to-end migration stage. 5. Name concrete validation tests that catch each risk.
## 11. Verification commands and evidence
Read-only git status/rev-parse, graph search/trace and coverage for cited root paths, direct missed ranges. Check core/profile/production/identity/construction tests and raw serializer fields; no builds necessary. Existing logs in /tmp/stoneheart-milestones.xprJ2SVp.
## 12. Constraints and stop conditions
No new generic public dependency/remote issue unless actual gap separate from #7/#8 is identified; root handles filings. Stop to report actual contradictions, keep analyzing independent parts. Do not review or edit the code of another upcoming assignment.
## 13. Authorization and decisions
User authorizes complete implementation; root accepted pre-admission vs admitted rejection accounting, modern CancelProduction by durable ID, raw13 UnsupportedLegacyState and retained exact 4096 receipts, immutable stacks with a single quantity source, and input-backed capacity claims, subject to technical feasibility.
## 14. Return format
Return M01-F8 PREFLIGHT verdict, concise exact corrections, schema and ownership constraints, regression fixtures and performance risks.
+48
View File
@@ -0,0 +1,48 @@
# Preflight independent renderer frames and deterministic completion replay
Task ID: M01-F9
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root M01 66af7c5 includes client b7f18c0, current14, S06 atomic pickup. M01-P6 planner inspected current Win32/worker paths. Actual WM_TIMER pumps every 60 ms, scene packets borrow spans and camera-only paint rebuilds flat D3D mesh, while 20 Hz runtime is independent. Replay covers serial/2/6/12 and last berry but lacks proof of opposing real computation completion and semantic divergence diagnostics.
## 2. Objective and deliverables
Preflight M01-P6 proposals for S17-W01 and S21-W01 before assigning separate implementation worktrees. Return separate corrections and concrete signoff conditions.
## 3. Scope and non-goals
S17 independent presentation with one retained prepared flat mesh and 16ms dirty-only visible UI timer; S21 success observer for real worker callables plus deterministic arbitration/barrier/replay reporting. No M02 voxel geometry, native 60fps claim or GPU/backend replacement.
## 4. Files to inspect
Read root app/viewer_win32.cpp, app/d3d_scene_win32.hpp/.cpp, viewer_session, app timer/lifecycle, tests/replay_tests.cpp/executor_tests.cpp/runtime_tests.cpp, engine/include/settlement/core/worker_pool.hpp, engine/src/world.cpp actual stage spans and quota; docs S17/S21/M01, M01-P6 and pinned FuturePool/Testing. Inspect temporary actual client handler smoke.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posts/other agents or Serena switch. Root assigns separate S17/S21 branches, and S18 owns ongoing title changes.
## 6. Implementation or investigation approach
S17 verify packet owns world/camera/selection/overlay and prepared GUI inputs, UI-thread resource ownership, post-replacement pairing after pump consumes event, immutable pin across nested UI; D3D reuses existing flat GPU/CPU mesh for camera-only changes, avoid per-timer reallocation/hot spinning, hidden/title/minimized and zero-size restoration. Real actual handler test needs camera and render changes while owner/file blocked, safe destruction; respect existing WARP/offscreen/hardware capabilities and fallback HUD only.
## 7. Interfaces and data contracts
S21 optional after_execute(index) on success after real callable returns, before future satisfaction; return void/value/references/move-only, same-callable exceptions including observer errors, no throwing destructor, no hook when absent. Existing Void #15 registered. Two gates for two known competitors, controlled opposing completions asserted; tests 2/6/12 + capacity1 fallback without deadlock; real generic job contest parallel, berry claim serial with parallel movement separately. Report object/field/owner/request for first divergence using public World and canonical current serializer as authority; gated old world vs queued same-world reload with fresh session and unchanged old snapshots.
## 8. Dependencies and integration
S17 rendering work in new branch separate from S18 title/profile; avoid altering normal client command pumps. S21 production edit restricted to optional worker hook and tests/docs, no world mutation/codec changes. Future body15 normalize version selector after integration.
## 9. Edge cases security and performance
Check exception lifetimes, reference dangling/extra move, re-entrance or UI init/failure, force order while caller coordinator blocked, guarantee test oracle actually observes completion, full terminal effects after faults/cancel. Potential thread-lifetime hang on assertion; GPU device generation invalidates cached upload after reset. Check path/store version key for camera-only frames and active overlay state.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. Concrete prescreen decisions, testable postconditions and residual limitations. 3. Meaningful assignment in each isolated subsystem without changing the product contract.
## 11. Verification commands and evidence
Use source read and graph search/trace/coverage plus direct ranges; inspect actual m01-viewer-{build,ctest,ui-smoke}.log and client_handlers_smoke.cpp. No builds.
## 12. Constraints and stop conditions
Send prescreen first safe scope early. No apparent missing generic capability needs a duplicate issue; root filed Void/Library #15, immutable publication uses #5. Do not review unseen code or demand native-only validation for feasible Wine work.
## 13. Authorization and decisions
User authorizes complete roadmap branches and tests; root accepts dirty-only 16ms timer, one retained flat mesh generation, optional success observation and semantic diagnostics subordinate to canonical bytes, subject to technical preflight.
## 14. Return format
Return M01-F9 PREFLIGHT stage-specific verdict, corrections, exact test cases/source, bounded risks and practical blockers.
+48
View File
@@ -0,0 +1,48 @@
# Map the authoritative runtime and dependent system branches
Task ID: M01-P2
Role: astra_planner
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation at M00 904bdf8, M01-C/T in progress. User extended the goal to the full plan with commits, pushes and separate milestone/system branches. Pin 7b0fea6, Windows GCC16.
## 2. Objective and deliverables
Design the next integrated M01 implementation after the deterministic reference. Give concrete separable packages, frozen APIs, branch order and runnable acceptance for S01, S15, S16, S19 and the viewer.
## 3. Scope and non-goals
Read-only plan for M01 and prospective compatibility seam for M02. No new product discovery; the approved roadmap controls. Do not replan existing serial/replay task.
## 4. Files to inspect
Inspect PLAN.md, M01/M02, S01/S15/S16/S19 and S04/S06 contracts, world.hpp/world.cpp/world_save.cpp, app/viewer_win32.cpp, app/lan_session.hpp and _win32.cpp, CMakeLists.txt and current tests incl LAN. Check actual world mutators, UI direct writes, reload/command cache hazard and exposed stores/indices.
## 5. Write ownership and coordination
Write scope: none
Shared checkout; root owns branches/builds. Do not modify files or activate a different project.
## 6. Implementation or investigation approach
Indicate exact integration for a single-owner fixed-tick runtime publishing immutable snapshots; atomic candidate load/epoch rejection; versioned, city-scoped idempotent command results/authentication; rules manifest dependency validation/fingerprints; permanent ID and custody path. Preserve old format13/protocol11 with an explicit compatibility boundary for existing programs. Propose deliverable slices which independently add executable tested features.
## 7. Interfaces and data contracts
Name specific NEW types and responsibilities separate from observed ones. Explain host identity, dedup key, conflicts with stale packets, pending versus committed epoch, queue bounds and failed save/load. Suggest a no-duplicate-serialization path, CPU cost/50ms budget and API for existing viewer reads.
## 8. Dependencies and integration
Researcher separately investigates Void/primitives. Root authorizes scope, owns CMake integration, cross-system compatibility and push. One branch per milestone or system package fits the added user direction. New worktrees may be used for independent systems.
## 9. Edge cases security and performance
Call out deadlocks, stale load/worker results, snapshot lifetime, partially applied ticks, time spent in rendering, current hardcoded two slots and generator/script state. Keep more ambitious M09 features on M09.
## 10. Acceptance criteria
1. Source-grounded M01 package graph and first precise interfaces usable for concurrent implementation. 2. Boundaries for each acceptance criterion including existing gameplay/legacy callers. 3. Concrete, short next package to dispatch plus integration strategy.
## 11. Verification commands and evidence
Use git status --short --branch, git diff 904bdf8 --stat; rg -n 'WM_TIMER|world->step|world->apply_command|read_save|write_save|lan.poll' app engine; use scoped graph with coverage/direct checks for cited source. Existing integrated check is CMake + CTest Windows on Wine. No remote writes.
## 12. Constraints and stop conditions
Send first independent work packages early when ready. Stop if evidence requires a product decision; keep useful read-only work going. Do not spawn.
## 13. Authorization and decisions
User explicitly requested the full plan, local commits, remote pushes and occasional status. This assignment is planning only.
## 14. Return format
Return M01-P2 READY/PARTIAL, package DAG, file boundaries and frozen API, behavior/risk/test matrix, what can ship first and which assumptions need owner confirmation.
+48
View File
@@ -0,0 +1,48 @@
# Map durable item custody and stable entity references into the running game
Task ID: M01-P3
Role: astra_planner
Status: READY
## 1. Context and baseline
The integrated M01 branch /home/faumaray/Projects/stoneheart_at_home is at cf0cc2f. S01-03 groups logical state in a private WorldState in s01 worktree. S15-02 introduces a versioned modern checkpoint around validated legacy body and exact rules. S16-01 scopes command receipts to session. User's next gameplay requirement in M01.2 is stable IDs and conservation.
## 2. Objective and deliverables
Specify an executable incremental implementation plan for M01 stable IDs/ownership through actual current game actions (production, resource haul, construction, inventory, demolish). Identify the first narrow end-to-end migration that can be dispatched immediately.
## 3. Scope and non-goals
Read-only S04/S06 and checkpoint/world integration architecture; distinguish current IDs from index-based fields and later M03 capabilities. No redesign of the whole roadmap, mod SDK, region/world geometry or unrequested product choices.
## 4. Files to inspect
Inspect world.hpp, world.cpp, world_save.cpp, first_colony.cpp, viewer_win32.cpp, app/d3d_scene_win32.cpp/tests, plan S04/S06, M01 and M03. Inspect s01 capture worktree actual logical representation and detached checkpoint checkout. In pinned Void inspect public IDs/typed handles/registry if relevant and cross-check already documented matrix.
## 5. Write ownership and coordination
Write scope: none
No mutations, branches, external requests or children. Parent owns root task notes and Git. Do not change shared Serena project.
## 6. Implementation or investigation approach
Map introduction, assignment, transport, consumption, split/merge, cancel/delete, HUD, serialization and load validation by actual symbols. Plan monotonic counters never reused, ownership and transitions, stable typed references with bounded lookup and ordered arbitration. If legacy format13 must keep indices on the wire, convert at codec compatibility boundary, ensuring legacy snapshots can import deterministic IDs; modern checkpoints must encode actual counters and identities so rollback/mutations never reassign values. Identify exact compatibility mode for changing demolish behavior, preserve existing tests where game design allows. Avoid double representations that can silently diverge/lose inventories.
## 7. Interfaces and data contracts
Specify NEW API and fields only after source check. Cover existing WorkJob.id, Agent.id, ResourceNode.id, Storage.id, ProductionOrder, MaterialReservation, ConstructionStop, ItemStack and private AgentInventory. Give ownership and migration sequencing for WorldState, routes, input/output codec, renderer, tests, and branches S04 vs S06. Recommend whether durable ID fields are domain-local or reusable generic Void capability needing issue; no remote writes.
## 8. Dependencies and integration
Dependencies S01 snapshot/dispatcher/S15 versioned checkpoint. Root owns integration order. Send first safe independent task early with exact symbols, lossless old-wire export boundary and hard tests before broad changes. Multi-branch CMake/World ownership must be serialised.
## 9. Edge cases security and performance
Check nonempty demolished storage (currently erases stored items), active reservations/held goods, room/floor target, duplicate/dangling IDs, counterfeit aggregate counters, overflow and million-record malicious saves. No behavior changes to LAN11 or wrong acceptance claims. Keep authoritative reconciliation deterministic for serial/parallel.
## 10. Acceptance criteria
1. Source-grounded table of stable vs positional identifiers and mutation sites. 2. First executable slice with narrowly owned files and disambiguated compatibility. 3. Subsequent DAG solves M01 reference/custody exit, tests after mid-carry load/cancel and ledger conservation. 4. Name any actual product decision needed, or bounded technical recommendation.
## 11. Verification commands and evidence
git status --short --branch, git show -s --format=%H, rg -n 'shift_index|reserved_slots|construction_delivery|MaterialReservation|production_index|stock_storage|finish_production' engine app tests; inspect actual pinned headers, current serializer/acceptance fixtures and exact removal semantics. No build needed for read-only planner.
## 12. Constraints and stop conditions
No source/code modifications, deployment or tool state changes. Stop if pinned source unavailable or a consequential design decision is truly user-owned. Return useful independent conclusions immediately.
## 13. Authorization and decisions
User approved entire plan and requested subagents. Root assigns this dependent architecture work within M01. F3 authority and failure decisions remain in force. Does not authorize a new public protocol/dependency or branch push by agent.
## 14. Return format
Return M01-P3 READY/PARTIAL, concise path/behavior, implementation contracts, ordering, tests, upstream fit, unresolved facts. No children.
+48
View File
@@ -0,0 +1,48 @@
# Map the first selectable rules to existing game behavior
Task ID: M01-P4
Role: astra_planner
Status: READY
## 1. Context and baseline
Main 4ba64f7 has frozen rules manifests, checkpoint v1, Window-independent runtime. S18 initial UI preflight correctly permits only actually supported profiles. Present World::start_scenario hardcodes staged_beds_=true, while saved legacy worlds and recipes/game commands contain both staged and simple/plank bed behavior. Builtin colony manifest has a board work_ticks field (8) different from compiled SawPlank (12), so treating that as activated configuration would change prototype behavior.
## 2. Objective and deliverables
Produce a narrow verified implementation proposal for M01 real module selection/new game/load, with an actual deterministic gameplay difference and unchanged default trajectory. Assess existing simple vs staged bed paths as the first selectable feature.
## 3. Scope and non-goals
Read-only S19 technical/product-fit plan for first actual setting, default compatibility and existing explicit script-state contract for M01. Keep new Lua runtime, complete mods SDK and public cooperations in planned later scopes.
## 4. Files to inspect
Inspect rules_manifest.{hpp,cpp}, world.{hpp,cpp}, world_save.cpp, first_colony.cpp, checkpoint.hpp/.cpp, checkpoint_files.cpp, simulation_runtime.cpp, actual title_screen_win32.hpp and viewer handlers, S19 W01–W03, master/parity/prototype fixture. Review test constructions of old v1/v2/current bed states, frozen digest fixture and handoff from S18.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote access or child agents. Parent owns root decisions and eventual branch contracts; keep shared Serena activation fixed.
## 6. Implementation or investigation approach
Trace actual recipe/placement/material/progress behaviors under World::staged_beds() false/true, inputs/stock and ability to complete both. Propose a valid optional built-in rule package with explicit behavior and data (for example opt-in classic recipe always uses simple plank). Keep frozen default 2-package digest, current normal make_first_colony behavior and v1–13 imports. Give validation path from chosen catalog → Resolved actual game options → world initialization and saved rules → preinstall compatibility. Avoid merely switching labels/fingerprints without changing executed mechanics. Do not equate any early option with complete ACE parity.
## 7. Interfaces and data contracts
Propose frozen NEW C++ APIs and file/branch ownership. Handle old scenario saves with staged_beds=false and legacy imported default manifest, custom unsupported manifests in generic readers vs retained exact viewer profile gate, default-only LAN11, authoritative rules invariant on loads, real user setting at new colony in existing Windows title flow. Identify any compatibility ambiguity requiring product decision. S04 changes raw body/current checkpoint in parallel; coordinate ownership and versioned format boundaries.
## 8. Dependencies and integration
Dependencies S19 owns package/factory behavior; S18 UI can wire selector when accessor/factory verified; S15 owns generic file prepare, S01/S16 already identity/legacy gates. Keep selectable integer state/atomic script results on M01 contract only unless actual milestone requires executing Lua now. Use existing Void facilities, flag genuinely missing upstream primitive without externally filing.
## 9. Edge cases security and performance
Risks default digest change, explicit legacy import with previously valid raw data, failing to reflect actual selected mechanics after reload, stale display code assuming staged beds, repeated loading/selection under same world seed. Need exact tests for active-world refusal on incompatible compiled profile, variant supply/bed completion, replay and v1/cross-binary.
## 10. Acceptance criteria
1. Source-grounded selected pair or better alternative with clear real effects, no cosmetic difference. 2. First implementable core task and limited follow-up UI integration. 3. Testable legacy/frozen/unchecked-catalog/canonical behavior and precise pending script contract. 4. Name any real product decisions.
## 11. Verification commands and evidence
Use git rev-parse HEAD; rg -n 'staged_beds_|start_scenario|make_first_colony|BedStage|default_rules_manifest|builtin_rule_packages' engine app tests; inspect actual pinned API when relied on. No build needed.
## 12. Constraints and stop conditions
Send first viable technical criteria early. No refactoring, remote writes, branch changes or children. If simple-bed feature is invalid by plan/source, identify a valid alternative with direct evidence instead of forcing it.
## 13. Authorization and decisions
User authorizes complete roadmap and rules selection is explicit M01 deliverable; this design reuses existing gameplay/boundaries. Root retains scope and integration choices.
## 14. Return format
Return M01-P4 READY/PARTIAL, actual source references, bounded interface/ownership design, exact verification targets, integration risks/native gaps.
+50
View File
@@ -0,0 +1,50 @@
# Specify the first authoritative inventory and transfer operations
Task ID: M01-P5
Role: astra_planner
Status: READY
## 1. Context and baseline
Root M01 2a5df1a. S06 IDs 8260e09 are integrated. The developing S04-01 converts production orders/agent links to ProductionId, current save body14/outer2 and typed legacy import. Previous M01-P3 mapped object domains, but actual quantities still live in storage/resident representations and construction drops cargo on arrival. This is the detailed technical handoff for M01.2.
## 2. Objective and deliverables
Freeze a small end-to-end migration for S06-02 and S04-02 with exact authoritative ownership, identity allocation, operations and backward projection. Suggest genuinely independent implementation segments that can be dispatched before large World edits.
## 3. Scope and non-goals
Focus on objects/recipes already present, order-reservations/haul/consumption/cancel/demolition, no new gameplay, extra protocols, catalog or general database. Domain-level transfer retry/retention must have explicit bounds.
## 4. Files to inspect
Read root docs/plan/systems/{S04,S06}.md, M01, M01-P3, engine/include/settlement/core/world.hpp and actual Inventory/Storage definitions, engine/src/world{,_save}.cpp plus tests for logistics/production/replay and resource/food handling. Inspect s04 worktree public diff for actual ProductionId and NEW current14 schema; never modify it. Review pinned Void Numeric, upstream #7/#8 linked in docs/plan/void-library.md.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posting, shared project switches or children. Parent owns root/remote and serializes World/codec ownership. Work from actual source and verified graph coverage.
## 6. Implementation or investigation approach
Trace every quantity introduction, split/move, take_reserved_material, pickup, in-transit cancellation, construction worksite arrival/delivery, consumption, eating, storage demolition and factory stock. Identify minimum source of truth. Design checked before-effect atomic operations, stable nonzero StackId by world, one current owner per stack, explicit material balance opening/sink, exact held amounts, and reliable projection to old fields. Avoid persisting parallel quantity ledgers without enforced consistency. Characterize active/inactive imported orders to preserve v1–14 continuation, including mid-site delivery. Product keeps pre-existing demolition's removal of stock and records its amount/reason.
## 7. Interfaces and data contracts
Give exact proposed NEW operation types, identities/high-water constraints, on-disk version steps, and API surfaces for S04 claims vs S06 actual stock. Pin behavior on outcomes AlreadyApplied/Duplicate/Conflict/Busy and stale retries even after bounded receipt retention and save/load, deterministic order vs multi-actor concurrency. Name genuine policy questions; choose bounded defaults for reversible design.
## 8. Dependencies and integration
An independently testable ledger module before World integration may be parallel if it has a real consuming path and fixed grounded seam. S04-01 must integrate first for worksite references, and S19 touches only scenario setup. Summarize actual changes needed in UI for preserving displayed amounts.
## 9. Edge cases security and performance
Bound memory by current existing file/collection capacities, handle zero and uint64/int quantity overflow, reserve IDs without partial mutation including splits/exhaustion, owner removal after pickup, no-free-space redirects, capacity races, negative/cross-owner dangling state, and loaded modern wrong digest. Avoid quadratic hot paths; identify realistic measurement checks.
## 10. Acceptance criteria
1. Source-grounded transition and migration tables; 2. First independently deliverable task with exact scope and tests that leads to real stock; 3. Subsequent isolated work packages with complete modern migration path; 4. Leverage correct Void utilities and #7/#8 where adequate; 5. Declare present limits in legacy raw13/network11 projection.
## 11. Verification commands and evidence
Use git rev-parse HEAD, actual scoped rg -n on add_item, take_reserved_material, advance_construction_delivery, finish_production, reserved_slots, item inventory and stock, scoped current/load/save comparisons, local Void pin as needed. Check graph identity/coverage for relied-on root code; isolated s04 working diff uses direct reads. No compilation required.
## 12. Constraints and stop conditions
Send first technical seam early, then full report. Do not assign new IDs by vector position, silently destroy cargo on cancel, break legacy binary projections or start new worktrees/remote Git. If uncertainty materially changes the product scope, identify the specific branch and continue other evidence.
## 13. Authorization and decisions
Approved M01 hard requirements and earlier planner M01-P3 permit this focused design of actual custody. Root decides integration order and product-preserving defaults. No release or merge to main.
## 14. Return format
Return M01-P5 READY/PARTIAL, exact grounded operations and claimed invariants, owners/paths, test and version matrix, bounded retention/performance policy plus actionable blockers only.
The accepted decisions and historical format boundaries are recorded in [the custody contract](../../plan/custody.md). Source-backed corrections from preflight address creation retries, retained site stages, pending completion and representability on LAN 11.
+48
View File
@@ -0,0 +1,48 @@
# Define the remaining client frame and replay acceptance work
Task ID: M01-P6
Role: astra_planner
Status: READY
## 1. Context and baseline
Root db0a872 merges S18 b7f18c0, S19 selectable rules, S04 Current14, S01 owner and legacy LAN. Actual client WM_TIMER pumps every 60 ms while camera input can invalidate on demand and scene Present uses 0. Existing replay on serial and 2/6/12, last meal, synchronous structural barriers and faulted owner recovery pass. M01 needs independent client frames and an evidenced worker completion-order adversary/first divergent IDs.
## 2. Objective and deliverables
Prepare two independent real work packages for S17-W01 render frame delivery and S21-W01 deterministic replay diagnostics. Identify acceptance already satisfied vs missing. Recommend minimal source-grounded additions that can proceed alongside full S06/S04 custody.
## 3. Scope and non-goals
No implementation, new M02 terrain, mesh engine overhaul, native performance claims, general benchmark infrastructure or speculative production hooks. Preserve S18 title/rules changes and S06 current schema.
## 4. Files to inspect
Read docs/plan/milestones/M01.md, systems/S01,S17,S21; app/viewer_win32.cpp pump_session/scene/view/HUD/camera/modal/WM_PAINT/WM_TIMER, app/d3d_scene_win32.* and public draw interface, existing client_* smoke and tests; engine worker_pool/world scheduling/hooks, runtime/dispatcher, tests/replay_tests.cpp/executor_tests.cpp/runtime_tests.cpp, benchmarks as pertinent.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote/children or Serena switch. Root plans separate branches, S18 owns title and profile logic, S06/S04 own inventory world paths. Use current root graph only after coverage check and read missed lines.
## 6. Implementation or investigation approach
S17 identify how to prepare/pin immutable frame data once, main+child/software/D3D and nested UI callbacks, decouple scene refresh from event/network pump and authoritative 50 ms tick, avoid busy loop/rebuilding expensive static geometry solely for unchanged state, camera movement during gated world and file work. Match existing Win32 design and keep title/minimize/pause behavior; future D3D chunk cache is M02. State how real harness could assert camera changed and original tick stayed fixed without treating Wine fps as native.
## 7. Interfaces and data contracts
S21 locate how last-item/resource arbitration relates to actual parallel batches and stable tie order. Design test/harness that PROVES opposing order of completed tasks (not just ordering hook starts/sleeps) for an actual contested outcome and canonical state. If after callback needed, preserve WorkerPool completion/exception/move-only behavior and use least invasive grounded seam. Check stale results after load owner barrier, real two client idempotent and save+camera. Recommend first-divergent tick/ID (inventory/actor/job/command) reporting and repeatable command entry/tag. Avoid duplicated serializers that drift; existing current14 soon current15. Derive calls/files from source.
## 8. Dependencies and integration
Align S17 renderer-owned files vs S18 title/client profiles and CMake/worker code ownership. S21 can adapt test golden canonical encoding immediately independent of future custody, document which invariants extend after body15. Flag any truly missing generic primitive and check pinned Void facilities before suggesting upstream issue.
## 9. Edge cases security and performance
Check UI timers/window events after destroyed, minimized/hidden, modal subloops and GPU resource lifecycle/race. Race tests deterministic using bounded waits and release cleanup even on assertion. Never rely on exact Wine wall scheduling or declare physical 60fps. Prevent deadlocks at 2 workers or queue capacity 1.
## 10. Acceptance criteria
1. Separate executable contracts with exact paths and acceptance. 2. Clear proof of forced completion and stale fencing/diagnostic usefulness. 3. Real GUI cadence event and pinning acceptance with labels and stable source ownership. 4. Mark which existing evidence suffices. 5. No broad refactors outside M01.
## 11. Verification commands and evidence
Use git rev-parse HEAD; scoped graph search/trace and snippets plus coverage ranges. Read actual integrated CTest/GUI logs m01-viewer-{build,ctest,ui-smoke}.log and /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. No builds needed.
## 12. Constraints and stop conditions
Send first independent S17/S21 seam early. Avoid new protocol/settings, general policy changes or altering product contracts in design. No remote actions/children.
## 13. Authorization and decisions
User authorizes complete roadmap and per-system development branches. Root owns product/integration/publication. Preliminary design may proceed while S18 title and S06 custody progress.
## 14. Return format
Return M01-P6 READY/PARTIAL per system, current verified behavior, scope/paths, exact measurable tests, remaining gaps/dependencies and likely performance implications.
+48
View File
@@ -0,0 +1,48 @@
# Verify Void contracts for runtime, persistence and modules
Task ID: M01-R2
Role: astra_researcher
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home at M00 904bdf8 on milestone/m01-authoritative-simulation; initial serial/replay tranche in flight. Public Void HEAD matched CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. User wants later systems implemented as well.
## 2. Objective and deliverables
Find exact reusable Void APIs for M01 rules module/manifest dependencies and hashing, transactional saves/Windows atomic replacement, immutable snapshots/fixed clocks and idempotent command dispatch. Produce per-contract decisions so authors can begin without duplicating library code.
## 3. Scope and non-goals
Read-only evidence focused on S19/S15/S01/S16. Start by returning results for rules/manifest and atomic writes. M01-R already covered executors/replay.
## 4. Files to inspect
Inspect CMakeLists.txt, docs/plan/void-library.md, docs/plan/systems/{S01,S15,S16,S19}.md, current save codec, viewer save entry points, exact public Void pin, test and backend files and current upstream tracker. Verify source branches against pin, not co-located names.
## 5. Write ownership and coordination
Write scope: none
Root owns all network writes. Other agents own game/test files. Do not change branches or active graph.
## 6. Implementation or investigation approach
Check public API, real behavior, Windows flags and tests at pin e.g. Binary, Crypto SHA256, IO atomic replace, version/dependency graph/manifest. For each required generic gap give existing matching issue or minimal issue content, expected replacement check, local game path candidate. Distinguish domain ownership. Independently validate whether Windows build/link of candidates is feasible, no application writes.
## 7. Interfaces and data contracts
Return precise API/units, guarantees and missing pieces (including byte/string handling, version compatibility and corruption behavior). Prefer supported existing routines over new custom equivalents.
## 8. Dependencies and integration
M01-P2 handles game integration. Root decides package ownership, upstream issues and commit/push. Authenticated tool available only if needed; use read-only upstream operations.
## 9. Edge cases security and performance
Do not leak private code, real data or credentials in external queries. Treat native Windows vs cross-test explicitly. Network, sandbox and subprocess errors must be reported accurately.
## 10. Acceptance criteria
1. Runnable library reuse plan for each next M01 system. 2. Direct URLs/test paths and Windows constraints. 3. Actual tracked gaps or precise issue drafts with acceptance and migration test.
## 11. Verification commands and evidence
From game root git show HEAD:CMakeLists.txt and from confirmed pinned checkout git show 7b0fea6095f603f9e1904f66dfdc7752f4be4792:<path>. Check live git ls-remote and read-only public issues. Reference existing cross env and use source fixtures as appropriate without changing project.
## 12. Constraints and stop conditions
Do not create issues, fetch private data into public tools, or ship dependency changes. Return findings by priority, including partial early results. No children.
## 13. Authorization and decisions
User's plan requires library-first analysis, and separately authorizes authorized repository changes and branches. This task grants read-only investigation.
## 14. Return format
Return M01-R2 status, decision/evidence per feature, real gaps/practical issues and replacement criteria, current Windows evidence and unresolved questions.
+56
View File
@@ -0,0 +1,56 @@
# Audit the live LAN owner bridge and interactive session integration
Task ID: M01-V10
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S16-02 in isolated /home/faumaray/Projects/stoneheart_at_home-worktrees/s16 based 8c4c1fe. Contracts S16-02 and M01-F5 closed peer+epoch issues. S18-01 in sibling s18 has reviewed S15 a063894 merged, viewer in progress; LAN candidate will enter its checkout after review. One independent review per product path.
## 2. Objective and deliverables
Review actual S16 adapter now for branch integration. Later when root supplies final S18 commit/diff and evidence review normal Win32 entry for events, snapshots, async files and lifecycle, with separate verdicts.
## 3. Scope and non-goals
Only S16 compatibility host/guest integration and S18 normal client wiring. Legacy protocol remains 11. No public additional transport or deployment.
## 4. Files to inspect
Inspect s16 tracked diffs app/lan_session.hpp/.cpp, tests/lan_tests.cpp, docs S16, frozen runtime header and actual command/snapshot logic. S18 later inspect actual all new viewer_session code/tests and viewer_win32.cpp, CMake, S15 CheckpointFiles and normal entry + smoke. Read M01-F4/F5 and the assignments.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children/project switches. Other workers own code. Use direct source for isolated worktrees. Ignore their summaries until checked.
## 6. Implementation or investigation approach
S16 validate default-only authenticated legacy slot, session replacement, coalesced/wrong/rejected old sequence vs modern next_requests, pending future capacity/incarnation/peer tags, reconnect with in-flight owner mutation, truthful Wire11 receipt and first snapshots, consumer of take_result accept/reject vs prior take_rejection, correct future lifetime and no blocking poll on game work. Cross-verify old/no default rules or disconnect and correct generation in actual state transitions.
## 7. Interfaces and data contracts
S18 later validate consistent immutable world on paint/menu including nested window callbacks, pumped title/modal completions, no per-reset UI join, one file service check latest ticket + dimensions/supported rules, healthy save capture max, correct current epoch after commands, reject and retain draft, receipt routing and bounded local IDs, short locks and cleanup, actual normal new/continue/title load and LAN. No live mutable world assignment through UI.
## 8. Dependencies and integration
Root merges S16 into S18 to actually build/test full client after S16 review. S18 source is incomplete initially; do not approve unseen future work. Public test port uses loopback only. Native acceptance separate.
## 9. Edge cases security and performance
Check state across TCP rebind and network packets/receipts allowed on aborted session. Saturation/old guest fixed sequence, authoritative exceptions. UI must handle busy/faulted futures, avoid stale changes after failed newer load, process-level save ordering and bounded memory. Compare baseline behavior only within approved compatibility.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per phase with concrete sources and triggers. 2. First confirm real 5/5 lan-owner, 92/92 core, 9/9 LAN and original/new binary interop in both directions. 3. S18 after actual signoff + build/smoke logs; name any missing evidence for end-to-end status.
## 11. Verification commands and evidence
git -C s16 diff --check; inspect /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-final-{build,ctest,tag}.log and lan-owner-interop.{cpp,py,log}. For S18 compare named parents once available and logs client-* in shared temp dir. Read-only inspection only.
## 12. Constraints and stop conditions
Return S16 review early. If blocked by outstanding S18 dependency, confirm stage A and await final evidence without premature approval. Inform root immediately of a verified actionable defect.
## 13. Authorization and decisions
User authorizes complete plan and system/milestone commits/MRs accumulating on roadmap. Root owns external actions/normal integration.
## 14. Return format
Return M01-V10 separate S16/S18 findings with actual tests, changed paths and limitations. No children.
The S16 adapter has been integrated at `aa4e271` (parents `60154bd` and `09545bf`). Recheck the transport, legacy codec and test blobs against the reviewed branch, confirm the absence of merge edits to the owner or file adapter, and inspect `m01-lan-{build,ctest}.log` before publication. This additional check is read-only. The combined suite passed 106 core and 9 LAN tests.
Stage A passed the integrated review at `aa4e271`. For stage B inspect the actual tracked and new S18 files in the `s18` worktree based at `eef69ca`, including `viewer_session`, the Win32 entry point, CMake and the viewer suite. Inspect `client-{build,ctest,ui-smoke}.log` and `client_ui_smoke.cpp` under the temporary evidence directory above. The smoke used three real viewer processes with isolated save data. Check title, modal navigation, successful and failed load, guest transitions and truthful pending-blueprint outcomes. The contract still distinguishes the initial compiled default profile from the separately scheduled S19 selection. Return a defect report or READY for S18 without changes to the checkout.
Stage B initially required three corrections. Recheck the finished fixes for identity after modal demolition, rejected guest rejoin preserving the retained replica, and ticking acknowledgements across fault recovery. Inspect the updated committed-quantity and request-path checks in `client_{handlers,regression}_smoke.cpp`, the corresponding `client-{handlers,regression}-smoke.log`, the final viewer build, the three-process smoke and `client-ctest.log` (99 core, 9 LAN, 10 viewer). Separate integrated audit follows when root supplies the merged ref.
Stage B fixes passed review and were committed as `b7f18c0`. Integrated commit `db0a872` has parents `5354241` and `b7f18c0`. Confirm that the resident panel uses approved resource/storage/production IDs while the view remains pinned, both UI and core suites register, and the merged application’s three-process smoke passed. Check `m01-viewer-{build,ctest,ui-smoke}.log` under the temporary evidence directory.
+50
View File
@@ -0,0 +1,50 @@
# Review durable order identity and compiled colony profiles
Task ID: M01-V11
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Independent review in two phases. S04-01 isolated worktree s04 based 4ba64f7 with production order IDs, body14 and outer checkpoint2, existing schema1 real fixture. S19-02 isolated s19 based 60154bd with first optional package/profile, old default retained. S19 and S04 are expected to touch adjacent World declarations/CMake; root will supply combined refs for final checks. Baseline S16/S06/S15 already published.
## 2. Objective and deliverables
Provide separate disposition for actual S19-02 and S04-01, then for a root-supplied integrated result if requested. Alert root quickly on reproducible failure before workers retire.
## 3. Scope and non-goals
S19 backend, old/new data and S04 current changes including codec, command handling, real placement/reservations and lifecycle. S18 screen/selector verification belongs to a separate client review. This review covers the public core seams that later UI calls.
## 4. Files to inspect
Inspect actual tracked/untracked files in sibling worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s19,s04}, including all new headers/sources/tests, full surrounding world, checkpoint/readers, rules_manifest, first_colony, command_dispatcher, changed CMake and docs; baseline legacy tests + new fixtures actual consumed bytes. Read contracts S04-01/S19-02 there and root M01-F6.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote postings or children. Parent owns commits/resolution. Use direct scoped reads for separate worktrees, shared root graph with coverage/direct missed lines if used. Do not change project activation.
## 6. Implementation or investigation approach
S19 audit exact old default manifest/hash, optional package deterministic compile of real recipes vs forged/missing/additions and unsupported profiles, factory UUID/canonical rules, no mutable after-start rule switching. Check active staged optional refusal, default raw/simple/inactive/saved historical compatibility, actual input requirements/duration simple vs staged, finished beds and room. S04 review full ID allocation, batch production scheduling incl replenishment simulated post-demolition, before/after failures transactional, exact Busy narrow no domain next seq mutation; new ID in all actor references, cancellation, finishing order and find; explicit codec boundaries, bounds/duplicates/noncanonical/high-water/dangling, v1 authentic + modern pair and replay.
## 7. Interfaces and data contracts
Public profile functions colony_rules/compile_colony_rules/make_colony_checkpoint/validate_colony_checkpoint and staged/default initializers preserve calling contracts; strict profile policy only at game/client gate, generic codecs/runtime remain reusable. ProductionId 0 absent, MAX exhausted with last valid MAX-1. Compare both double dispatch (legacy/direct/modern) where relevant to tests.
## 8. Dependencies and integration
Order of branch signoff independent. On integrated stage confirm the raw/outer and profile gates and all added tests coexist under root CMake/World changes. Native hardware/real LAN separate. Root will send ready marker and evidence directory for each phase; do not approve unseen results.
## 9. Edge cases security and performance
Watch O(N²) references in hot/hostile save path, exhaustion partial mutations after storage erasure/cabin terrain / counters/room placements, v13 and LAN11 byte drift, accidental implicit fallback on unauthenticated or modified data, restoring historical default simple and optional staged mismatch. Confirm authentic fixtures frozen using prechange binary; never log private data.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component with concrete reproduction and severity. 2. Compare targeted/final logs and actual old corpus bytes, not just worker report. 3. Root integration evidence after selected branches merged must identify any new cross-contract issue. 4. Document unverified native/product gaps.
## 11. Verification commands and evidence
Use git -C <wt> rev-parse HEAD; git -C <wt> diff --check and --stat; read status/new paths and inspect source directly. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{baseline,tag,ctest,compatibility}.log and production-id-{final-tag,ctest}.log plus archived production replay/corpus logs as provided. For merge phase compare relevant actual branch/HEAD blobs and final CTest logs.
## 12. Constraints and stop conditions
Give findings as soon as evidence warrants; no remote or code writes, no plan beyond requested changes. Hold component approval if final tests not yet recorded or actual source still changing. Two failed same-cause fixes escalate via root.
## 13. Authorization and decisions
User authorizes roadmap/push/MRs/upstream issues; root alone owns those actions. Preflight M01-F6 explicitly passed under default simple/inactive compatibility policy and scoped capacity exception contract.
## 14. Return format
Return M01-V11 S19/S04 separate verdict, file/line, trigger, actual tests/artifacts and remaining gaps. Later verify corrected diff or integrated refs when supplied.
Both component reviews returned READY. Audit integration commit `a8cd7bb`, parents `9a248c3` (which includes S19 `2759563`) and S04 `2a3ec92`. CMake kept both new test sources during conflict resolution. Check the merged World initialization and stable production fields, old/new checkpoint and profile behavior, selection tests using the real current encoder, and the unchanged legacy host gate. Windows x64 logs `m01-orders-profiles-{build,ctest}.log` cover 122 core and 9 LAN cases. S18 initial viewer and follow-up title selection have separate reviews. Scope here is the integrated core and runtime LAN behavior.
+50
View File
@@ -0,0 +1,50 @@
# Review atomic pickup and the title profile selection
Task ID: M01-V12
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S06-02 at sibling s06 a8cd7bb plus implemented checkout. Targeted quantity tag 14, whole 136 core+9 LAN at isolated branch and two prior corpora. S18-02 at sibling s18 e6a01be in progress. Each had explicit M01-F7 preflight corrections. Root will signal when to inspect S18 implementation and integrated refs.
## 2. Objective and deliverables
Independently review actual atomic pickup now, title/profile integration when ready, then combined branch evidence before remote publication.
## 3. Scope and non-goals
S06 subset meal/construction stop only and preserved direct recipe processing; S18 visible title selection, exact compiled acceptance/host gates, old profile compatibility. Durable custody in design F8 is separate.
## 4. Files to inspect
Read root M01-F7, sibling s06 S06-02, its new inventory_transaction.hpp/.cpp, narrow World integration, actual new quantity_transaction_tests.cpp/CMake/docs, contextual World/WorldSave/Immutable runtime. For later S18-02: actual title_screen_win32/viewer_win32/viewer_session/tests, S19 factory/validator, LAN and GUI/handler smokes.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posts/other agents or Serena switch. Root publishes and owns merges. Direct scoped worktree source incl untracked files mandatory; shared root graph with range checks only when relevant.
## 6. Implementation or investigation approach
Pickup verify one storage at the current stop, multiple and nonadjacent duplicate line aggregation, no underflow/overflow or invalid type indexing, exact target count, checked final storage capacity including one first-ingredient output reservation at the correct stop. Late rejection leaves original count/slot inventory, routes/cursor/state from pickup entry. Ensure commit has no allocation/throw, erases correctly and preserves stack order, body14/raw13/LAN11 outputs unchanged. Ensure tests enter real meal/multistop/carpentry and runtime fault behavior and direct finish_production is preserved.
## 7. Interfaces and data contracts
S18 later validate title-only New choice, accurate simple Miner description/controls, both initial and latest async candidates use accepted compiled profile & 32×32, historical default simple/staged/inactive, malformed latest after superseded prepared candidate, exact-default legacy host both immediate/deferred/after modal and explicit pending-load refusal before listener effects; S18-01 guest rollback/modal epoch and ticking fixes remain.
## 8. Dependencies and integration
Send independent verdicts as available. Root may request follow-up integrated comparisons via updated refs/log paths. Wait for actual S18 ready marker; no future-code signoff.
## 9. Edge cases security and performance
Check arithmetic touched only accepted input, multiple erased stack lifetime, max 11 types vs unbounded input lines, true atomic output-slot commit, current state unchanged after failures, actual compiled probes and real Win32 entry. Test data mutations must remain scoped to fixtures. Do not equate Wine with native Windows.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. Source-grounded findings with concrete triggers/severity. 3. Confirm actual logs and golden files/GUI smoke. 4. Integrated review only when refs supplied.
## 11. Verification commands and evidence
git -C <wt> status/rev-parse/diff --check; read new source and relevant tracked full contexts, /tmp/stoneheart-milestones.xprJ2SVp/quantity-{config,build,rebuild,tag-final,ctest,probe-build,golden}.log and actual checksums. S18 final logs will use client-profile-* in same temp directory.
## 12. Constraints and stop conditions
No code/Git/remote changes; if a blocking defect appears report promptly, then re-review actual corrected source on request. Do not assume dry approval of new receipt registry or future schema15.
## 13. Authorization and decisions
User authorizes roadmap/push/MRs/upstream issues; root owns all external actions. Prescreen fixes incorporated before implementation.
## 14. Return format
Return M01-V12 separate S06/S18 verdicts, real files/paths/tests, exact remains and native caveats, later integrated check as assigned.
The S06 component passed and is committed as `3c997ed`. Compare integration `66af7c5` (parents `e6a01be` and `3c997ed`) to each parent. Inspect actual `m01-quantity-{build,ctest}.log`: Windows x64 under Wine passed 136 core, 9 LAN and 10 viewer tests. S18-02 is still a separate pending review.
+48
View File
@@ -0,0 +1,48 @@
# Review the independent executor and rule package changes
Task ID: M01-V2
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Milestone integration root /home/faumaray/Projects/stoneheart_at_home at 8d2870a. Actual candidate worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s01,s19} both based on 8d2870a. S01-02 and S19-01 have test evidence, root owns integration.
## 2. Objective and deliverables
Independently review each actual system diff and return separate merge-ready verdicts. Include new untracked files, not only git diff or implementer summaries.
## 3. Scope and non-goals
Check correctness/regressions/compatibility and possible new test defects in the two bounded packages. Scope excludes later authoritative runtime and native release acceptance.
## 4. Files to inspect
Inspect each worktree's docs/agent-workflow/tasks/{S01-02 or S19-01}.md, CMakeLists.txt, new engine/src/rules_manifest.cpp/public header, rules_tests.cpp, worker_pool.*, world.cpp/world_save.cpp/world.hpp, tests/executor_tests.cpp and replay_tests.cpp. Use exact upstream headers at pin in /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
## 5. Write ownership and coordination
Write scope: none
No edits, branch/Serena switching, new builds, network writes or children. Worktrees are isolated; check cwd for each.
## 6. Implementation or investigation approach
S19 inspect public API and actual bounded StrictJson handling, duplicate key/definition/ID diagnostics, exact SemVer incl build, canonical SHA of simulation content, order permutations, dependency closure and conflicting providers, malformed constructs and failure diagnostic. S01 inspect task capture lifetimes and guard destruction order, reserved capacity, overload retention, stop/start/error handling, expected/future semantics, partial startup, nested dispatch assumptions, injected tests and threading on Windows.
## 7. Interfaces and data contracts
Verify original M01-C replay public default behavior and format13/LAN11; new rule identity needed by S15. User expects appropriate Void APIs and references for gaps (#4 resolver). Check public compile/link feature propagation and competing CMake edits for root.
## 8. Dependencies and integration
Evidence for S19 in /tmp/stoneheart-milestones.xprJ2SVp/rules-final-*.log (9 tagged +42 core/4 LAN). S01 build /tmp/stoneheart-milestones.xprJ2SVp/executor-build; additional capacity-one replay and throwing move case being finalized with original 5 normal replay cases. Baseline 33 core/4 LAN. Root owns final integrated CMake and each system commit.
## 9. Edge cases security and performance
Inspect actual changed and new lines before verdict. Avoid assigning unchanged historical limitations as new bugs; label native filesystem/Windows physical checks outstanding. Read-only isolation excludes shared Serena switching. Capability process notes are not test evidence.
## 10. Acceptance criteria
1. Separate S19 and S01 verdicts, P0–P3 real issues with reproduction/locations/fixes. 2. Verify evidence and exposed contracts. 3. Report integration risks and targeted regressions. Give early S19 verdict to unblock persistence integration.
## 11. Verification commands and evidence
Run git -C <actual-worktree> diff 8d2870a --stat and git -C <worktree> status --short; read the actual new files. Review each ctest log and check git diff --check. Optional existing binary smoke under known Wine env; no competing rebuild.
## 12. Constraints and stop conditions
Do not approve unseen final changes, or perform external or repo writes. Stop once bounded evidence suffices and send findings early.
## 13. Authorization and decisions
User authorized branch-per-system development, commits and pushes. Root requested independent final review.
## 14. Return format
Return M01-V2 verdict for each branch, findings with severity/observed effect, verification and anything unrun. No application edits.
+48
View File
@@ -0,0 +1,48 @@
# Recheck executor teardown and integrated system target linkage
Task ID: M01-V3
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root at de38aff S19; s01 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 based on 8d2870a. M01-V2 accepted all production paths and S19; P2 concerned only promises and shared future destroyed before WorkerPool joined on assertion unwind.
## 2. Objective and deliverables
First re-review the one-line test lifetime repair in s01 and its rebuilt evidence. Then when root sends the staged integration, verify actual combined target graph for S01+S19 and any contemporaneous reviewed S16/S15 layers expressly identified.
## 3. Scope and non-goals
Independent read-only review of precise previously identified risk and later integration overlap. Code/design outside changed boundaries retains its separate reviews.
## 4. Files to inspect
Inspect s01/tests/executor_tests.cpp test_capacity_retains_move_only_work_and_exceptions, s01/docs/plan/systems/S01.md and M01-V2. Integrated CMakeLists.txt, test registry, system target interfaces, actual git staged merge. Root provides integration refs/results at that point.
## 5. Write ownership and coordination
Write scope: none
Do not mutate checkouts, shared Serena or Git. Others own code; report findings only.
## 6. Implementation or investigation approach
Reason through reverse destruction on early failure, ScopeExit ordering, async future captures. Consult actual targeted runner log and receipt; send READY/CHANGES_REQUIRED per component. Later verify merge parent trees and union of observed features without re-reviewing unchanged code.
## 7. Interfaces and data contracts
Core composable Windows consumers need transitive public Void::Async (cxx_std_26) and other headers' dependencies. Retain pure SHA, correct enabled modules, all sources/cases including executor/rules/replay. New S01/S19 docs report actual benchmark with Windows/Wine scope.
## 8. Dependencies and integration
Root owns merge, CMake conflict resolution, clean build and pushes. First verdict unblocks the branch commit. Remain available for integrated changes.
## 9. Edge cases security and performance
Reversed destruction must keep promises, shared_future and borrowed worker data alive through join; guard releases before join. No native Windows or performance overclaims.
## 10. Acceptance criteria
1. Live source + actual rerun validate lifetime finding. 2. For integrated stage identify any lost component or unintended changes in overlapping files and verify real aggregate suite counts. 3. Report verdict separately per stage.
## 11. Verification commands and evidence
Use git -C <s01> diff --check; read test lines 104–136 and /tmp/stoneheart-milestones.xprJ2SVp/executor-recheck.log (8 of 8), root reran CTest core and LAN PASS. At stage two use git -C <root> diff --cached --stat and inspect actual CMake vs named parents, link/test results root sends.
## 12. Constraints and stop conditions
No edits, new roles, external writes, branch changes or builds touching worker build dirs. Stop on uncovered shared behavior or missing evidence.
## 13. Authorization and decisions
Parent authorized this follow-up to M01-V2 on the specific finding; full roadmap scope permits integration after evidence.
## 14. Return format
Send first verdict immediately; second when integrated staging and results are available. Findings severity, location, impact, fix and actual evidence.
+48
View File
@@ -0,0 +1,48 @@
# Review accepted-command retention and Windows save publication
Task ID: M01-V4
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Separate isolated worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s16,s15} at 8d2870a. S16-01 and S15-01 each add a concrete service + tests. S16 build 43 core/replay/session incl ten session and four LAN, native Win32 writer verification finishing. M01-F3 accepted contracts. Root owns Git and app integration.
## 2. Objective and deliverables
Perform fresh defect-oriented independent audit of both actual diffs. Send S16 signoff/finding early and S15 when its final test run finishes. Initial review covers independent component behavior for subsequent integration.
## 3. Scope and non-goals
Read-only S16 and S15 actual code and new paths, test quality, CMake/public API, NFK Windows error semantics. Later integration review is separate. No UI, scheduler or broad networking architecture.
## 4. Files to inspect
In each isolated checkout inspect git diff + git ls-files --others --exclude-standard; source/header/tests for command_dispatcher, save_service_win32, session_tests, save_service_tests and CMakeLists. Read S15-01/S16-01 there and M01-F3 in root. Read actual World::apply_command, queue_cabin, pinned Void Async/Uuid/FuturePool, and original synchronous viewer save as needed.
## 5. Write ownership and coordination
Write scope: none
No mutations, branch actions, builds into active build dirs, shared Serena activation, external writes or children. Reviewers did not implement either change.
## 6. Implementation or investigation approach
S16 reserve before effects; exact complete payload comparison; bounded cached accepted/rejected receipts; trusted separate player, UUIDs and city; valid new request mapping, out-of-order detection and paused/prior-world exact repeats; Before/After fault observer must poison uncommitted ledger and expose previous commitments only. Confirm all domain input validities incl extreme coordinates before arithmetic. S15 inspect FIFO identity, concurrent submission reentrancy, producer ownership on acceptance/rejection/completion, no writes before validation, bounded work/bytes, OS-level staging ownership/exclusive temp, close/flush/publish point, recovery and shutdown.
## 7. Interfaces and data contracts
Independent API must give strong failure boundary, cloneable dispatcher with candidate staging and exact unchanged legacy format13/LAN11. S15 single writer, atomic same-directory replace; share denial may return prepublication failure, preserving old bytes. Requiring replace-through-held-handle across all Windows filesystems is outside game contract. For that specific error test prove visibility flags, unchanged old data and next success after closing.
## 8. Dependencies and integration
Root merges CMake with other branches preserving Void::Core public and previously reviewed Async/Rules. Later runtime consumes these primitives; no new native/cross-platform durability claims. Compare upstream actual API and latest registry before raising feature gaps.
## 9. Edge cases security and performance
Check exception surfaces, future lifetimes, retained failures, no success exposed after partial domain mutation, no unsafe catches/rolled-back state claims; UUID/session fence; Windows Unicode paths, sharing, race before/after rename, close errors, relative path rejection and whole contents for readers. Do not equate program-crash publication with durable power-loss protection.
## 10. Acceptance criteria
1. Separate scoped READY/CHANGES_REQUIRED for S16 and S15 with actual locations/impacts. 2. Compare accepted F3 contracts to implementation incl test-on-failure cleanup and producer concurrency. 3. Check real tests, counts and flags. 4. Distinguish legacy limitations from introduced bugs.
## 11. Verification commands and evidence
From each checkout git diff --check; git status --short; inspect explicit new files and matching ranges. /tmp/stoneheart-milestones.xprJ2SVp/session-final-{build,ctest,tag}.log and /tmp/stoneheart-milestones.xprJ2SVp/save-build/Testing/Temporary/LastTest.log and final save-tag/build logs when ready. All computed tests Windows x64 under Wine.
## 12. Constraints and stop conditions
Read only. Return actionable findings immediately. No external writes or blind reruns. If either component needs a repair, identify distinguishing check before re-review.
## 13. Authorization and decisions
User authorized plan, system branches and remote MRs to main. Parent retains authority to publish and rechecks merged components. Review doesn't approve main merge.
## 14. Return format
Return M01-V4 S16 and S15 independently, actual files and tests inspected, severity/code location/rationale for any defect, native and integration gaps.
+48
View File
@@ -0,0 +1,48 @@
# Audit snapshot ownership and checkpoint compatibility
Task ID: M01-V5
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S01-03 actual implementation in /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 at 68f91a2, S15-02 in ../stoneheart_at_home-worktrees/checkpoint detached de38aff. They independently implement immutable owner captures and persisted modern envelopes. Other reviewers cover writer/dispatcher and past S01/19. M01-F3 remains controlling for failure/publication.
## 2. Objective and deliverables
Read-only final independent review of both real source diffs before branch commits. Send per-branch verdicts early. Later integration will be separately verified.
## 3. Scope and non-goals
Review exact changed snapshots/logical field partitioning/lifetime and checkpoint/rule catalog extraction/format gating, tests/limits/headers/CMake. No runtime owner or future custody field required from these narrow slices.
## 4. Files to inspect
Each worktree git status, git diff (tracked changes), explicit new files. Review world.hpp/.cpp, snapshot_tests.cpp, surrounding const rendering/WorldSaveCodec, checkpoint.hpp/.cpp, checkpoint_tests.cpp, rules_manifest.hpp/.cpp, target and actual pinned Void Binary/SHA/Uuids. Read S01-03/S15-02.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children, shared Serena project stays at main game. Direct check worktree source and evidence; you are not an implementer.
## 6. Implementation or investigation approach
Snapshot: reason about every logical field vs executor/cache, copied nested state and observability, no callbacks/pool/references retained, C++ construction/copy/move/const escape/lifetime on exception, no silent public ABI caller break. Checkpoint: check endianness/checksum coverage, length/overflow/allocations before validation, bounded work/memory, no eager megabyte unbounded allocations for tiny malicious body, compare entire installed closure order-independent, identity/tick matching, unsupported versions/trailing data, SHA >16 MiB, named error, independent candidate.
## 7. Interfaces and data contracts
Existing raw save13/LAN11 APIs and exact bytes unchanged. Running captured world is read-only. Modern binary envelope has stable nonnil UUID/city/rules/tick, current body on existing serializer, no on-disk active session/ledger. CMake public types propagate Void::Core.
## 8. Dependencies and integration
Root owns CMake/Git and cross-component integration. S01 path will underpin renderer/background saves, S15 prepares candidate; do not claim they're connected in this slice. Fresh win native/physical tests unavailable here.
## 9. Edge cases security and performance
Investigate invalid input triggering count-based huge allocations despite small outer blob, default/moved-from rules objects, empty rule sets whether legal in resolver, stream consumption/trailing and portability. Catch definite problems in changed surface; distinguish historical legacy-parser behavior. Snapshot test failure-path lifetime/drain warrants attention.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. Identify file and precise trigger/consequence for defects and proposed focused regression. 3. Report current actual build/test evidence and any unverified claims.
## 11. Verification commands and evidence
git -C <wt> diff --check; inspect new files with real paths, /tmp/stoneheart-milestones.xprJ2SVp/checkpoint-{build,ctest,tag}.log (8 checkpoint, 50 core and 4 LAN). S01 capture is 4 snapshot plus full suites and benchmark in same temp folder as capture-* when available. No rebuild needed.
## 12. Constraints and stop conditions
Remain read only; send urgent actionable findings after validating reachability. No speculative redesign, external actions or other agents.
## 13. Authorization and decisions
User approved roadmap and PRs. Parent owns commits/push and review acceptance; local independent branch certification doesn't approve merging main.
## 14. Return format
Return M01-V5 S01-03 and S15-02 verdicts, actual evidence, limitations and any re-review scope. Send first ready ASAP.
+48
View File
@@ -0,0 +1,48 @@
# Verify the combined M01 systems and preflight stable storage references
Task ID: M01-V6
Role: astra_reviewer
Status: READY
## 1. Context and baseline
M01 main worktree /home/faumaray/Projects/stoneheart_at_home commit 2224299 vs earlier integrated cf0cc2f. Reviewed component tips 84a78ef S16, fd17a2f S01 capture, 3844ebb S15 writer, 15da3f4 S15 checkpoint (parent de38aff S19), combined S15 db4ac30. Reviews M01-V4/V5. Separate prospective S06 slice proposed by M01-P3 planner.
## 2. Objective and deliverables
First adversarial integration audit of 2224299 and db4ac30, including actual target union and cross-file operating limits. Second, read-only preflight for replacing runtime positional storage/node references with existing durable IDs. Separate verdicts.
## 3. Scope and non-goals
Only S01/S15/S16/rules integrated surfaces and upcoming first S06 migration. Owner/runtime not yet in integrated commit. No implementation.
## 4. Files to inspect
Inspect git diff cf0cc2f..2224299, all merge parents, s15 CMake db4ac30, primary headers checkpoint/save_service/world/command_dispatcher/rules_manifest and normal callers; logs. For S06 World::edit_object/gather/assign/finish, Agent/MaterialReservation/ConstructionStop, WorldSaveCodec::body/validate/load, viewer resident detail, tests.
## 5. Write ownership and coordination
Write scope: none
No mutations, branches, external actions, children or shared Serena switching. Other agents own future changes, compare named commits only.
## 6. Implementation or investigation approach
Audit merged code vs exact source commits for lost fields, ABI or modules, transitive flags; verify actual native-target build reports core tag counts and compatibility. Check whether max_checkpoint_bytes and SaveService limits align for explicit caller config, typed capture/dispatcher/codec work together. Record any unmet obligations to runtime instead of claiming integration already wired.
## 7. Interfaces and data contracts
First S06 proposal: stored Agent/MaterialReservation/ConstructionStop references to existing sorted Storage.id/ResourceNode.id migrate from index/sentinel to nonzero actual ID/zero none in live memory; bounded lookup via lower_bound or equivalent. Legacy byte layout retains positional fields only inside WorldSaveCodec: stage raw positions during deserialization in separate bounded temporary structures, resolve against fully parsed pools before domain validation; encode inverse mapping and reject invalid refs before writing. Existing public code/callers updated where needed; vector order/indices are transient iteration only. Stable production, transfers and item IDs follow separately. Verify there is no non-reference zero or order interaction that breaks this. Present recommendations for const accessors/source compat as needed.
## 8. Dependencies and integration
Run-time 20Hz, UI/file/lifecycle wiring and larger S04 IDs are future; new S06 can progress with disjoint package files while runtime owns separate files. Root merges/updates Gitea. F3 controls fault bounds. No branch push from reviewer.
## 9. Edge cases security and performance
Review save13/LAN11, root's complete CMake stack and old caller behavior. S06 legacy unordered/invalid data, max sentinel, moving/deleting unrelated earlier elements with active reservations; encoding cost O(N log M) not quadratic searches. M00 goal records nonempty demolition intentional confirmed by human choice; any accounting change separate.
## 10. Acceptance criteria
1. Separate integrated READY/CHANGES_REQUIRED with actual evidence 82/82 core and 4/4 LAN; S15 59/59 +4. 2. First S06 task READY/needs correction with concrete narrow stop conditions and reproducible tests preserving canonical save13. 3. No approval of unseen runtime or native acceptance.
## 11. Verification commands and evidence
git diff --check cf0cc2f..2224299 and git show --cc db4ac30; compare source blobs to each branch, inspect /tmp/stoneheart-milestones.xprJ2SVp/{m01-candidates,s15-combined}-{build,ctest}.log. For S06 inspect real world/codec/HUD paths via targeted graph + source, reachability and smoke fixture behavior.
## 12. Constraints and stop conditions
No edits/builds/Git/remote mutations. Send integrated review immediately. Stop if older valid format or dependency would force distinct migration beyond current scope. Return actionable findings, no speculation.
## 13. Authorization and decisions
User authorizes all system/milestone branches, commits/push and merge requests into main. Root alone publishes cumulative integration. This is final integrated review plus prospective S06 technical gate.
## 14. Return format
Return M01-V6 two verdicts: integrated M01+S15 and S06 preflight. Evidence, limits, actions and native gaps.
+48
View File
@@ -0,0 +1,48 @@
# Recheck S06 allocation limits and audit the simulation owner
Task ID: M01-V7
Role: astra_reviewer
Status: READY
## 1. Context and baseline
M01-V6 accepted system assembly 2224299 but required one S06 design correction. New task S06-01 is in /home/faumaray/Projects/stoneheart_at_home-worktrees/s06 at a4cf99c. Runtime S01-04 implementation is in sibling s01 worktree at 2224299. Reviewer did not implement it.
## 2. Objective and deliverables
First confirm that revised S06-01 resolves the sole preflight finding. Then independently inspect the actual integrated runtime/World/command/clock/publication contracts and new tests before its branch push.
## 3. Scope and non-goals
Stage A preflight limit/failure invariants only. Stage B actual S01-04 core changes, CMake, tests and docs. UI/transport/disk integration not yet present.
## 4. Files to inspect
Read s06/docs/agent-workflow/tasks/S06-01.md sections 6–10 and World allocation positions, S01-04 spec and new simulation_runtime.hpp/.cpp, runtime_tests.cpp, CMakeLists.txt, docs/plan/systems/S01.md. Check previous M01-F3, S16 receipt staging, load API, const captures, pinned headers with actual worker join/clock behavior.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children or shared Serena switching. Use direct actual isolated sources (outside graph). Parent owns all fixes.
## 6. Implementation or investigation approach
A. Confirm MAX terminal, allocation MAX-1 publishes successor MAX before exhaustion, use checked successor before vector/terrain effects, factory overflow vs command Busy, loaded MAX valid, include direct field/mine + add_storage/PlaceStorage. B. Critique single owner restart/load and epoch ordering, short locks, healthy/faulted snapshot read, receipt transaction, active+queued completion and shutdown, fixed deadlines across pause/suspend/exhaustion, concurrency, manual-clock tests and real worker drain.
## 7. Interfaces and data contracts
Read actual SimulationRuntime new header, RuntimeSubmission/Result, LoadTicket, commit/wakeup and scheduling code. Freeze public API only if no correctness gaps. Record how caller retries transient Busy and obtains new contiguous IDs after completed rejects; latest snapshot meta must agree with committed ledger. Check latest request vs current epoch immediately before installation and preserve old publication on failed install.
## 8. Dependencies and integration
Root owns integrations. S06 work begins on stage A verdict. S01 acceptance is limited to tested core; GUI/S15 adapter must acquire healthy immutable save capture and limit bytes. Platform is Windows x64 under Wine.
## 9. Edge cases security and performance
Look for timing regressions from owner using admission clock timestamps, unchecked overflow, transaction window with visible successes after fault, queued mutators in faulted state, settlement of pending loaders/receipts, captured aliases and mutex hold during disk/tick/owner join. Check repeated and failed calls on background owner and teardown.
## 10. Acceptance criteria
1. Return stage A feasibility verdict immediately and stage B independently. 2. Compare source+tag tests to F3 and all required observability/fault/stale boundaries. 3. Report any reachable defect with cause and precise regression. Native acceptance separate.
## 11. Verification commands and evidence
use git -C s01 diff --check; read new files, /tmp/stoneheart-milestones.xprJ2SVp/runtime-{final-build,final-ctest,final-tag}.log. Run no competing builds. For A inspect new contract plus actual world.cpp 396–425, 770–803 and world_save.cpp validation.
## 12. Constraints and stop conditions
Read only. Stop if phase evidence not ready, but return the other independent verdict first. Contact parent for code changes and bounded follow-up if needed.
## 13. Authorization and decisions
User authorizes roadmap, pushes, MRs and upstream issue tracking. Root requests corrected preflight and fresh code review before integrating core runtime. No external actions by reviewer.
## 14. Return format
Return M01-V7 A/B READY/CHANGES_REQUIRED with file/location/evidence, expected symptoms/urgent fixes, counts and residual native/UI risks.
+48
View File
@@ -0,0 +1,48 @@
# Audit the storage and resource identity migration and file adapter
Task ID: M01-V8
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S06-01 isolated worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s06 baseline a4cf99c, separate S15-03 in s15 baseline 8c4c1fe. M01-V6 and corrected V7 preflight S06. M01-F4 accepted S15-03. Both packages have single owners; this reviewer is independent.
## 2. Objective and deliverables
Verify S06 actual full migration/legacy bytes and then S15-03 actual file reader/writer adapter implementation when ready. Give independent per-branch verdicts with real evidence.
## 3. Scope and non-goals
Read-only two component reviews; do not infer viewer is wired or production/stack identity finished. Scope new code only plus changed cross-file contracts.
## 4. Files to inspect
Inspect git diff/status plus new files in both worktrees, actual WorldState/World/WorldSaveCodec/body/validate/HUD/identity_tests and S15 checkpoint_files header/source/tests, SaveService/modern envelope and project tasks. Compare against pinned Numeric/Async/UUID and actual command/loader callers.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children or shared Serena switching. Others own code. Read exact worktree files directly if outside graph.
## 6. Implementation or investigation approach
S06 exhaustively check migration sites including partial no-ref (tending, meal), erase/shift, validated sorted IDs and lower_bound, no deref absent pointers, constructor/command MAX and MAX-1 behavior before effects including mine changes/command sequence, codec preserving old positional bytes, loading malformed pool order/IDs/dangling refs before validation without out-of-bounds. Review real tests and any new allocations/complexity.
## 7. Interfaces and data contracts
S15-03 check one handle path read under bound incl growth/trailing/truncation/EOF, modern magic + bad version cannot downgrade to legacy, fresh stable legacy UUID and default compatible rules, load future and diagnostic/caller action, max_checkpoint_bytes writer, one bounded reader queue plus in-flight, concurrent shutdown, no live worker pointers, progress of writer while reader stalled, snapshots/futures release resources safely under failures.
## 8. Dependencies and integration
Root merges S06 and S15 work; UI and other packages are independent. If S15 not ready yet send S06 verdict first; parent will provide ready files/logs. Per-component review only; native Windows integration later.
## 9. Edge cases security and performance
Check actual pre/post baseline bytes and high-water exhaustion semantics; preserve intentional demolition behavior. Inspect kernel calls and archive validation handling hostile/malformed data defensively. Guard test teardown and multi-GB file size observations. Do not equate program exit with physical durability.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. Report precise reachability + fix/regression for material issues. 3. Check observed test completeness, external trajectory compatibility and tool limits. 4. Name additions needed before combined normal entry.
## 11. Verification commands and evidence
git -C each worktree diff --check; inspect /tmp/stoneheart-milestones.xprJ2SVp/identity-{build,ctest,tag}.log and identity compat/trajectory binaries using wc/sha256sum. file-adapter-{build,ctest,tag}.log when ready. Check newly added files not yet staged for whitespace if appropriate.
## 12. Constraints and stop conditions
Read only. No competing builds. Send an early confirmed finding or verdict on S06. Report S15 only against complete available implementation.
## 13. Authorization and decisions
Root requested two independent checks, user authorizes roadmap system branches/MRs and cumulative pushes. Root retains mutation authority.
## 14. Return format
Return M01-V8 two scoped reported verdicts, real files/commands/counts, untested native or integration requirements and re-review scope.
+52
View File
@@ -0,0 +1,52 @@
# Verify merged logistics references and preflight modern production identities
Task ID: M01-V9
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Main checkout milestone/m01-authoritative-simulation c2d9d8d (parents 512c9ef, S06-01 8260e09); S01-04 integrated at 8c4c1fe. Reviewed S06 and compatibility corpus M01-V8. Next owner migration M01-P3 calls for persistent production IDs in S04 while legacy format13 remains stable.
## 2. Objective and deliverables
Independently verify merged S06+runtime and preflight the concrete S04-01 modern identity + codec migration. Send integration verdict early.
## 3. Scope and non-goals
Integration of actual components only, no assumption viewer already uses runtime. Preflight production IDs only, no broad transfer registry or new region architecture.
## 4. Files to inspect
Inspect git diff 512c9ef..c2d9d8d, both parents and CMakeLists.txt, WorldState/world.hpp, world.cpp, world_save.cpp, checkpoint.hpp/.cpp, S06 identity tests, normal consumers, compat traces. S04 plan M01-P3, existing save13 and checkpoint-v1 writer/parser plus legacy import adapter in s15.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children or shared Serena activation. Other workers continue on their own worktrees.
## 6. Implementation or investigation approach
Verify application blob equality vs reviewed S06 apart from merged CMake and actual registrations/linkage: Math for checked_add, Time public for runtime, tests identity/runtime all active. Analyze unsupported legacy boundary for next stage and identify every order insertion and caller that must reserve a whole ID batch before normal return.
## 7. Interfaces and data contracts
S04-01 proposal: ProductionId nonzero, stored ProductionOrder::id, Agent::production_id (0 absent) and copyable persistent WorldState::next_production_id_. All three insertions (queue_production + two PlaceRoom loops) and every recipe/room/cabin batch share checked allocation, sorted ID vector/lower_bound; valid MAX next terminal never wraps. No partial ordinary acceptance/rejection. Reuse Void Numeric checked operations, upstream #7. Existing raw World::write_save default still v13, exact position projection for older readers; explicit modern raw body v14 includes order IDs, next counter, durable agent refs. Checkpoint encode becomes v2 using v14; decode preserves authentic v1 + old bodies incl valid old legacy imports and rejects inconsistent v2 body / bad version/IDs. New modern canonical replay includes all durable fields; old files import IDs deterministically in vector order with next greater than all. Game session/UUID untouched. Reject duplicate/zero/dangling/current ID, invalid/exhausted batch before mutation; erasing highest then reloading modern snapshot must not reuse it. Isolated S15 file signature classifier uses shared envelope magic, keep unchanged. Legacy wire13 loss of new auxiliary ID history accepted only at its explicit export boundary.
## 8. Dependencies and integration
Root owns cross-component integration. S06 and S04 touch shared World/serializer, so sequence them. Viewer branch will update one resident production lookup during merge; avoid changing S18 normal UI design. Existing legacy public code and normal current renderer must keep working. Require exact statement if prior v1 had stricter/looser body behavior.
## 9. Edge cases security and performance
Inspect O(NlogN) lookup, checked arithmetic including batches; post-decode forward reference resolution; cache/loader behavior incl ordering. How to preserve old test fixtures while schema bumps: freeze old known bytes with successful read. No overwriting current schema fixture pretending compatibility. Watch allocation without effects vs retry/reporting in dispatcher (must preserve world when returning Busy).
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per integrated S06 and S04 preflight. 2. Concrete blockers/acceptance e.g. continued mid-carry world, removed order before unrelated active target, MAX-1 vs >=2 batch, wrong outer/inner pairing, replay serial/2/6/12. 3. Report real aggregate evidence 99/99 core+4 LAN; use old/new binary comparisons from S06.
## 11. Verification commands and evidence
git diff --check 512c9ef..c2d9d8d; git show -m --stat c2d9d8d, compare selected paths to 8260e09 and 512c9ef, inspect actual /tmp/stoneheart-milestones.xprJ2SVp/m01-identity-{build,ctest}.log and identity compat hashes, scoped source/caller reads. No builds needed.
## 12. Constraints and stop conditions
Read only. Send confirmed integration verdict promptly, then preflight scope. No speculation without source validation.
## 13. Authorization and decisions
User authorizes all milestone/system development, pushes, PRs and upstream linkage; parent retains publication/merge authority. These are final integration and design gates.
## 14. Return format
Return M01-V9 integrated and S04 preflight verdicts separately, concrete failure scenarios/test boundaries and unverified native state.
## Additional merge under review
The root subsequently merged the independently reviewed S15-03 commit `a063894` into `c2d9d8d`, producing `4ba64f7` with an automatic CMake merge. Check the added checkpoint file service, classifier, test registration and their actual blobs against the S15 parent alongside the integrated stable-reference codec. Verify `git diff --check c2d9d8d..4ba64f7` and the real `m01-files-{build,ctest}.log` under the same verification directory. The combined suite passed 106 core and 4 LAN cases. Send this bounded verdict separately under the same read-only restrictions.
+50
View File
@@ -0,0 +1,50 @@
# Verify library support for voxel coordinates, chunks and surface picking
Task ID: M02-R1
Role: astra_researcher
Status: READY
## 1. Context and baseline
Approved game roadmap, M02 follows M01 and calls for an editable finite voxel region with 32³ chunks, consistent coordinate/picking/navigation interpretation. No M02 code or branch started. Game root current 60154bd/aa4e271, Void exact CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792 confirmed equal upstream HEAD, source/tests available locally.
## 2. Objective and deliverables
Prepare reusable API and missing-feature evidence so S02/S03/S17 can start under the user's Void-first dependency rule when M01 entry gates settle.
## 3. Scope and non-goals
Read-only M02-specific official/pinned API audit, exact target semantics and minimal verification/issue ideas. Not a game implementation, upstream write, or M02 completion claim.
## 4. Files to inspect
Inspect docs/plan/milestones/M02.md, systems/S02/S03/S17, prior void-library matrix and first_colony/world terrain/render picking, deterministic_rng.hpp. Pin clone /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src including CMake modules, include and tests. Inspect official library headers before claiming absent.
## 5. Write ownership and coordination
Write scope: none
No mutations to tracked/user data, Git/remote writes, public issue creation or children. Parent owns upstream tickets. Temporary isolated compilation probe in /tmp allowed if evidence is genuinely needed; no editing any shared build dir.
## 6. Implementation or investigation approach
Determine exact public support for (1) signed 3D integer coordinates with correct floor division at negative boundaries, checked conversion, fixed-size contiguous chunk index and 6 neighbors; (2) deterministic seed/coordinate hashing and stateful portable random streams with fixed parameters and import/state or existing game RNG; (3) bounded sparse/finite chunk storage, generation version/edit delta/revisions; (4) grid DDA/voxel surface hit and path invalidation by touched chunk revision. Test/document any claimed coverage. Distinguish math primitives to use directly from game-specific policy and genuinely reusable missing capabilities. Check actual dev/test modules/adapters on Windows x64.
## 7. Interfaces and data contracts
Return concrete interface names when present with source/tests at pin and what they guarantee. Root needs precise issue titles, reproducible inputs and replacement tests for actual generic gaps only; avoid a broad request to build the entire game in a shared library. Cover local coords at -1/0/31/32, extreme ranges, 3D axis convention and cross-chunk picking ties.
## 8. Dependencies and integration
M01 stable world ID/epoch/snapshot/checkpoint ownership upstream, future S02 data constructor and S17 ray picking consume that. No assumption M01 fully done; preparatory research only. Confirm whether upstream moved relative to pin via read-only ref if necessary.
## 9. Edge cases security and performance
Do not suggest library nondeterministic RNG for authoritative state when serialization/stream portability absent. Observe D3D renderer right-handed coordinate/picking constraints locally, storage limits and floating vs integer choices needed. Cite files, no private data outside approved repo/library.
## 10. Acceptance criteria
1. Separate supported modules with test evidence vs missing subcontracts; 2. Bounded ownership and exact replacement tests for future implementation; 3. Identify native/other gaps and M02 code dependencies. 4. Relay first actionable library finding early.
## 11. Verification commands and evidence
git rev-parse HEAD and git -C <pin> rev-parse HEAD, targeted rg --files and rg -n on actual symbols and tests, project graph with coverage/direct reads for current app/World when relevant. Source /tmp/stoneheart-verify.KoZwE4o8/env.sh for any standalone Windows probe, no global changes.
## 12. Constraints and stop conditions
Do not open remote tickets or implement new types; notify root with exact evidence. No speculation solely from CMake module names. No further agents.
## 13. Authorization and decisions
User mandates Void support/issue linkage for real gaps; root authorizes this preparatory evidence in parallel with M01 work, without marking M02 started or complete.
## 14. Return format
Return M02-R1 VERIFIED/PARTIAL, pinned paths/API/test names, minimal concrete missing-feature cases and upstream lookup/filing suggestions, native/target limitations.
The Windows x64 probe passed under Wine 11 with GCC 16.2. Native Windows and MSVC remain unverified. Numeric, canonical little-endian Binary fields, FNV-1a, seeded raw Xoshiro output and graph traversal limits are available on this target. Each missing reusable operation has its consumer and replacement check in the [dependency matrix](../../plan/void-library.md#подготовка-воксельного-мира-m02). Upstream records cover [restorable random streams](https://git.faumaray.com/Void/Library/issues/10), [Euclidean division](https://git.faumaray.com/Void/Library/issues/11), [grid ray traversal](https://git.faumaray.com/Void/Library/issues/12), [revision dependencies](https://git.faumaray.com/Void/Library/issues/13) and [atomic sparse volume edits](https://git.faumaray.com/Void/Library/issues/14).
+50
View File
@@ -0,0 +1,50 @@
# Persist production order identities and allocate complete command batches atomically
Task ID: S04-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s04 system/s04-jobs-reservations base 4ba64f7. WorldState includes capture, S06 durable storage/node refs. S15 envelope v1 accepts raw World v1–13. M01-P3/V9 identified all insertion and refusal paths including storage demolition replenishment and LegacyCabinPayload in S16. Upstream durable allocator #7.
## 2. Objective and deliverables
Give every production order a persistent World-scoped ID, remove stored positional production references, preserve identity history in modern checkpoints while keeping original saves/wire exact, and make all order-allocating business commands reject exhaustion without partial effects.
## 3. Scope and non-goals
Production identity, high-water mark, ABI/caller migration, modern raw/envelope generation and validated v1 import. Keep zero none, leave new stack/ownership/transfer records and broad economy behavior to later slices. Preserve historical default formatting/encoding and v11 public network.
## 4. Files to inspect
Inspect world.hpp, world.cpp all insertion/erase/use sites and missing_carpentry_orders, world_save.cpp body/validate, checkpoint.cpp/.hpp/checkpoint_files.cpp, command_dispatcher.cpp catches LegacyCabinPayload, viewer resident detail, existing tests and old baselines. F3/F5, M01-P3/V9. Inspect/preserve exact pinned Void Numeric/Binary/Crypto and prior deterministic corpus.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; engine/src/command_dispatcher.cpp (only legacy cabin exhausted outcome); app/viewer_win32.cpp (resident production details only); tests/core_tests.cpp; tests/identity_tests.cpp; tests/replay_tests.cpp; tests/production_identity_tests.cpp (NEW); tests/checkpoint_tests.cpp; tests/checkpoint_file_tests.cpp; tests/session_tests.cpp; CMakeLists.txt; docs/plan/systems/S04.md
Only touch listed affected tests/callers as needed. Other owners touch UI, files, profiles elsewhere. You are not alone; root integrates branches. Do not edit other worktrees/Git/Serena.
## 6. Implementation or investigation approach
Add real ProductionId, immutable order identity, WorldState::next_production_id_, Agent::production_id (0 absent), bounded sorted lookup, erase without index repair. Centralize all order insertion incl queue_production and both direct PlaceRoom loops. Calculate exact whole ID requirement and incrementable successors before any command/domain side effect. Single and multi-order (bed, loom, workshop, rooms/furnishings, direct cabin and implicit replenishments) precheck numeric exhaustion as well as vector allocation. MAX terminal valid, last allocatable MAX-1. Calculate EXACT post-demolition missing carpentry counts across products/requirements WITHOUT erasing/mutating storage first, reserve all IDs before deleting stock or appending any order. If full batch cannot fit return nonmutating Busy with exact old storage/stock/sequence and counters. For LegacyCabinPayload use explicit testable pre-mutation exhaustion result/exception, narrowly translate THIS proven refusal to completed Busy in CommandDispatcher::apply, retain exact repeat while session remains healthy. Do not catch a generic error that could follow partial mutation. Other unexpected errors use F3 fault boundary. Avoid duplicated independent registries.
## 7. Interfaces and data contracts
Default World::write_save(std::ostream&) still emits exact v13 bytes and historical positional links, old callers incl LAN11 unchanged. Add explicit modern World write mode v14 (new actual enum or method) using same codec/body, include stable refs / order IDs/high-water; now World::read_save handles appropriately. Checkpoint encode becomes schema2/modern body14. Decode authentic schema1/inner1–13 and schema2/inner14 only, verify signature & checksum using common codec, latest high-water after deleting last/highest/all survives. Historical import assigns IDs deterministically in vector order with next > live max; no new UUID on modern reload. Validate sorted unique nonzero ProductionIds, strictly larger next (MAX valid), referenced target existence/state before indexing. Keep envelope magic unchanged. Old file-adapter test hardcodes unsupported next value 2: change to actually unsupported value and retain a true pre-change v1 fixture, not just changing expected bytes. Tell root exact frozen API early.
## 8. Dependencies and integration
Root owns final merge. S18 worker also touches UI but not resident-detail lookup; S19 profiles separate. File reader matches same signature and uses generic decode; ensure outer/inner pairing tests even when attacker recalculates both checksums. Registry consumers continue using const World. Use existing checked arithmetic; local implementation+replacement link Void/Library #7 in docs and allocation source where useful.
## 9. Edge cases security and performance
Avoid O(N²) repeated scans of million-record parsed data; legacy index projection/import bounded as in S06. Active resident must keep same original order when lower deleted. All domain normal refusal keeps previous capacity/contents/command seq; last accepted identifier remains unaffected by vector erasure, world capture or save. Ensure no different command arbitration/legacy behavior on ordinary non-exhaustion. Preserve legal old v1–v13 payload behavior. Do not overwrite any user save.
## 10. Acceptance criteria
1. Deleting lower/highest/all orders followed by v2 reload + allocating another never reuses IDs, actual mid-haul agent remains bound; corrupt ID/dangling/current combinations rejected. 2. MAX/MAX-1 single and multi batch incl room/cabin/stock demolition with multiple products, verify byte-identical complete current state/unchanged seq after Busy, and exact replayed cabin Busy with healthy runtime. 3. Authentic checkpoint v1 lower inner and v13 accepted, wrong pairing incl v1/14, v2/13 rejected with valid checksums. 4. Per-tick MODERN canonical replay including ID state across serial/2/6/12, old default v13/legacy benchmark data compare exact. 5. All cross suites pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/production-id-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag production-id, full verbose CTest, git diff --check; fixed binary compatibility corpora at /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin, baseline 4ba64f7 artifacts. Save logs production-id-*. No synthetic recreation of a golden old checkpoint with the new encoder.
## 12. Constraints and stop conditions
No broad rewrite or custom replacement for supported Void primitives, branch changes or further agents. If existing unknown pre/post mutation exception means a Busy lie, stop and send contract+counterexample. After two failed repairs raise distinct hypothesis with evidence.
## 13. Authorization and decisions
User authorizes all milestone/system features, commits/push and merge requests. M01-V9 requested exact demolition and cabin corrections; parent obtains narrow preflight recheck before dispatch. Root owns all side effects.
## 14. Return format
Return S04-01 READY/BLOCKED, public format and ID APIs, actual coverage of all allocation sites, clean failure outcomes, compatibility corpora hashes/tests, and remaining later custody/native risks. No children/commits/push.
The middle-of-delivery assertion in `tests/snapshot_tests.cpp` also reads the removed production index. The implementer owns its equivalent check of the stored nonzero production ID.
+48
View File
@@ -0,0 +1,48 @@
# Resolve stored logistics references by stable storage and resource IDs
Task ID: S06-01
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s06, system/s06-logistics begins a4cf99c. M01-P3 mapped World+codec+UI references, M01-V6 requires checked exhaustion for all storage/node allocation paths. Actual WorldState groups the complete capture; modern v1 checkpoint embeds format13; legacy tests 1–13/LAN11.
## 2. Objective and deliverables
Migrate live Agent::resource_node_index and storage_index, MaterialReservation::storage_index and ConstructionStop::storage_index to the selected objects' existing nonzero IDs. Deleting an earlier unrelated element must preserve all targets and quantities. Cover restoration and ID exhaustion.
## 3. Scope and non-goals
Only S06-01 storage/resource references and checked allocation at all existing sites. Production index and next agent/job/production counters have their own later contract, stack/reservation/transfer identity comes later. Preserve deliberately confirmed stock demolition behavior. No public new network protocol, geometry, checkpoint schema or UI feature.
## 4. Files to inspect
Inspect world.hpp, world.cpp, world_save.cpp, first_colony.cpp, viewer_win32.cpp resident detail, graphics/callers including benchmarks, core/replay/snapshot/checkpoint tests. Read S06/S04, M01-P3/V6, pin Math/Numeric.hpp checked_add and Core/Counted.hpp. Use stable-vector ordering validated by WorldSaveCodec. Verify existing API users by rg.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; app/viewer_win32.cpp (existing resident-detail reference access only); tests/core_tests.cpp; tests/snapshot_tests.cpp; tests/replay_tests.cpp; tests/checkpoint_tests.cpp; tests/identity_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S06.md
Other code owners operate in isolated branches. You are not alone; do not revert others or change Git/shared Serena. Modify existing tests only for changed ref semantics, not to weaken checks.
## 6. Implementation or investigation approach
Use zero as missing typed ResourceNodeId/StorageId, remove positional fixups for these members everywhere. Expose read-only bounded ID lookup and reuse ID-ordered lower_bound or equivalent. Keep indices ephemeral inside assignment and validation count arrays. Encode ID→old positional one-based/sentinel fields exactly; decode raw positions in explicitly bounded loader temporaries then convert to IDs after referenced arrays are populated and order validated, before world domain validation/use. Reject out-of-range/missing ID before indexing. Keep production_index/no_entity_index independent. Preserve ordering, deterministic routes and complete old wire bytes. Write source comments with linked replacement test for Void/Library #7.
## 7. Interfaces and data contracts
ID exhaustion: UINT64_MAX in next_* is a legitimate terminal high-water mark, last allocatable ID is MAX-1. Precompute checked successor with pinned Void::Numeric::checked_add before world/vector/terrain effects in World::add_resource_node, World::add_storage AND direct Place{BerryField,TreePlot,FlaxField,Mine} and PlaceStorage command paths. Only commit counter after successful construction/insertion. No returning zero, wraparound or duplicate IDs. Direct factory exhaustion raises std::overflow_error, commands return non-mutating Busy without consuming legacy sequence. For MAX-1 exactly one insertion then a stable serialized exhausted world. Validate invalid refs and preserve existing stronger invariants/canonical old bytes.
## 8. Dependencies and integration
Root owns CMake merge, dependent runtime/GUI packages, Git and upstream. Void/Library #7 covers restorable checked sequences; #8 is later custody, pinned Void Numeric handles arithmetic now. Preserve current std::unique_ptr<World> factories/mode, Render const path, standalone tests. No compatibility alias which silently restores use of vector indices.
## 9. Edge cases security and performance
Mid-carry before/after erasing earlier store/node, pantry meal, site tending with no storage, construction multi-stop delivery, carpenter output reservation, active targets remain protected by existing rules. Guard lookup for none/dangling, sorted IDs and caches. Ensure fast logarithmic lookups; avoid O(N²) scans or per-agent linear scans during codec, no duplicate durable map to synchronize. Check max vs max-1 inputs, failed insertions and byte-level determinism. Use pre-migration external baseline or saved corpus to verify exact bytes when gameplay equivalent.
## 10. Acceptance criteria
1. Live references preserve meaning after erasing an earlier unrelated store/node; no shifted refs remain in runtime. 2. Capture, legacy save13, checkpoint roundtrip and serial/2/6/12 trajectories agree mid-haul. 3. MAX/MAX-1 at every allocation path, including mine blocked-cell/cache on rejection. 4. Damaged legacy indices reject candidate, no partial live mutation. 5. All tests/cross build pass incl baseline, focused identity tests and project docs.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/identity-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag identity, verbose CTest, git diff --check. Cross-baseline compare relevant old outputs; root shares /tmp/stoneheart-milestones.xprJ2SVp/trajectory.cpp & old-trajectory.bin. Report actual bytes/scenarios and time if performance measured.
## 12. Constraints and stop conditions
No side effects outside checkout/build/log temp. Stop if current wire cannot represent migrating these existing IDs without loss, or a supported caller needs out-of-scope change, or after two failed repairs of the same issue. Do not silently drop malformed/legacy data.
## 13. Authorization and decisions
User authorizes all milestone/system implementation, upstream issues, commits and PRs. M01-P3 proposed slice and M01-V6 preflight correction is incorporated here; root confirms narrow corrective re-review before dispatch.
## 14. Return format
Return S06-01 status, actual files/lookup and legacy conversion boundaries, overflow/Busy semantics, commands/counts, cross-baseline byte evidence, remaining limitations. No children/commits/push.
+50
View File
@@ -0,0 +1,50 @@
# Apply a complete reserved pickup to one resident atomically
Task ID: S06-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated system/s06-logistics worktree s06 at a8cd7bb (S04 ProductionId/current14, S19 selectable rules, S06 stable StorageId). Meals and construction stops call take_reserved_material then Inventory::add, and a carpentry output reserves a new storage slot at its first ingredient pickup. Earlier M01-P5/F7 require whole-stop preflight. Existing finish_production also calls take_reserved_material for direct storage→recipe consumption, a different operation.
## 2. Objective and deliverables
Implement checked all-or-nothing physical pickup in both real meal and construction stop paths, including a carpentry output slot when applicable. Retain normal simulation bytes/timing. Cover overflows, split duplicate material entries and late failure before mutation.
## 3. Scope and non-goals
No save version, StackId, worksite ownership, reservation ID, journal, general-purpose database or protocol change in this slice. Keep existing direct recipe consumption in finish_production. Stage only future work in appropriate system notes.
## 4. Files to inspect
Read engine/include/settlement/core/world.hpp Inventory/Storage/ItemStack/MaterialReservation, engine/src/world.cpp named consumers, world_save.cpp validation/legacy split records, tests identity/production_identity/core/replay, and S06 documentation/linked Void #8. Consult pin include/Void/Math/Numeric.hpp checked_add/sub. Root baseline cumulative a8cd7bb.
## 5. Write ownership and coordination
Write scope: engine/src/world.cpp (narrow meal/construction stop pickup and related local helper); NEW engine/include/settlement/core/inventory_transaction.hpp and engine/src/inventory_transaction.cpp if needed for a shared testable operation; NEW tests/quantity_transaction_tests.cpp; CMakeLists.txt only source and test entries; docs/plan/systems/S06.md
Exclusive to your isolated s06 worktree. Others work in sibling worktrees. Do not revert others' changes or edit unrelated methods/world_save/UI or shared Serena state. Root owns Git and remote.
## 6. Implementation or investigation approach
Use one bounded operation over a single Storage and resident Inventory, evaluating present source/reserved counts, aggregate duplicate participating lines per type, and checked destination increments. If using the whole order span, choose only lines at the current storage; a missing/zero/invalid selection fails. Reject invalid types/None, zero amount, overflows, insufficient reserved or count and reserved>physical. Preserve source stack order, prune zero stacks without allocation; prevent throws between first and last logical writes. Use the existing checked Numeric API. For carpentry precompute reserved_slots successor and ensure post-withdrawal total_items+reserved_slots<=capacity before any quantity write; move commit/route/cursor only after success. No per-line mutating call before complete preflight. Failures observed by the owner must preserve last healthy publication. Avoid needless repeated lookup/allocations.
## 7. Interfaces and data contracts
Prefer one simple domain function returning std::expected<void,typed quantity diagnostic>; exact type and header naming locally flexible. Application entry precondition is pickup-function entry: World::step may already advance walking position/route_cursor earlier in the tick. On pickup rejection, no additional stop, inventory, reserved slots/stock, route replacement or state transition; never publish partial transfer. Cover zero/foreign-only or out-of-range data; existing legitimate repeated material entries aggregate. Raw13/LAN11 layout stays byte exact and modern Current14 shape stays the same.
## 8. Dependencies and integration
Root owns merging this branch to milestone/integration and cross-branch checks. P5 future durable IDs and reservations will consume this operation. S04-01 and S19-02 are already present; S18 UI can proceed independently.
## 9. Edge cases security and performance
Data bounds as provided by old loader; max distinct types item_type_count, avoid allocating proportional to a user-provided count. Do not wrap at uint32 max on destination, source/slot arithmetic or sum. Source storage count/metadata may be inconsistent on direct test input; fail safely. No total mutable parallel ledger. Minimize impact on World::step hot path.
## 10. Acceptance criteria
1. Source/dest byte-equivalent on success for valid meal and multi-material/multistop/carpentry paths, tested from production code. 2. A two-item stop late failure plus cumulative duplicate and destination overflow leaves all stock/reserved/capacity/inventory unchanged. 3. Successful exact depletion removes zero stack, respects source order and reserve slot. 4. Replay serial/2/6/12 modern checks and both old byte corpora unchanged. 5. Document limits separately from future custody and link Void #8 replacement.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/quantity-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Use --tag quantity-transfer on new tests, CTest -V, git diff --check; /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin old golden outputs were checked by s04 (portable projection probe sources in same directory). Keep verification logs quantity-* in that temp root.
## 12. Constraints and stop conditions
Do not fake output inventories for finish_production or weaken legacy validity, add unrelated changes or use unbounded copies. Alert root if actual code contradicts the contract. Root owns commit/push/MRs/upstream issues. After two failed same-cause repairs escalate; no children.
## 13. Authorization and decisions
Approved M01 item conservation and per-system development. F7 corrective terms are included above. Conditional batch issue Void/Library #8 already registered; parent owns external tracking.
## 14. Return format
Return S06-02 READY or PARTIAL, owned files, exact tradeoffs/failure boundary, actual tests/golden output, any native and deferred full-custody limitations. No Git/remote operations.
F7 corrections are binding. Item indices are checked against 1..item_type_count before using type−1. Aggregate nonadjacent duplicate lines, handle an absent stack, and preserve the original first material's storage as the output source even when it is visited after another stop. No stale iterators may survive zero-stack removal. Include valid exact UINT32_MAX destination count, multiple erasures with unrelated surviving stacks, full storage freeing exactly one carpentry output slot, invalid slot/capacity state rejected before physical transfer, and direct storage→output production compatibility.
+50
View File
@@ -0,0 +1,50 @@
# Track real item ownership from sources through worksite and cancellation
Task ID: S06-03
Role: astra_implementer
Status: READY
## 1. Context and baseline
Exclusive s06 worktree f6493e2 has checked pickups (3c997ed), durable ProductionId, current14, S18 snapshot client. docs/plan/custody.md and root M01-F8/P5 contain binding full model. Existing World loses physical cargo on arrival at a construction site; its recipes and storage share ItemStack, and historical source leases continue until production completion. S15 peer independently captures authentic historical fixtures and implements codec.
## 2. Objective and deliverables
Implement authoritative physical ownership and bounded reservation/transfer lifecycle on every current inventory-affecting game path: grant/stock, extraction, meals, crafting, construction, return and demolition. Provide frozen in-memory data/validation contracts early for S15, raw13 representability for S16 and cancel/resume for S04. Do not publish a half-integrated version.
## 3. Scope and non-goals
Existing modeled item types/jobs/recipes only. No regions, filters/marketplace, scripts, new graphics or custom database. World and actual operation record are the source of truth. Authoritative persistent codec, command adapters/live LAN and UI are separate owned work packages.
## 4. Files to inspect
Read docs/plan/custody.md, plans S04/S06 and root F8/P5 (root and s06). Read entire world.hpp/world.cpp incl assign/step, stock/sources/idle/meal/all recipes, inventory_transaction, writer/validation in world_save.cpp, current schema2 and capture/runtime/old replay tests. F8 corrections on held old source IDs, work_remaining=0 and unsupported legacy states apply.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/include/settlement/core/inventory_transaction.hpp and engine/src/inventory_transaction.cpp; NEW engine/include/settlement/core/custody.hpp and engine/src/custody.cpp or narrow related source files for actual World operations; NEW tests/custody_tests.cpp; CMakeLists.txt limited to own implementation/tests; docs/plan/systems/S06.md
S15 exclusively owns all world_save/checkpoint/fixture changes, S04 later command dispatcher/cancel UI, S16 LAN. You may declare WorldSaveFormat::Current15 and agreed in-memory migration/validation seam in owned header. Never write other branches/Git/remote/Serena/children; other workers share filesystem.
## 6. Implementation or investigation approach
Separate recipe requirements from owned stacks. Embed one nonzero durable StackId per nonempty owner/item slot. Full move into empty retains ID; splitting allocates once; merging keeps destination ID; move matching ReservationIds and keep other source reservations. World-owned counters 0 none, MAX exhausted, plan all required IDs/counts/physical capacity/balance entries/receipt storage and allocations before effect, with nonthrow final commit. Single physical count per storage/resident/ProductionId input; caches exclusively updated/rebuilt from claims. Restore snapshot copies without stale pointers. Source/sink tracking Opening+Grant+Harvest+RecipeOutput equals live+RecipeInput+Meal+Installation+StorageDemolition. Use Void::Numeric and existing #7/#8, avoid O(N²) global scans in hot step. Preserve real original source and timing/game decisions in normal v13 trajectories.
## 7. Interfaces and data contracts
AgentId+positive durable next_admission (starts 1) keys admission; distinct tagged key namespace from TransferId+ordinal. On admission record exact request and issued transfer and increment next_admission together; pre-admission refusal unchanged. Persistent next available IDs avoid reuse; active single execution per worker. 4096 global receipts in commit order, each canonical typed input and outcome <=1024 bytes each, no opaque hash-only comparison or arbitrary route payloads. Normalized source/material lines max actual recipe units (cabin five positive units across different storages), bounded stock kinds, typed data. Retained duplicate same bytes gets exact result, conflict distinct payload, evicted old sequence Stale, future unissued rejected. Retired receipt references may identify no-longer-live objects but must be in issued ranges. Prefer compact immutable shared payloads/COW for retained snapshots; account memory/time at full retention.
## 8. Dependencies and integration
Reservations distinct for exact item+owner, output capacity, worksite, harvest/tending. Input-backed output slot links the actual ReservationId in the same store; never counted or backed twice. Preserve old origin-storage lease until work finishes for Move/Demolish Busy. Worksite arrival moves real goods into order input, consumed only at stage completion. Research genuine existing guarantees and send actual frozen declarations immediately to root, including explicit entries/interfaces for S15 legacy migration, strict modern full validation and pure legacy representability. S04 needs World::cancel_production(ProductionId) and World::resume_production(ProductionId) or equivalent typed result. S16 needs pure preflight that correctly recognizes ALL unsupported modern states incl single canceled plank/stone-block, absent destination, partial mixed return and suspended site.
## 9. Edge cases security and performance
On cancel pre-pickup release claims; in-transit/at-site cargo remains with same transfer/worker until all types actually deposited, with meaningful blocked reason and persistent no-destination status. Partial return exact, do not allow meals/rest/new jobs while carrying. Canceled staged bed after prior installation or already built recurring loom remains suspended under same ID/occupancy; explicit resume continues retained phase without duplicated inputs. Installed/completed final objects refuse cancel. Historical demolish/move occupied semantics continue. Completion with zero remaining and temporary refusal is a valid modern pending phase; never unsigned-decrement 0 on retry, new ordinal on actual retry; reject legacy projection if not exact. Before destroying stock record exact reason/qty and preflight replenishment production IDs as in S04.
## 10. Acceptance criteria
1. Live single ownership and conservation for all current paths including partial splits/merge, last item, storage disappearance and worksite delivery before consumption; exact conditional refusals and repeat/eviction/conflict. 2. Cancel/return at each stage incl full/no storage and suspended partial bed/installed loom resume; actual normal World operations. 3. Snapshot immutability and deterministic serial/2/6/12, old raw13 corpora remain exact. 4. Tests for zero/MAX/overflow, duplicate/cross-owner and exhaustion, last active worker and terminal failure. 5. Frozen schema integration passes with S15 before public delivery; provide measured 500 resident, ~10K stack/2K order and full/empty 4096 receipt state costs where technically applicable.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s06-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Focused new custody tag and CTest -V; both existing byte regression probes in temp dir; S15 tests/migration validation added after interface merge. Capture p50/p95/size and actual benchmark workload/environment (5ms p95 initial Wine capture budget, disclose measured values). Use s06-custody-* logs. Keep fixtures and user saves private/isolated.
## 12. Constraints and stop conditions
Send concrete C++ data declarations/API seam before broad implementation so S15 can progress; do not generate or edit schema15 on disk yourself. Preserve public Inventory/Storage read-facing APIs and existing behavior relied on by old tests. Never ship/claim completion until integrated codec and cancellation boundaries; alert parent on needed scope/ownership or two failed same-cause attempts. No children/Git/remote.
## 13. Authorization and decisions
User authorizes complete roadmap. Root accepts compact bounded retention, embedded single-owner stacks and verified F8 corrections; normal multi-stage behavior and legacy bytes remain mandatory. Root integrates and publishes only fully verified compatible state.
## 14. Return format
After local candidate `4f4c038`, S15 observed that a retained admission can be authenticated with repeated reservation IDs, even though the allocator always issues distinct increasing IDs. Inspect canonical emitters and reject repeated issued reservation IDs or demonstrably duplicate identical effect rows, including after the referenced actor/stack has retired. S15 adds authentic malformed fixtures in its own files. Verify genuine consumed-through-zero and valid split/merge results continue to pass. Use the same exclusive scope, tests, and Gitea restrictions.
Return S06-03 status, frozen seam early, actual source/operations/remaining integrations, tests/goldens/perf logs. Clearly identify original old boundary vs actual strengthened ownership and any native limitations.
+48
View File
@@ -0,0 +1,48 @@
# Prepare checkpoint files in the background for the interactive client
Task ID: S15-03
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive s15 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s15 system/s15-persistence fast-forwarded to 8c4c1fe. Includes verified runtime PublishedSnapshot, S15 checkpoint and SaveService + builtins. M01-F4 accepted bounded background file adapter; #3 is the linked Windows atomic-write contract.
## 2. Objective and deliverables
Supply a usable persistence adapter for the real window: submit save of a held PublishedSnapshot, prepare a modern or legacy file asynchronously into a complete WorldCheckpoint; no disk or parsing on UI/owner thread.
## 3. Scope and non-goals
Only S15 file API/implementation and test/docs/target integration. Viewer itself and its load-ticket/feedback lifecycle are owned separately. Existing SaveService handles writes; existing World/checkpoint codecs handle validation.
## 4. Files to inspect
Inspect actual simulation_runtime.hpp (PublishedSnapshot immutable), checkpoint.hpp/.cpp, save_service.hpp/.cpp, rules_manifest.hpp/.cpp, world_save.cpp signature/limits/validation, viewer current dialog/select and file handling. Review Void Async ThreadExecutor/FuturePool lifetime/admission tests and pinned Windows IO coverage. M01-V6 requires max_checkpoint_bytes.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/checkpoint_files.hpp; engine/src/checkpoint_files.cpp; tests/checkpoint_file_tests.cpp; CMakeLists.txt; docs/plan/systems/S15.md; engine/include/settlement/core/checkpoint.hpp and engine/src/checkpoint.cpp only if needed to expose canonical signature recognition
No changes to other worktrees/Git/Serena/Win32 UI. You are not alone; other workers own runtime, LAN, UI, World/custody. Parent integrates CMake.
## 6. Implementation or investigation approach
Introduce NEW CheckpointFiles owning one existing SaveService configured max_checkpoint_bytes and a bounded pinned Void reader executor/FuturePool. try_save(absolute path, shared_ptr<const PublishedSnapshot>) delegates to existing queue, producer owns const world/manifest and runs encode_checkpoint on writer. Caller acquired healthy snapshot already. try_load(absolute path,... immutable installed catalog, workers/mode) returns immediately with explicit admission and accepted future/typed diagnostic or complete candidate. Provide useful error for file access, limits, legacy decode, missing package etc. For modern signature call decode_checkpoint only, never downgrade after a modern failure. For legacy signature parse validated World::read_save and attach fresh stable nonnil UUID, city1, default supported manifest. Preserve exact prior old v1–13 paths; don't invent a mutable live session. Open each path once, enforce maximum read incl growth/EOF before consuming unbounded storage. Reader/writer can run independently; hold input/catalog through work, drain on shutdown.
## 7. Interfaces and data contracts
Communicate exact header early. Constructor may own shared immutable installed catalog (default builtins) to simplify caller. Caller keeps this service for window lifetime across runtime resets; jobs never capture viewer/raw runtime or call GUI. Return SaveSubmission or precise adapter result preserving prior SaveService metadata. Reader producer can use an optional bounded observer/gate for deterministic tests following existing failure hooks if needed. No thread per file; explicit bounds & stable closed admission. Busy or invalid admission does not consume caller data. Viewer handles begin_load tickets/replacement policy, reporting and 32×32 restriction.
## 8. Dependencies and integration
Root wires UI later, receives filled result and verifies dimensions before SimulationRuntime::try_install; runtime itself rechecks epoch/ticket. Old valid file import gets a fresh stable ID on each explicit import. Default `.settlement` existing extension and title paths maintained. Store upstream #3 link where relevant; pinned Void supports asynchronous running and file codecs as documented. No external actions.
## 9. Edge cases security and performance
Check Unicode filesystem path, open-one/read-one with changing files, oversized declared/actual data (bound including growth), corruption/trailing/truncation distinctly, catalog mismatch names missing package, nil UUID generator error, concurrent submit/shutdown/read queue/in-flight count, writer retains held snapshot after source advances. Avoid throwing from worker leaving pending futures. No double-opening for format detection, no fallback rewriting files. Track native/Wine differences.
## 10. Acceptance criteria
1. Roundtrip actual immutable old snapshot through production save helper to file then load to independent candidate; live world progresses meanwhile. 2. Open true legacy fixtures and modern mismatches; invalid/oversized/trailing/frame corruption rejects. 3. Bounded and closed reader, deterministic held reader blocking test shows UI submit and writes/other work independent, shutdown drains, next read succeeds after bad file. 4. Normal cross build and old suites pass. 5. Frozen interface is usable for viewer async polls without lifetime hazards.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/file-adapter-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag checkpoint-file, full verbose CTest, git diff --check; files in new temporary Windows directories. Name logs file-adapter-*.
## 12. Constraints and stop conditions
No editing viewer/custody, raw live World access from workers, remotely written actions or new external deps. If architecture requires a new generic capability report it to root. Two failed fixes for the same issue require escalation.
## 13. Authorization and decisions
Root owns all Git; user approved roadmap and asked maintain PR/cumulative/issue tracking. F3/F4 and V6 freeze acceptance; Windows physical tests follow separately.
## 14. Return format
Return S15-03 READY/BLOCKED, early concrete signatures for viewer, owned paths, complete tests/observations and limitations. No children/commits/push.
+48
View File
@@ -0,0 +1,48 @@
# Migrate historical cargo and persist modern custody atomically
Task ID: S15-04
Role: astra_implementer
Status: READY
## 1. Context and baseline
Isolated s15 worktree f6493e2. Stable read-only historical checkout /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14 at same ref, old Windows build available. Current published checkpoint schema2/body14, schema1/body1–13. S06-03 under construction in sibling s06 exclusively owns World types/normal transitions, will supply concrete data declarations via parent. Source-grounded M01-P5/F8, docs/plan/custody.md include full decisions.
## 2. Objective and deliverables
Capture genuine old schema2/raw14 fixtures now, then implement canonical raw15/checkpoint3 encoding, strict validation, bounded migration of prior genuine worlds and before-output typed rejection of unrepresentable raw13 states. Complete end-to-end after root integrates S06 schema declarations into this worktree.
## 3. Scope and non-goals
Persistence/codecs and validated restored state only. No World gameplay changes, command dispatcher, UI, net or new dependency. Data snapshots/custody/command semantics remain owned by sibling S06/S04. Do not invent temporary independent schema if peer interface pending; use that interval for golden collection and historical phase audit.
## 4. Files to inspect
Read root/S06 docs plan/custody, M01-F8, old world_save.cpp full validator and historical fields, checkpoint.hpp/.cpp, checkpoint_files.cpp, world.hpp current14, new custody declarations when supplied, existing tests/checkpoint*, identity/production_identity/replay/snapshot/quantity, pinned Binary budgets and hash. Fixtures old source and golden corpus/probe helpers in /tmp/stoneheart-milestones.xprJ2SVp. S15-03 already version/size-safe reader/write service.
## 5. Write ownership and coordination
Write scope: engine/src/world_save.cpp; optional NEW engine/src/custody_save.cpp/internal header for supported codec; engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; engine/src/checkpoint_files.cpp only as genuinely required; tests/checkpoint_tests.cpp/tests/checkpoint_file_tests.cpp/tests/snapshot_tests.cpp only for schema/current snapshot checks; NEW tests/custody_migration_tests.cpp and concise frozen fixture data if needed; CMakeLists.txt limited to registering owned codec/test sources; docs/plan/systems/S15.md
Do not change world.hpp/world.cpp (S06 owner), dispatcher or LAN/app. Other agents work in sibling checkouts; never revert their work. Root will integrate S06 headers when ready. No Git/remote/children or shared Serena switch.
## 6. Implementation or investigation approach
First capture authentic schema2/raw14 from old binary before peer edits. Include fixed seed/UUID, actual legacy Working worksite after pickup, between stops/hauled product, normal/direct order, staged simple as applicable. Preserve original bytes or minimal readable hex fixture + provenance+SHA and exercise actual decode; do not generate expected old bytes using new writer. Parse/check input under historical schema first; preserve true unused/complete routes. For versions before 5 preserve sleep normalization, versions1–8 historical footer/different fields. Old Working delivery order with stops cleared/no resident material reconstructs exactly validated input at ProductionId; direct SawPlank/CutStoneBlock/WeaveCloth inputs stay in storage; post-carpentry output belongs to resident, no active production link. Meal and tending phases distinct. Allocate migrated IDs deterministically by owner kind/ID/item, active execution by AgentId. Opening balance computed only after implicit site stock reconstructed. Migrated active admission generation1,next2, no fabricated receipt, inactive next1.
## 7. Interfaces and data contracts
Explicit schema table 1→body1..13, 2→14, 3→15 with digest before decoding, no version-constant-only dropping v2. Strict authenticated body15 data includes all counters/IDs, owner stacks incl site, live execution+claims/capacity backing and source leases, saved phase/pending completion/suspended partials, opening/source/sink totals, exact canonical creation+ordinal receipt ring incl bounds/retired refs. Enforce sorted unique live identities, ID nonzero/less-than valid highwater, one owner, references/counts/claim capacity and valid reservations; historical receipts may name retired IDs below issued highwater, never demand liveness of those refs. Reject modern missing/inconsistent states; no rematerializing missing modern data. Original current14 vs Legacy13 outputs must remain available as defined. Use shared S06 pure validation/projection method where feasible; avoid duplicate simulation/codec rules.
## 8. Dependencies and integration
Raw13 projection performs complete legacy representability check BEFORE first externally written byte incl single Plank/StoneBlock canceled orderless haul, mixed cargo, missing dropoff, suspended residual bed/loom, zero-completion pending or other modern combinations. Signal typed UnsupportedLegacyState from agreed core type for S16. Preserve valid historical reserved counts/source storage leases, stops and route metadata, actual frozen old byte corpora exact. Modern persistent codec must save unsupported-on-LAN states safely. Parent handles per-worktree header merge; report exact needed seam early. Avoid a 128MiB scratch copy just to detect unsupported states when pure preflight suffices.
## 9. Edge cases security and performance
Strict 128 MiB body/existing size limits/1M collection caps and exact 4096 receipts, <=1024 bytes each request/result, checked iteration/preallocation budget/count arithmetic before allocation. No hash-only conflict comparison. Tests fully authenticated malformed data for wrong outer/body pair, duplicates and mismatched counters/balances, dangling live vs valid historical refs, embedded wrong epoch, exhausted IDs, canonical order. Preserve existing file/owner transaction semantics and background service. Avoid O(N²) owner/claim lookups and full defensive copies in hot paths.
## 10. Acceptance criteria
1. Tests load authentic old fixtures (old1–14 layout as supported) at real phases then continue to same economic/gameplay outcome, including original current14. 2. Canonical full modern equality over save/load mid transfers/suspension/return and replay, retained snapshots include new state. 3. Host-facing raw13 rejected states write zero bytes while normal golden projections match. 4. Every malformed candidate rejected without affecting active world/data. 5. All cross-branch integration, Wine CTest and focused migration tests; native caveat.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s15-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. For historical capture use immutable /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14 headers/source and matching prechange runtime library; save evidence/probe/hash under /tmp, freeze meaningful fixtures in tests where necessary. Later CTest -V/targeted custody migration/current/old golden probes and git diff --check; s15-custody-* logs.
## 12. Constraints and stop conditions
If core declarations are not frozen, deliver authentic fixtures and precise needed interfaces now; do not guess incompatible wire layout or edit S06 files. Root coordinates compile/integration. No standalone incomplete publication. After two failed same-cause fixes escalate with evidence.
## 13. Authorization and decisions
User authorizes full roadmap, file compatibility and Gitea milestones. Root accepts 1–3 outer + 1–15 body migration and all F8 constraints. Server/client adverse input validation is defensive, with no external communication. Root owns all public actions.
## 14. Return format
Return S15-04 progress including authentic prechange fixture SHA early, actual agreed storage schema/constraints, changed paths/tests/golden behaviors; mark native/combined gates explicitly.
+50
View File
@@ -0,0 +1,50 @@
# Serve compatible LAN clients from the immutable authoritative runtime
Task ID: S16-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16, system/s16-authority fast-forwarded to 8c4c1fe. Existing LanSession::poll(World&) protocol11 is tested (4 cases/baseline binary interop). Runtime and command dispatcher new headers exist. M01-F4 identified manifest and outstanding-command reconnect gates, included below.
## 2. Objective and deliverables
Add production host polling that consumes immutable runtime views and submits authenticated guest actions to the owner asynchronously. Add guest-only polling usable by a view-only client, preserve current hardcoded two slots and old packet format.
## 3. Scope and non-goals
Legacy LAN11 compatibility adapter and actual loopback tests. No public new protocol/version or remote rollout, no new internet exposure. Preserve existing poll(World&) entry/fixtures for old API clients. Viewer source is owned separately.
## 4. Files to inspect
Inspect app/lan_session.hpp, app/lan_session_win32.cpp, app/lan_wire.hpp/.cpp, tests/lan_tests.cpp, simulation_runtime.hpp, command_dispatcher.hpp, world.hpp, rules_manifest.hpp, docs/plan/systems/S16.md. Read /tmp/stoneheart-verify.KoZwE4o8/interop.cpp/.py for existing binary interop.
## 5. Write ownership and coordination
Write scope: app/lan_session.hpp; app/lan_session_win32.cpp; tests/lan_tests.cpp; docs/plan/systems/S16.md
If an identified shared codec change is necessary, contact root first; no data layout redesign. Other workers own Win32 viewer/core. You are not alone, do not change Git/Serena/other worktrees.
## 6. Implementation or investigation approach
NEW poll_host(SimulationRuntime&) and poll_guest() (or equally explicit) for real viewer. Wire11 Hello carries no manifest/epoch, so allow ONLY default compatibility manifest (verified frozen identity); close incompatible connection before exposing a snapshot/command. Bind host session incarnation; detecting replacement drops peer & requires new hello before serving new world. Existing TCP framing/auth and slot validation retained. Read current immutable published World and prepare v13 snapshots with current bounds. No direct mutation in new host path. Screen sends one action at a time; bound hostile/pipelined volume, keep pings/timeouts/disconnect progress, never wait on a long owner while polling socket. Serialize one outstanding valid command per authenticated guest slot.
## 7. Interfaces and data contracts
Wire request IDs are legacy World::next_command_sequence(guest), only accepted gameplay increments them. Modern envelope number from committed PublishedSnapshot::next_requests[guest] also advances on domain rejection. Precheck wire sequence without mutating state; old wrong-sequence -> expected number. Submit trusted guest=2, verified UUIDs/world/city/version, exact payload; report the correct legacy result and next wire sequence only from corresponding committed runtime result. Reject unsupported actions using existing authority. Track one outstanding admitted operation across TCP disconnect/rebind; suppress old-connection replies by connection generation, hold/reconcile its completion before next guest's sequence or authentication/publication is used, prevent reusing in-flight modern request number. On epoch change fence old future before new peer bind. No borrowed runtime pointer persisted. Expose status to viewer on incompatible rules/fault. Send early public signatures.
## 8. Dependencies and integration
Root owns actual Win32 viewer integration. Runtime consumers now available at baseline; old standalone overload remains tested. Add only in-process loopback tests using random port/loopback flag. Reuse existing socket implementation and avoid duplicate dispatch/snapshot logic. Legacy reader file/body remains format13 and lower limits; world with unsupported future schema must be rejected explicitly in later change.
## 9. Edge cases security and performance
On Busy/Closed/Faulted/superseded/out-of-order preserve protocol-correct old next id and prevent lost reported effects. Guest can correct a rejected action using same old number. Do not retain retired peer's optimistic blueprint metadata. Check long owner tick does not block server pings/poll; settled work from old peer cannot reply to a new one. Enforce bounded admission and no logs of join codes. Test a publication at same tick.
## 10. Acceptance criteria
1. Old-style genuine guest joins runtime-owned host and receives actual committed world; user action, domain rejection and corrected next command preserve legacy sequences. 2. Deliberately blocked/delayed command, disconnect/reconnect, no old receipt to new peer, sequential guest slot safely resumes. 3. New epoch and non-default manifest refuse or reauthenticate before any legacy snapshot. 4. Both existing LAN11 fixtures and old API work; deterministic cross-version loopback including old guest executable. 5. Real x64 tests and warning status.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_lan_tests.exe --tag lan (or registered runtime LAN tag plus full target), verbose CTest, git diff --check. Logs lan-owner-*. Root can stage external original-binary harness if needed.
## 12. Constraints and stop conditions
No changes to socket reachability, authentication standards, new transport, UI or unrelated game state. Two failed fixes for the same defect -> send evidence and changed hypothesis to root. No children/Git/remote mutations.
## 13. Authorization and decisions
User approved milestone/system work, commits/PRs/accumulation. M01-F3/F4 require authenticated owner entry and preserved old-wire rules. Root handles final integration.
## 14. Return format
Return S16-02 status, early exact caller entry points, peer/session tracking contracts, actual test evidence/counts/interop and any native limitations.
The client also needs positive acknowledgements to remove committed draft parts. The approved preferred guest interface exposes `take_result()` with the full accepted or rejected intent, including resident ID. Retain one completion until the preferred caller drains it, clear stale results across connection generations and preserve legacy `take_rejection()` behavior. The loopback cases cover accepted and rejected results.
+48
View File
@@ -0,0 +1,48 @@
# Drive the Win32 client from committed world views and async results
Task ID: S18-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s18 system/s18-client at 512c9ef. Runtime reviewed at 7979fff and M01 8c4c1fe. S15-03 and S16-02 are in separate worktrees and root will supply reviewed commits to this checkout before final build. S18-W01 owns separating snapshot reads and command submission from window handlers. M01-F4 identified title/menu, lifetime, admission and rules gates.
## 2. Objective and deliverables
Wire the actual Win32 viewer to the single-owner runtime for offline play and hosting, immutable guest view, bounded async command handling and real background checkpoint save/load. Keep title/new/continue, legacy scenario/cabin controls and LAN guest usable.
## 3. Scope and non-goals
Normal Windows app entry points plus focused testable client-state handling. This first S18 slice does not include unrelated keyboard/scale/sound settings, new internet protocol or UI for metadata-only rule selections. Show only supported default-profile new games; S19 adds genuine selectable behavior separately.
## 4. Files to inspect
Read app/viewer_win32.cpp all session lifecycle/menu/paint/blueprint/command handlers, app/title_screen_win32.hpp, D3D const World entry, LAN and CheckpointFiles headers in sibling s16/s15, frozen simulation_runtime.hpp/impl, raw world factory/first_colony, and existing tests/smoke source /tmp/stoneheart-verify.KoZwE4o8/viewer_smoke.cpp. Watch S06-01 resident detail index access intentionally owned by another worktree.
## 5. Write ownership and coordination
Write scope: app/viewer_win32.cpp; app/viewer_session.hpp and app/viewer_session.cpp (NEW if needed for testable state); tests/viewer_session_tests.cpp (NEW); CMakeLists.txt (viewer_session target/tests only); docs/plan/systems/S18.md
Do not edit other worktrees, shared Serena or Git, or overhaul unrelated UI. Keep resident-detail lookup changes minimal where S06 branch also edits one line; parent integrates. Native normal entry is mandatory.
## 6. Implementation or investigation approach
One window-lifetime owner runtime where possible. New/reset/load install prepared WorldCheckpoint with fresh incarnation; reuse the long-lived runtime or retire former owners off UI without joins, keeping retirement bounded. Guest reads latest received world immutably, never steps/applies; suspend local owner when guest, fence pending UI/authority. Preserve playable disconnected/leave behavior: keep last received guest World privately owned to import into a fresh local session on deliberate leave if prior behavior allows continuing that colony. Fresh first colony uses nonnil stable UUID+resolved default manifest. Gate viewer installs to exact supported compiled-rules profile/32x32 dimensions, preserve legacy imported world. Use consistent shared const world/view per frame and protect raw references across nested window messages/modal confirmations by pin or revalidate after dialogs. Render/HUD paths must stay safe on title with no world. WM_TIMER pumps file/network/runtime completions and reconciles desired ticking state BEFORE ANY title/offline/file-dialog/UI early return. Never step/serialize mutable World on UI. File picker is normal modal selection; picker open affects presentation pause without blocking owner polling or completion processing. Anchor title/hidden, pause-menu, file-dialog, guest/host and shared World::paused semantics to existing user-facing choices; no flood of set_ticking when unchanged or Busy. Fault visible, rendering last head and explicit load still usable.
## 7. Interfaces and data contracts
Expected seam: S15 CheckpointFiles(options) with try_save(path,shared_ptr<const PublishedSnapshot>), try_load(path,workers,mode) → admission/request/future<expected<WorldCheckpoint,CheckpointFileDiagnostic>>, one process-level instance, survives reset across slots. Viewer obtains snapshot_for_save(), tracks completion by request+epoch, only reports latest relevant result. At selected load intent issue runtime begin_load even if ensuing file decode fails so stale older prepare cannot undo latest request; file result independent, filter UI ticket/generation+epoch, install checks again, preserve display on invalid/busy/superseded. S16 provides void poll_host(SimulationRuntime&) and unique_ptr<World> poll_guest(); guest presentation stores owned snapshot only, legacy standalone poll(World&) is for old consumers. Attach local controls/host and legacy cabin to modern CommandEnvelope, trusted host slot, via ONE bounded per-client intent queue and at most one runtime submission awaiting reply; allocate number from latest committed next_requests, never consume on Busy; retries do not duplicate. Pending blueprint/room IDs or exact generation-marked metadata ensure only an actually accepted part is cleared, rejected/busy remains editable, repeated click cannot resubmit pending. Other accepted-only statuses after commit. On reset/join/load, disconnect or retired epoch fence stale results and preserve unrelated current edits. Explicit local effects and connection authority; no GTK/web UI.
## 8. Dependencies and integration
Root merges reviewed S15/S16 deps into s18 checkout before final build; send dependency requests early. Development may start on public seam/logical model; verify actual source before final compile. F4 corrections per exact contract. Existing tests and external Wine UI smoke must still run. Current UI actions should remain meaningful. No fake alternate rules advertising. Preserve old compatible file extension/recent saves and existing no-guest-save host policy.
## 9. Edge cases security and performance
UI must remain responsive during deliberately long tick/file write, complete results on title/modal loops, avoid dereferencing stale selected_agent pointer, actively fence prior session commands/loads, avoid starving owner and don't freeze on reset/new/join. No stateful dangling callbacks on WM_DESTROY; orderly shutdown can drain on app exit. Queue memory and ongoing operations bounded by documented capacity. No unchecked exceptions escaping Win32 callbacks or stale feedback after generation change. Use deterministic gates for tests; actual end-to-end app path observable.
## 10. Acceptance criteria
1. Launch actual viewer, start and advance local colony; deferred owner command incl cabin, pause/unpause while at same tick; no WM_TIMER direct world->step/World::apply_command. 2. Open modern and old saves from title, save during progress, update status only on newest completion; malformed/superseded/unsupported rule loads preserve current session. 3. UI reader can repaint/pan while owner/writer blocked; no synchronous join resetting/joining. 4. Host and guest continue through correct polling and domain-rejection/blueprint sequencing; stale queued intent/load cannot affect new session. 5. All Windows x64 tests and real viewer smoke, including title load if possible, with recorded native gaps.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe or viewer suite as actually registered, CTest -V, git diff --check. Reuse local isolated Win32 smoke harness for real viewer title/new/close and extend temporary harness for title/save/load as feasible; no disk writes to real user saves. Keep logs client-*.
## 12. Constraints and stop conditions
No edits to S06, raw game rules, runtime, file service or LAN wire. Stop if exact external API differs or a product decision is needed, continue independent work. After two failed repairs of the same issue escalate. No children/Git/remote mutations.
## 13. Authorization and decisions
User authorizes all milestones, per-system branches, commits/push and merge requests. F3/F4 and subsequent corrective recheck apply; parent owns branch merges/remote publication, no release.
## 14. Return format
Return S18-01 status, actual changed behavior/lifetime/queue and gates, owned files, exact tests and Win32 smoke evidence, pending native validation. Communicate frozen helper/normal UI entry paths early.
+48
View File
@@ -0,0 +1,48 @@
# Compile a selectable plank-bed package into actual colony behavior
Task ID: S19-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive s19 worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 60154bd. Prior S19 catalog/manifest reviewed, M01-P4 and F6 preflight approved both existing bed production paths. Current World::start_scenario sets staged_beds_=true unconditionally; legacy/restored worlds already execute nonstaged SawPlank + BuildBed. S18 initial UI work/other World changes in distinct checkouts.
## 2. Objective and deliverables
Allow real selection between the existing default staged bed assembly and optional one-plank bed assembly at colony creation. Freeze compatible manifest/engine configuration and provide supported-profile validation at the application boundary for creation and loading.
## 3. Scope and non-goals
S19 core package, game-profile compiler/factory, narrow World scenario initialization and runtime-neutral validation tests. No UI/transport changes in this slice. No change to generic resolver/decoder acceptance or Lua VM. Preserve all original package contents, default game output and original call signatures/behavior.
## 4. Files to inspect
Inspect rules_manifest.{hpp,cpp}, first_colony.cpp, world.hpp/.cpp start_scenario/PlaceBed/PlaceRoom/recipes, world_save.cpp staged flag/state validation, checkpoint.hpp, actual tests/rules_tests, core_tests, legacy fixtures, prime S18 viewer_session.cpp constructor/load/host gates via sibling and plans S19/F6. Pin has resolver primitives used earlier, existing issue #4. Current default SawPlank executes 12 ticks; the old manifest's sample work_ticks=8 is not activated by this feature.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/colony_profile.hpp and engine/src/colony_profile.cpp (NEW); engine/src/rules_manifest.cpp; engine/include/settlement/core/world.hpp; engine/src/world.cpp (scenario initialization only); engine/src/first_colony.cpp; tests/rules_tests.cpp; tests/profile_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S19.md
Skip all UI and unrelated caller edits. S04 changes production identity in separate worktree. You are not alone; root integrates and handles simultaneous CMake/World edits. Never revert another worker, change Git or shared Serena.
## 6. Implementation or investigation approach
Add additive optional built-in exact package settlement.plankbeds with an allowed recipe definition in its own namespace, stable dependency on settlement.colony and no conflicting exclusive construction capability. Interpret explicit typed data describing one plank/simple assembly to select the actually existing engine bed mode. Use resolver/checkpoint typed APIs, validate supported exact closure/digests and content before building a supported colony. Compute prechange default manifest canonical bytes/fingerprint using the verified baseline first, hardcode golden from it into regression (old two-package closure/content unchanged); do not recompute expected with candidate. New default=false option meaning must be clear by names. Expose concise NEW profile enum/options and a game-specific factory producing validated WorldCheckpoint (owned World, fresh stable nonnil UUID, city1, correct manifest), plus supported-profile validation taking World/manifest or candidate. Name signatures early so S18 follow-up can wire title.
## 7. Interfaces and data contracts
Keep existing World::start_scenario(sawmill), make_first_colony(workers) staged by default; add explicit creation-only mode/profile parameter or overload, no mutable post-creation toggle. When active optional package selected, actual simple path: SawPlank + one BuildBed, one plank consumed; default already uses foundation wood/stone plus cloth twice. Furnished rooms must respect same rule. Existing schemas saved real mode; loaded exact default is allowed with EITHER persisted mode, inactive legacy worlds included (historical v1 or raw-format import). Do not alter their rules/mode at load. Optional exact profile requires active scenario staged=false where applicable; reject exact simple-manifest with active staged world. Unknown package/digest/config rejected by supported-profile gate; generic decode/runtime continue to handle caller-supplied catalogs independently. Reuse shared immutable definitions/lookup as suitable; avoid catalog-size assumptions and requiring every installed unrelated package.
## 8. Dependencies and integration
Viewer later calls this public factory and canonical compatibility gate on BOTH initial and prepared worlds, and keeps immediate/deferred old LAN11 exact-default-only. Do not mix S18 UI edits on s19; communicate the trusted support check and whether a profile may host to root. New catalog optional must not automatically activate or alter existing default hashes.
## 9. Edge cases security and performance
Exercise active/inactive imported historical worlds, current resaves, no silent toggle or package rewriting. Avoid claiming all base/ACE systems implemented. Use an actual complete bed production run under both options with relevant materials/outputs (incl furnished room), mature/paused snapshots persisted and continued. Preserve wire13/old baseline normal path. An altered content package using same ID/version must not pass compiled-profile support.
## 10. Acceptance criteria
1. Old default known fingerprint/bytes and baseline gameplay preserved; selecting optional package changes material chain and completes bed with actual initial supply. 2. Compare modern canonical per tick across serial/2/6/12 for representative events; held view does not change; mid-carry save/load continues identically. 3. Exact optional mismatch, default historical raw/v1 active simple and inactive accepted without rewriting; catalog reordering and missing/changed/extra activated packages handled. 4. Correct real startup factory and no mutable rules switch. 5. All cross suites pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/profile-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag profile and tagged rules, full verbose CTest, git diff --check; source actual old baseline digest from already built branch or separate helper, log its hash. Provide exact logs profile-*.
## 12. Constraints and stop conditions
No editing S18 UI, no broad changing existing recipes to fit sample data and no rewriting old manifests, formats or resources. Stop/escalate after two failed repairs of same issue or if actual optional mode cannot complete the scenario. No children/Git/remote mutations.
## 13. Authorization and decisions
Plan explicitly requires new-world module selection. Existing bed behaviors were chosen as first reversible demonstration, preserving old defaults and P4/F6 restoration policy. User authorized commits, issues and PRs through root.
## 14. Return format
Return S19-02 status, early exact creation/validation API, source derived default golden, observed actual bed/room/canonical and legacy compatibility, counts and residual native/UI risks.
+53
View File
@@ -0,0 +1,53 @@
# Владение грузом во время работ M01
Формат 14 уже различает заказы по постоянным ID. Следующий срез [S06](systems/S06.md) и [S04](systems/S04.md) вводит имущество, требования к нему и результат передачи. Это контракт реализации для текущих игровых действий. [План этапа](milestones/M01.md) · [Проверка действующего кода](../agent-workflow/tasks/M01-P5.md)
## Имущество и резервы
Каждый непустой стек имеет ID мира и одного владельца — склад, жителя или входной запас конкретного производственного заказа. Количество хранится у владельца. Резерв ссылается на него и задаёт удерживаемое количество. Отдельные резервы удерживают рабочее место, источник добычи и место для результата. Счётчики доступности склада и источника можно восстановить из действующих резервов. Требование рецепта описывает затраты отдельно от имущества.
Целый стек, переходящий в пустой слот, сохраняет ID. При разделении ID остаётся у исходного остатка, а новая часть получает отдельный ID. При объединении сохраняется ID стека получателя. Ссылки резервов на перемещённое количество обновляются той же операцией. Для каждого вида ID свой восстанавливаемый счётчик. Ноль означает отсутствие ссылки, а `UINT64_MAX` у следующего ID — исчерпание. Выделение всей группы проверяется до изменения мира. [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7)
Назначение работника закрепляет все материалы, рабочее место и вместимость вместе. Для плотника место под результат может обеспечивать зарезервированный входной материал в том же складе. Резерв места ссылается на конкретный резерв материала. Одна единица обеспечивает только одно место. При получении этого материала на освободившееся место устанавливается обычный резерв. До окончания работы запоминается и исходный склад, чтобы прежние команды перемещения и разбора выдавали согласованный отказ после получения груза.
| Событие | Изменение владения |
|---|---|
| Стартовые запасы и добыча | Начисление создаёт количество у склада либо жителя. Для добычи в тот же момент уменьшается исчерпаемый запас источника. |
| Получение материалов | Все позиции текущей остановки переходят со склада к жителю. При отказе любой позиции весь груз остаётся на месте. |
| Прибытие на стройку | Материалы переходят к заказу. Пока идёт работа, у площадки есть собственный входной запас. |
| Завершение рецепта, монтаж, еда | На одном шаге списываются входы, учитывается причина и при необходимости создаётся результат. |
| Отмена до получения | Освобождаются требования к складу, рабочему месту и исполнителю. |
| Отмена в пути или на площадке | Груз остаётся у жителя либо возвращается ему со стройки. Уже установленные части здания сохраняются. Житель возвращает все виды груза, ожидая место при заполнении складов. |
| Разбор свободного склада | Оставшиеся запасы списываются с причиной разбора и точным количеством каждого вида. |
Когда время работы истекло, а завершение временно невозможно, исполнение сохраняет состояние ожидания завершения и нулевой остаток времени. Новый шаг повторяет проверку с очередным номером операции. Так при исчерпании ID или переполнении не происходит повторного уменьшения нулевого таймера и частичной выдачи результата.
Для каждого вида предмета проверяется баланс. Начальный остаток, начисление, добыча и производство равны сумме имущества у всех текущих владельцев и списаний на сырьё, монтаж, питание и разбор. Счётчики источников и расходов используют проверяемую арифметику. Эта проверка выполняется при загрузке и в тестах. [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8)
## Исполнение и повтор
У создания исполнения заранее известен ключ из ID жителя и его следующего номера назначения. Нумерация начинается с 1. При успешном принятии мир одной операцией выдаёт `TransferId`, сохраняет данные запроса и его результат и увеличивает номер назначения. Потеря ответа не может назначить ту же работу повторно. Нехватка ID, места или материалов до принятия оставляет оба счётчика прежними. Последующие шаги используют пару из `TransferId` и очередного номера операции. Отказ принятого шага меняет только журнал повтора. Повтор с исходными данными возвращает прежний результат, с изменёнными — конфликт.
Хранятся последние 4096 результатов в порядке применения. Для каждого результата закодированные запрос и ответ ограничены 1024 байтами каждый. После вытеснения прежний номер распознаётся по следующему номеру шага действующего исполнения или по границе выданных ID завершённых исполнений. Устаревший запрос не может повторно переместить имущество. У жителя не более одного действующего исполнения. Резервы одинакового предмета могут относиться к разным складам; размер набора проверяется по фактическим ограничениям игры. Полные проверки и измерения размера снимка входят в приёмку.
Действующие ссылки должны разрешаться к существующим объектам. Историческая квитанция может содержать уже израсходованный стек или удалённый заказ. Загрузчик проверяет её вид, согласованность полей и диапазоны выданных ID. Пары схемы и тела проверяются по отдельности для всех трёх поколений сохранений.
Явная отмена относится к современному приказу по `ProductionId`, с проверками города, инкарнации и номера запроса. Житель с возвращаемым грузом сохраняет своё исполнение до сдачи последней единицы. Если у кровати уже установлено основание или существует действующий ткацкий станок, отмена сохраняет площадку под прежним ID и приостанавливает следующие работы. Явное возобновление продолжает с сохранённой стадии. Завершённая кровать сохраняет назначение владельцу. Для старых `DemolishObject` и `MoveObject` продолжают действовать прежние отказы при занятом источнике, складе или кровати. [Контракт команд](systems/S16.md)
## Сохранение и миграция
Планируемая контрольная точка схемы 3 использует тело версии 15. В нём сохраняются реальные ID, владельцы, незавершённые исполнения, резервы, результаты повторов и баланс. Повтор ID, лишний владелец, пропавший источник или несовпадающий баланс отклоняют кандидата до смены текущей партии.
| Вход | Восстановление |
|---|---|
| Тела 1–13 и контрольная точка схемы 1 | Проверить исторические поля и контрольную сумму. Сопоставить позиционные ссылки постоянным ID. |
| Тело 14 и схема 2 | Сохранить имеющиеся ID заказов и следующий ID, восстановить остальное имущество из действительных старых данных. |
| Материалы в пути | Уже посещённые остановки соответствуют грузу жителя. Оставшиеся материалы удерживаются у склада. |
| Начатая работа с доставленным материалом | В старом формате прибытие убирало материалы из инвентаря жителя. Восстановить вход площадки по проверенному действующему рецепту, затем посчитать начальный баланс. |
| Добытчик, перевозчик, голодный житель | Восстановить фактический груз, удержание места, резерв источника или еды в соответствии с сохранённой стадией. |
При переносе старого активного задания ему назначается первое поколение, а следующий номер назначения жителя устанавливается в 2. Для свободного жителя следующее назначение начинается с 1. Запрос от уже перенесённого поколения без исторической квитанции получает ответ об устаревшем номере.
Обычная партия сохраняет побайтовый экспорт 13 и протокол LAN 11. Для отменённой стройки житель может нести несколько видов материалов без доступного склада. Даже одна доска без связанного с ней заказа может не иметь представления в старом состоянии перевозки. Кодек сообщает `UnsupportedLegacyState` до записи первого байта. Это относится также к приостановленной площадке и другим несовместимым сочетаниям состояния. Современная контрольная точка сохраняет партию полностью. Хост проверяет представимость до допуска гостя, разбора приказа и выдачи снимка. При отказе совместимый гость получает отказ в подключении или отключается, а хост продолжает игру.
Приёмка охватывает остановки до получения, между складами, на площадке, при отмене и при ожидании свободного места; исчерпание ID и числовые границы; точный повтор до и после загрузки; старые двоичные наборы; сравнение каждого такта на последовательном исполнителе и 2/6/12 потоках. В контрольном сценарии с 500 жителями дополнительно измеряются снимок, размер сохранения и операции при 10 000 стеках и 2 000 заказах.
+4
View File
@@ -25,6 +25,10 @@
### Переход к авторитетному такту
Ядро выполняет такты по 50 мс в отдельном потоке. На каждой завершённой границе `SimulationRuntime` публикует независимый снимок и квитанции приказов. Пока идёт новый такт, читатели могут продолжать работу с прежней версией. Остановка игрового времени сохраняет возможность отдать приказ. Результат загрузки заменяет мир после повторной проверки номера запроса и инкарнации, в том числе при откате того же сохранения. [Интерфейс владельца](../../../engine/include/settlement/core/simulation_runtime.hpp) · [Тесты такта и отказов](../../../tests/runtime_tests.cpp)
Селектор `--tag runtime` под Wine выполнил десять проверок. Среди них — 20 тактов за секунду ручных часов, чтение предыдущего снимка при задержанном рабочем задании и возврат к управляемой партии после отказа публикации. Независимая проверка и общая сборка охватили 92 случая ядра и 4 LAN. Дальнейшая приёмка M01 проверяет действия игрока через окно, обмен со старым LAN-клиентом и постоянные ссылки при удалении объектов. [Техническая проверка](../../agent-workflow/tasks/M01-V7.md)
Выделить одну воспроизводимую партию прототипа и записать последовательность приказов. Сначала пропустить её через очередь авторитетного мира и дать окну читать последний завершённый снимок. Далее заменить один участок независимого расчёта, сверить результат каждого такта, затем подключить следующий. Так первое расхождение привязано к конкретной стадии. Для суммы запасов, состояния задания и номера команды выводить в отчёт также идентификатор первого отличающегося объекта.
Проверить для нынешнего `WorkerPool` исполнителя `Void::Async::ThreadExecutor` с `FuturePool`. На частичном отказе запуска уже созданные потоки должны штатно завершиться. При заполненной очереди логическая работа остаётся в такте до исполнения. При одновременных заявках на предмет ожидаемый победитель определяется правилами арбитража. Доступность API и управляемое воспроизведение отказов записать до удаления прежнего пути. Эталонный последовательный исполнитель — новый тестовый режим. Исторический тест, отклоняющий конфигурацию с одним рабочим потоком, остаётся свидетельством поведения прототипа.
+13 -1
View File
@@ -6,7 +6,19 @@
## Исходное состояние
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. В ссылках на материалы и остановки используются индексы контейнеров. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. Материалы и остановки хранят `StorageId`, источники — `ResourceNodeId`, назначения производства — `ProductionId`. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
## Реализованный срез S04-01: идентичность производства
У `ProductionOrder` появился постоянный `ProductionId`, а житель хранит `production_id` (`0` означает отсутствие назначения). Единственный счётчик `next_production_id_` входит в копируемое состояние мира. Заказы остаются отсортированными по ID, поиск выполняется через `lower_bound`; удаление нижнего заказа не требует исправлять ссылки жителей. Присвоенный ID не меняется в течение жизни заказа.
Все вставки, включая обстановку и клетки комнаты, проходят общий метод. До первого изменения проверяются ID и вместимость вектора для всей группы: кровать, ткацкий станок, комната с мебелью, дом и замещающие столярные заказы при сносе склада. Снос вычисляет нехватку каждого затронутого изделия по запасам **после** предполагаемого удаления, учитывая другие склады и уже существующие заказы, затем резервирует всю группу. Недостаток ID возвращает `Busy` без потери запасов, изменения заказов или номера команды. Последний выдаваемый ID — `UINT64_MAX - 1`; `UINT64_MAX` остаётся допустимым исчерпанным счётчиком. Прямой `queue_cabin` сообщает такую проверенную до изменений нехватку через `ProductionCapacityError`; диспетчер сохраняет повторяемый результат `Completed/Busy`, а runtime продолжает принимать команды.
`World::write_save(stream)` сохраняет прежний формат 13 и позиционные ссылки для совместимости, включая LAN 11. Явный `WorldSaveFormat::Current14` записывает настоящие ID производства, складов и источников, а также следующий ID производства. Новые checkpoint используют внешнюю схему 2 и тело 14. Схема 1 принимает тела 1–13; несовместимые пары отклоняются даже при корректных контрольных суммах. Импорт старого тела назначает производству ID по порядку записей; современные сохранения сохраняют историю выдачи после удаления последнего, максимального или всех заказов. Чтение проверяет ненулевые упорядоченные ID, следующий ID и ссылки до разыменования; новые проверки не добавляют квадратичный поиск.
Используются закреплённые `Void::Numeric::checked_add`, Binary и Crypto из `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. Отдельного библиотечного восстанавливаемого генератора ID пока нет: [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Локальную проверку и продвижение счётчика в `World::reserve_production` / `append_production` можно заменить после подтверждения того же поведения на Windows x64, включая групповую проверку и исчерпание.
Проверки: [production_identity_tests.cpp](../../../tests/production_identity_tests.cpp), [checkpoint_tests.cpp](../../../tests/checkpoint_tests.cpp), [replay_tests.cpp](../../../tests/replay_tests.cpp). Срез проверен Windows x64 GCC 16.2 через Wine: 9 проверок `--tag production-id`, полный verbose CTest — 115 core и 4 LAN. Replay сравнивает тело 14 на каждом такте в serial/2/6/12, включая сохранение в пути и дырку в ID. Существующие двоичные эталоны формата 13 совпали во всех четырёх режимах: 738386 байт (`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`) и 393857 байт (`05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`). Сохранён настоящий checkpoint схемы 1, полученный старым encoder до изменения. Нативный запуск Windows и MSVC не выполнялись. Общие поручения, самостоятельные ID резервов, передача владения и отмена груза остаются последующими срезами S04/S06.
## Данные и владение
+39
View File
@@ -60,6 +60,22 @@ S06 владеет фактическими количествами, содер
## VoidLibrary и приёмка
[Контракт имущества M01](../custody.md) описывает владение при подборе и сдаче, возврат материалов, повтор операции и перенос старых сохранений.
Первый срез M01 хранит в жителях, требованиях материалов и остановках доставки постоянные `ResourceNodeId` и `StorageId`. Ноль означает отсутствие ссылки. Удаление более раннего склада или узла сохраняет цель активной работы. Списки объектов упорядочены по ID, чтение использует двоичный поиск. Формат 13 продолжает хранить прежние позиции. Загрузчик удерживает их во временном буфере, проверяет порядок ID и переводит в постоянные ссылки до проверки состояния мира. [Модель](../../../engine/include/settlement/core/world.hpp) · [Кодек](../../../engine/src/world_save.cpp)
Счётчик со значением `UINT64_MAX` обозначает исчерпание. Последний выдаваемый ID равен `UINT64_MAX - 1`. Фабрики и команды проверяют следующий ID через закреплённый `Void::Numeric::checked_add` до изменения объектов и геометрии. Фабрика сообщает `overflow_error`, команда возвращает `Busy` и сохраняет номер следующей команды. Общая возможность восстанавливаемого счётчика предложена в [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Переход на неё проверяется независимыми мирами, сохранением после удаления объектов и отказом у верхней границы.
Семь проверок `--tag identity` под Wine покрывают удаление более ранних объектов при переноске, доставку с двух складов, кладовую, засев без склада, готовую продукцию плотника, границы счётчиков и недопустимые старые ссылки. Загруженные копии продолжают совпадать потактно в последовательном режиме и на 2/6/12 потоках, включая контрольную точку с правилами и удерживаемый снимок. Постоянные ID производственных заказов, стеков, резервов и передач входят в последующие срезы. Для общего резервирования и переноса количеств зарегистрирован [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). [Исполняемые проверки](../../../tests/identity_tests.cpp)
Срез S06-02 переводит физическое получение еды и материалов одной остановки на `withdraw_reserved_materials`. Операция объединяет все строки текущего склада по типу, включая несмежные повторы; строки остальных остановок не участвуют. До первого изменения проверяются ненулевой ID склада, выбранные типы и положительные количества, существование отсортированных уникальных стеков, `reserved <= count`, достаточность резерва, вместимость и проверяемые суммы источника и личного инвентаря. Счётчик назначения может достичь ровно `UINT32_MAX`. Фиксированные массивы ограничены числом типов; получение не выделяет память, удаление нескольких опустевших стеков сохраняет порядок остальных. [Контракт операции](../../../engine/include/settlement/core/inventory_transaction.hpp) · [Реализация](../../../engine/src/inventory_transaction.cpp)
Плотник в той же операции резервирует место для результата на складе **первого ингредиента**, даже если этот склад посещается позже другой остановки. Проверка учитывает освобождающееся место; полный склад может обменять последнюю единицу сырья на одно зарезервированное место. При отказе не меняются количества, резерв места, остановка, маршрут и состояние жителя относительно входа в получение. Перед ним `World::step` уже мог продвинуть движение или потребности. Ошибка нарушенного предусловия поднимается владельцу симуляции; runtime сохраняет последнюю здоровую публикацию и блокирует сохранение повреждённого кандидата. Прямое преобразование сырья в продукт в `finish_production` остаётся отдельной операцией и не получает гарантию атомарного преобразования рецепта. Форматы 13, LAN 11 и Current14 не меняются. [Вызовы получения](../../../engine/src/world.cpp) · [Проверки `quantity-transfer`](../../../tests/quantity_transaction_tests.cpp)
В закреплённом Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` используется платформенно независимая `Void::Numeric::checked_add/checked_sub`; `Storage::Batch` относится к ключам движка хранения и не меняет игровые структуры в памяти. Локальный перенос связан с [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки позднего отказа всего набора, несмежных повторов, пределов арифметики, полного склада плотника и реальных еды/доставки/публикации на Windows x64, затем сравнить продолжения и старые байтовые эталоны. Этот срез не вводит ID стеков, резервов и передач, журнал или идемпотентность: повторное получение отсеивает существующий курсор остановки, а долговременный учёт владельца груза остаётся будущей работой S06-A/S04.
Проверка S06-02: сборка GCC 16.2 Windows x64 Release и запуск под Wine; 14/14 проверок `quantity-transfer`, полный CTest — 136/136 core и 9/9 LAN, включая современные сохранения и повтор на 1/2/6/12 исполнителях. Оба старых байтовых корпуса (`old-trajectory.bin`, `identity-compat-old.bin`) совпали с проекцией формата 13 на всех четырёх режимах. Нативный запуск Windows и MSVC отдельно не проверялись.
Применять существующие подходящие средства контейнеров, проверяемой арифметики, сериализации и результатов из [VoidLibrary](../void-library.md). Для отсутствующей возможности перед локальной реализацией найти либо создать issue в `Void/Library` и указать ссылку в задаче и коде.
- Два заказа запрашивают последнюю единицу ресурса. Только один получает резерв, свободный запас остаётся неотрицательным.
@@ -68,3 +84,26 @@ S06 владеет фактическими количествами, содер
- Разделить и снова объединить стек с активным резервом. Количество и свойства сохраняются, ссылка остаётся разрешимой.
- Повторить подтверждение торговли и прибытия в регион. История содержит одну завершённую операцию.
- На контрольных 10 000 стеках и 2 000 работах измерить поиск поставщика, стоимость операций и объём сохранения через [S21](S21.md). Варианты предметов и логистики связать с [реестром паритета](../parity.md).
## Срез S06-03: владение грузом и восстановление исполнения
Кандидат M01 хранит единственное количество у склада, жителя либо входного запаса `ProductionId`. `StackId` встроен в эту запись; требования рецепта используют отдельный `ItemAmount`. Получение целого стека в пустой слот сохраняет ID, разделение выдаёт ID новой части, объединение сохраняет ID получателя. Вместе с количеством меняются ссылки резервов; исторический исходный склад остаётся в материалах заказа до завершения. [Типы](../../../engine/include/settlement/core/custody.hpp) · [Реальные операции мира](../../../engine/src/custody.cpp)
Обычные начисления, добыча, все существующие рецепты, монтаж, еда и разбор склада учитывают источники и расходы. На стройке материалы действительно принадлежат входу заказа до завершения стадии. Перед изменением количества готовятся ограниченные копии затронутых владельцев, арифметика, ID и место для квитанции; после проверки выполняется не бросающий commit. Используются `Void::Numeric` закреплённого `7b0fea6`; локальные счётчики и условные операции связаны с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки исчерпания, целого/частичного переноса, последней единицы, отмены и продолжения после загрузки на Windows x64.
Назначение использует ключ `(AgentId, next_admission)`, дальнейший шаг — отдельное пространство `(TransferId, next_operation)`. Планировщик выдаёт ключ и применяет операцию; `custody_request` восстанавливает результат уже выданного запроса и отказывает неизвестному будущему ключу. Сохраняются последние 4096 квитанций в порядке применения с точными типизированными полями, результатами и выданными ID. Снимки разделяют только неизменяемые объекты квитанций; массив указателей и остальные данные копируются. Длина материалов ограничена пятью реальными единицами крупнейшего рецепта, включая пять разных складов. Этот локальный повтор также связан с [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6).
`cancel_production` освобождает неполученные резервы, возвращает вход площадки жителю и удерживает исполнителя в `Returning` до сдачи всех видов груза. Частичная сдача и отсутствие свободного склада не уничтожают остаток. Уже смонтированное основание кровати или существующий ткацкий станок сохраняют ID и приостанавливаются; `resume_production` продолжает оставшуюся стадию. Завершённые конечные объекты не отменяются. При отказе завершения нулевой таймер остаётся нулевым; следующая проверка получает новый номер операции. `legacy_representable` не изменяет мир и запрещает экспорт несовместимых фаз до записи первого байта. Сериализацию Current15, миграцию старых тел и контрольную точку схемы 3 реализует связанный S15.
Проверки `custody` охватывают реальный вход стройки, баланс расхода, разделение/объединение, пять источников, смешанный частичный возврат, приостановку/возобновление, неизменность снимка и истории, точный повтор/конфликт/будущий запрос/вытеснение, неверные ссылки и фазы, нулевые и максимальные счётчики, ожидающее завершение после загрузки. Отдельная проверка `custody-metrics` строит мир 512×512 с 500 жителями, 10 000 стеками в 1000 складах и 2000 заказами на распределённых площадках; второй вариант дополнительно создаёт 4096 квитанций реальными циклами ткачества. Измеряются 101 захват снимка и 21 последовательный такт с полной проверкой и кодированием Current15. Это синтетический сценарий, а не измерение рендеринга или сети. [Исполняемые проверки](../../../tests/custody_tests.cpp)
Нативный Windows, MSVC и отказ системного аллокатора не проверялись. Числовые отказы и отказы вставки из-за неверных аргументов проверяются без изменения сериализуемого состояния. Готовность к публикации зависит от независимой проверки интегрированного M01; локальные изменения и измерения не означают разрешение на выпуск.
Проверка интегрированного кандидата: GCC 16.2, Windows x64 Release, Wine 11; полный `ctest --output-on-failure -V` прошёл 3/3 исполняемых набора (162 core, 9 LAN, 10 viewer). Включены 14 проверок `custody`, отдельная метрика и исторические/повреждённые контрольные точки S15. Оба обычных старых корпуса повторно совпали побайтово на 1/2/6/12 исполнителях: 738386 и 393857 байт.
В описанном синтетическом сценарии без квитанций захват снимка занял p50/p95 0,036/0,049 мс; с 4096 квитанциями — 0,046/0,053 мс. Полная проверка: 0,784/0,922 и 1,301/1,664 мс; кодирование Current15 с проверкой: 9,357/9,583 и 11,881/12,025 мс; 21 последовательный такт: 0,010/0,032 и 0,010/4,728 мс. Кодирование выполнялось в памяти без записи на диск. Размер Current15 — 924042 и 1335950 байт; исходное число стеков второго варианта — 10002 из-за ткацкого запаса. Один неизменяемый объект квитанции занимает 584 байта на проверенном ABI; 4096 объектов — 2392064 байта без служебных данных аллокатора и массива указателей. Измерения зависят от прогрева и нагрузки Wine; p95 снимка укладывается в исходный ориентир 5 мс, кодирование всего мира выполняется отдельно. Локальные журналы: `/tmp/stoneheart-milestones.xprJ2SVp/s06-custody-build-final.log`, `s06-custody-ctest-final.log` и `s06-custody-{trajectory,identity-compat}-compare.log`.
Дополнительная проверка кандидата Current15 требует уникальных ID резервов в порядке выдачи, в том числе в квитанциях уже завершённых исполнений. Результат завершения сначала объединяет строки материалов, которые относятся к одному окончательному `(владелец, StackId, ItemType)`: два склада с древесиной могут образовать один входной стек плотника. Одна итоговая запись сохраняет нулевой остаток расхода, отдельная — реальный результат у жителя. Повтор такой итоговой записи отклоняется независимо от указанного количества; одинаковый вид предмета у разных владельцев или разных стеков сам по себе не является повтором. Проверка ограничена восемью выданными резервами и одиннадцатью итоговыми записями.
Терминальная квитанция не может относиться к действующему исполнению, получению со склада или доставке на рабочую площадку. Задания с получением материалов переходят через `FetchingMaterials` и `Hauling`, затем в `Working`; обычный `Travelling` для них отклоняется, поскольку обходил бы получение. Дополнительные проверки используют реальные два склада плотника и пять источников хижины, точный повтор после загрузки и подписанные повреждённые контрольные точки S15. Сборка и полный CTest после этой коррекции: 167/167 core, 9/9 LAN, 10/10 viewer; отдельный `custody` — 17/17. Журналы этой проверки — `s06-custody-uniqueness-{build,focused,ctest}.log` в том же временном каталоге. Схема 15 остаётся неопубликованным кандидатом; старые опубликованные форматы не меняются.
+26
View File
@@ -25,12 +25,38 @@
## Границы интерфейсов
`CheckpointFiles` обслуживает файлы вне потока окна. `try_save` удерживает опубликованный снимок и передаёт формирование контрольной точки единственному писателю с лимитом `max_checkpoint_bytes`. `try_load` возвращает номер запроса и future отдельного кандидата. Один ограниченный исполнитель чтения открывает файл один раз, проверяет размер и читает до конца под общим лимитом, включая рост файла после открытия. Ошибка современного формата сохраняет диагностику кодека. Импорт прежнего сохранения получает новый постоянный UUID и точный поддерживаемый набор правил из установленного каталога. [Интерфейс файлов](../../../engine/include/settlement/core/checkpoint_files.hpp) · [Проверки адаптера](../../../tests/checkpoint_file_tests.cpp)
Служба живёт до закрытия окна и завершает принятые чтения и записи при остановке. Окно связывает подготовку с `LoadTicket`, проверяет размеры карты и передаёт кандидат владельцу симуляции. Этот же владелец сверяет инкарнацию и последний запрос перед публикацией. Сценарии `--tag checkpoint-file` проверяют удерживаемый снимок при продвижении партии, прежние версии 1/8/9/13, диагностику несовместимых правил, рост файла, переполнение очереди, независимость писателя от задержанного чтения и завершение очереди при выходе.
Windows-адаптер чтения связан с [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). Условие перехода на библиотечную операцию — проверки чтения одним дескриптором до конца файла, путей Unicode, исходного размера и роста сверх лимита. Служба продолжает задавать ограничение приёма и владение запросом.
Контрольная точка версии 1 содержит постоянный UUID мира, город, такт, полный выбранный набор пакетов с точными версиями и SHA-256, а также состояние мира в формате 13. Декодер проверяет внешнюю контрольную сумму, заново разрешает набор правил по установленному каталогу и создаёт кандидат мира существующим проверенным загрузчиком. Клиенту доступны имя несовместимого пакета и поле ошибки. Восемь проверок под Wine охватывают переноску материалов, продолжение расчёта, перестановку каталога, обрезанные файлы, недопустимое состояние и тело размером более 16 МиБ. [Кодек контрольной точки](../../../engine/include/settlement/core/checkpoint.hpp) · [Проверки](../../../tests/checkpoint_tests.cpp)
`SaveRequest`, `SaveSnapshot`, `SaveManifest` и `LoadCandidate` — предлагаемые новые интерфейсы. Запрос содержит слот и желаемую операцию. Снимок привязан к одному завершённому такту. Манифест описывает все необходимые блоки и контрольные суммы. Кандидат загрузки предоставляет результат проверки до замены мира. Завершение операции возвращает идентификатор запроса, состояние и диагностическую причину ошибки.
При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md)
## Владение имуществом в версии 15
`encode_checkpoint` записывает схему 3 и тело 15. Декодер проверяет отдельную таблицу пар: схема 1 допускает тела 1–13, схема 2 — только 14, схема 3 — только 15. Проверка внешнего SHA-256 предшествует декодированию мира. Старый FNV-footer тел 1–8 и нормализация сна до версии 5 сохранены.
Тело 15 сохраняет прежний набор полей тела 14 и добавляет реестр владения: три границы выданных ID, ID складских стеков и инвентарей, номер назначения каждого жителя, действующее исполнение с номерами операций и резервами, входы и приостановку заказов, восемь счётчиков баланса для каждого предмета и журнал результатов. Резервы содержат владельца, конкретный стек, количество, источник обеспечения вместимости и исходный склад. Пустые позиции массивов имеют единственное нулевое представление. Журнал записывается от самого старого результата к самому новому независимо от физической позиции кольца в памяти.
Запрос и результат имеют собственные 16-битные длины и типизированные поля little-endian. Текущий запрос занимает не более 109 байт, результат — 318 байт; общий предел каждого остаётся 1024 байта. Непустой элемент результата может содержать нулевой остаток уже израсходованного стека. Это историческая ссылка, а не новый пустой стек. Максимум 4096 записей занимает до 1 765 376 байт вместе с длинами. Проверяются точные данные запросов, а не только их хеши.
Лимит тела 128 МиБ отделён от лимита старого сетевого снимка 4 МиБ и от бюджета декодированной памяти. Число записей каждой исторической коллекции ограничено миллионом. Бюджет памяти учитывает расширенные C++-записи всех ограниченных пулов, вложенные массивы и журнал; арифметика верхней границы проверяется при компиляции. Чтение растит вектор по одному элементу и не резервирует память под объявленное недоверенным файлом число. Маленький обрезанный файл с числом жителей 1 000 000 заканчивается ошибкой после первой незавершённой записи.
Перенос старого тела начинается только после полной исторической проверки. ID назначаются в порядке вида владельца, ID владельца и предмета. Материалы, уже доставленные на стройку, восстанавливаются во входе заказа без повторного списания склада; у прямых рецептов исходный материал остаётся на складе. Только после этого измеряется начальный баланс. У старого активного задания следующее назначение равно 2, следующая операция — 1; исторические квитанции не создаются. При загрузке тела 15 недостающие данные не достраиваются.
Экспорт 13 и 14 вызывает чистую проверку представимости до первого байта. `UnsupportedLegacyState` сообщает о возвращаемом несовместимом грузе, приостановленной площадке и нулевом времени ожидающего завершения. Эти состояния полностью сохраняются в современной контрольной точке. Правила собственности и фаз проверяет общий `World::validate_custody`; кодек дополнительно проверяет геометрию, задания, ссылки, размеры и каноничность полей.
[Исторический корпус](../../../tests/fixtures/custody_v14/README.md) содержит 13 подлинных контрольных точек схемы 2, созданных исходной сборкой `f6493e2`, и ожидаемые хеши 80 последующих тактов. Объединённый прогон `e348a42` на Windows x64 GCC 16.2 под Wine 11 подтвердил все такты на последовательном исполнителе и 2/6/12 потоках, точный экспорт 14, канонический цикл схемы 3 и продолжение после загрузки. Отдельно проверены отменённая одиночная доска и каменный блок, смешанный груз без места, частичный возврат, приостановленные кровать и станок, нулевой таймер, старые ссылки квитанций и отказ после аутентифицированного повреждения. [Проверки миграции](../../../tests/custody_migration_tests.cpp) · [Снимки с полной версией 15](../../../tests/snapshot_tests.cpp)
Итоговая проверка S15-04: 14/14 тестов миграции и аутентифицированных изменений прошли за 4,92 с; полный CTest — 3/3 цели, 169 основных, 9 сетевых и 10 клиентских проверок, за 9,57 с. Реальные 2050 заказов заполнили кольцо до 4096 результатов; проверены точный повтор, конфликт, вытеснение, устаревшие номера и каноническая перезапись кольца после загрузки. Дополнительные отрицательные случаи меняют терминальность действующего исполнения, фазу доставки, источник добычи, вместимость отменённого возврата и уникальность ID/эффектов квитанции, сохраняя согласованные вторичные счётчики и внешний SHA-256. Допустимые исторические ссылки на израсходованный стек, нулевой остаток и разные виды владельцев проходят тот же кодек. Полный протокол проверки находится в `s15-custody-final-build.log`, `s15-custody-final-migration.log` и `s15-custody-final-ctest.log` во внешнем каталоге верификации.
Универсальные части продолжают использовать закреплённые Void Binary/Core/Crypto. Собственный формат и перенос игровых фаз относятся к S15; проверка замены библиотечным реестром остаётся связана с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Нативная Windows и сохранность после отключения питания остаются отдельными проверками.
## Ошибки и восстановление
| Ситуация | Требуемое поведение |
+6
View File
@@ -47,6 +47,12 @@
## Приёмка
Клиент Windows может обслуживать хост через `LanSession::poll_host(SimulationRuntime&)`, а гостя — через `poll_guest()`. Хост читает опубликованный снимок и отправляет команду доверенного слота 2 владельцу мира. Сетевой опрос продолжает работу, пока симуляция завершает приказ. `take_result()` возвращает гостю результат вместе с исходными параметрами намерения. До чтения результата следующая команда гостя остаётся в ограниченной очереди. [Сетевой интерфейс](../../../app/lan_session.hpp)
Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается.
Пять проверок `--tag lan-owner` под Wine покрывают квитанции, заполнение очереди, совмещённые пакеты, переподключение при задержанной публикации, откат с незавершённой командой и отказ при несовместимых правилах. Отдельный двоичный клиент прототипа подтвердил обмен в обоих направлениях с новым хостом и гостем. Проверка физической Windows и двух машин остаётся частью сетевой приёмки. [Сценарии](../../../tests/lan_tests.cpp)
Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6)
Селектор `--tag session` под Wine выполнил десять проверок, включая двух клиентов, конфликт данных повтора, откат с новой инкарнацией и отказ до/после изменения. Сценарий из 700 тактов сверяет эталон и 2/6/12 потоков. Подключение окна и сетевого транспорта к владельцу мира входит в следующий срез M01. [Сценарии](../../../tests/session_tests.cpp)
+10 -2
View File
@@ -1,6 +1,6 @@
# S18. Интерфейс, управление и обратная связь
Статус — план реализации. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
Статус — первый срез S18-W01 реализован: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Исходное состояние
@@ -16,6 +16,14 @@
## Последовательность реализации
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное и загружаемое состояние проверяются на карту 32×32 и точное совпадение поддержанного стандартного состава правил. Настоящие альтернативные правила относятся к [S19](S19.md).
Локальная очередь ограничена 64 намерениями и одной отправленной командой. Номер запроса берётся из подтверждённого снимка; занятая очередь владельца оставляет намерение для повтора. Чертёж комнаты, мебели или старого домика удаляется только после принятого результата. Отказ сохраняет возможность редактирования, повторное нажатие не дублирует ожидающую операцию. Гостевые квитанции сопоставляются с ограниченной очередью отправок и поколением сессии. Таймер обслуживает завершения также на главном экране и внутри модальных меню. Одиночная пауза и выбор файла приостанавливают игровое время; меню хозяина сохраняет существующее сетевое поведение.
Сохранение удерживает здоровый опубликованный снимок, а общий файловый сервис сохраняет порядок записей через смену мира. Только последняя актуальная операция обновляет сообщение. Любая новая попытка загрузки сначала отменяет актуальность предыдущего билета, включая попытку открыть повреждённый или отсутствующий файл. Сбой симуляции оставляет последний подтверждённый вид и возможность явной загрузки. [Файлы и восстановление](S15.md) · [Сетевой адаптер](S16.md) · [Проверки состояния клиента](../../../tests/viewer_session_tests.cpp)
Проверка среза: сборка Windows x64 GCC 16.2; Wine 11, verbose CTest — 99 проверок ядра, 9 LAN и 10 состояния клиента. Отдельный прогон настоящего `settlement_viewer.exe` прошёл создание колонии, движение времени, подтверждённую смену приоритета, модальную паузу, выбор файла сохранения, продолжение партии, загрузку нового формата через главное меню в новом процессе, отказ повреждённого файла, загрузку старого формата из списка и штатное закрытие трёх процессов. Сохранения размещались в отдельном временном `LOCALAPPDATA`. Дополнительный Win32-прогон настоящих обработчиков проверил отказ и повтор чертежа, принятую комнату при переносе другой комнаты, старый домик через общий журнал, отрисовку и сохранение при заблокированном тике, смену мира и гостя без ожидания тика. Регрессионный прогон проверил отказ ошибочного повторного подключения с сохранением полученной колонии, откат при отказе владельца после подготовки соединения и запрет подтверждения сноса во время ожидающей загрузки. Отдельная проверка состояния клиента покрывает остановку после сбоя, успешную загрузку и возобновление тиков. Нативная Windows, доступность и визуальная проверка масштабирования остаются отдельной приёмкой; настройки масштаба, клавиш и звука за пределами этого среза.
1. **S18-W01, M01–M02.** Отделить чтение снимков и отправку команд от Win32-обработчиков. Определить модель состояния инструмента, выделения и отмены. Добавить настройку масштаба, клавиш и звука с проверкой конфликтов назначений.
2. **S18-W02, M02–M03.** Собрать путь демо. Игрок размечает склон, ставит склад, выбирает этаж, редактирует дом, видит материалы и подтверждает строительство. Затем назначает мебель, проверяет потребности жителей и сохраняет незавершённую работу.
3. **S18-W03, M04–M06.** Добавить панели рабочих очередей, профессий, запасов и торговых сделок. Фильтры и сортировки устойчиво сохраняют выбранный объект при обновлении снимка. Список населения ведёт к жителю или объясняет его нахождение в другом регионе.
@@ -42,7 +50,7 @@
## VoidLibrary
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
## Приёмка
+14
View File
@@ -10,6 +10,18 @@
На Windows x64 под Wine прошли 9 сценариев для манифестов. Разбор JSON, версии, граф и хеш использованы из закреплённой VoidLibrary. Для замены локального разрешения наборов библиотечным сервисом повторить проверки транзитивных зависимостей, перестановок, конфликтов и идентичности. [Запрос в Void/Library](https://git.faumaray.com/Void/Library/issues/4)
## Выбор исполняемого профиля колонии
Первый выбор механики использует два существующих способа постройки кровати. Профиль по умолчанию собирает основание из дерева или камня, затем отдельно доставляет ткань для постели и подушки. Дополнительный пакет `settlement.plankbeds@1.0.0` задаёт простую кровать из одной доски. Для неё жители сначала выполняют распил за 12 рабочих тактов, затем собирают кровать за 14. Команды отдельной кровати и меблированной комнаты используют выбранный способ. [Профиль и создание колонии](../../../engine/include/settlement/core/colony_profile.hpp) · [Игровые проверки](../../../tests/profile_tests.cpp)
Компилятор профиля проверяет точный состав, версии и SHA-256 реализованных пакетов, затем связывает проверенные поля определения рецепта с начальной конфигурацией мира. Фабрика возвращает мир вместе с его манифестом и постоянным UUID. Настройка выполняется при запуске сценария. Поля демонстрационного определения доски в исходном пакете сохраняют прежнее содержимое. Общее исполнение произвольных данных рецепта относится к S19-W02.
Два исходных пакета и их канонический манифест закреплены проверкой с отпечатком `06d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1`, полученным из ядра до добавления профилей. Выбор по умолчанию включает эти два пакета. Дополнительный профиль разрешает их вместе с пакетом простых кроватей.
Старое сохранение с исходным манифестом может содержать любой из двух способов постройки, включая неактивный сценарий. Проверка загрузки сохраняет этот способ и манифест. Для дополнительного пакета требуется сохранённый способ простых кроватей. Изменённый пакет, неизвестная комбинация или сочетание дополнительного пакета с поэтапной сборкой получает диагностический отказ до замены партии. Общие кодеки остаются доступными для каталогов вызывающего приложения. Прежний LAN11 допускает точный исходный манифест. Интерфейс выбора профиля подключается через S18.
Семь случаев `--tag profile` прошли в Windows x64 под Wine. Оба профиля завершили цель с тремя кроватями и едой, проверены меблированная комната, материал в переноске, продолжение после загрузки и одинаковые контрольные точки на последовательном эталоне и 2/6/12 потоках. Сохранён подлинный файл схемы 1 с исходным манифестом и простой сборкой. Общая сборка прошла 113 тестов ядра и 4 LAN. Все 738 386 байтов прежней траектории совпали с исходной сборкой во всех четырёх режимах. Нативная Windows и подключение выбора в окно проверяются отдельно.
## Исходное состояние
Предметы, профессии, рецепты и команды прототипа определяются C++-типами, а стартовая партия создаётся кодом. В проверенной CMake-конфигурации подключены `Void::Binary`, `Void::Core` и `Void::Testing`. Скриптовый runtime в этот перечень не входит. План вводит новые определения контента и границу расширения. [Текущая конфигурация сборки](../../../CMakeLists.txt)
@@ -28,6 +40,8 @@
Долговременное состояние обработчика представляет собой проверяемые сериализуемые значения с явной схемой. Продолжение события хранит идентификатор шага, данные и запланированный такт. Персистентные coroutine-стеки, нативные замыкания и произвольная память интерпретатора в формат сохранения не входят. Сам обработчик выполняется с фиксированным входом и возвращает предлагаемые изменения.
Состояние обработчика получает ключ пакета, обработчика и версии схемы. Продолжение имеет постоянный идентификатор, детерминированные данные и назначенный такт. Предложения связываются с исходной ревизией снимка и инкарнацией. Владелец проверяет их в устойчивом порядке и одной операцией применяет новое состояние, продвижение генератора случайности, расписание и игровые изменения. Отказ либо устаревшая инкарнация отбрасывают весь этот результат. Исполнение Lua вводится в S19-W03.
Игровой API задаёт детерминированный порядок коллекций, отдельные потоки случайных чисел и правила числовых значений. Авторитетные решения используют разрешённые целочисленные либо явно квантованные величины. Прикладное API запрещает неупорядоченную итерацию для последовательности игровых изменений. Время берётся из номера такта. Вызовы системы, сети, произвольных файлов и нативных расширений недоступны исполняемому игровому скрипту.
Каждый обработчик ограничен по инструкциям, памяти, размеру результата и стоимости вызванных функций хоста. Счётчик Lua-инструкций дополняется ограничением работы C++-функций, поскольку эта работа выполняется вне счётчика интерпретатора. Состояние обработчика и предложения применяются атомарно. Ошибка отбрасывает его незавершённый результат и ставит авторитетное продвижение на безопасную границу с диагностикой. Состав правил мира сохраняется. [Стадии симуляции](S01.md)
+25 -1
View File
@@ -15,7 +15,7 @@
## Срез на 2 декабря 2026 года
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. CMake игры явно выбирает `Binary` и `Core`, а при включённых тестах ещё `Testing`. Для следующих модулей проверены исходники закреплённой версии. Их включение и измерения в итоговой Windows-сборке входят в соответствующие этапы.
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. Windows-сборка M01 выбирает `Algorithms`, `Async`, `Binary`, `Core`, `Crypto`, `Data`, `Math`, `Text` и `Time`. При сборке тестов добавляется `Testing`. [Настройки зависимости](../../CMakeLists.txt)
| Задача игры | Что есть в VoidLibrary | Решение и граница применимости |
|---|---|---|
@@ -33,10 +33,34 @@
## Первое применение правила в M01
| Пробел в проверенном pin | Локальная задача и условие перехода на Void |
|---|---|
| [Атомарная замена файлов на Windows, #3](https://git.faumaray.com/Void/Library/issues/3) | S15, `save_service_win32.cpp`. Заменить адаптер после проверок первой записи, замены слота и отказов до и после публикации, включая пути Unicode. |
| [Ограниченное чтение одного файла на Windows, #9](https://git.faumaray.com/Void/Library/issues/9) | S15, `checkpoint_files.cpp`. Закреплённая `FileSystem::read_file_bounded` возвращает `unsupported` в Windows. Проверки замены охватывают Unicode, точную границу размера, увеличение уже открытого файла сверх лимита и отказ без возврата частичных данных. [API](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/System/Path.hpp) |
| [Разрешение набора пакетов, #4](https://git.faumaray.com/Void/Library/issues/4) | S19, `rules_manifest.cpp`. Проверить транзитивный набор, конфликты, циклы, диагностику и одинаковый отпечаток при перестановке входа. Игровая схема остаётся у S19. |
| [Публикация неизменяемого состояния с ревизией, #5](https://git.faumaray.com/Void/Library/issues/5) | S01, `simulation_runtime.cpp`. Читатели удерживают старую ревизию, пока владелец публикует следующую. При замене мира проверяются инкарнация и сохранность снимка после отказа. |
| [Идемпотентные результаты и конфликт повторов, #6](https://git.faumaray.com/Void/Library/issues/6) | S16, `command_dispatcher.cpp`. Готовый примитив должен вернуть первоначальные принятые и отклонённые результаты, распознать другой запрос под тем же номером и отсечь старую инкарнацию. |
| [Восстанавливаемый счётчик ID с проверкой исчерпания, #7](https://git.faumaray.com/Void/Library/issues/7) | [S06](systems/S06.md) и [S04](systems/S04.md), счётчики в `WorldState` и операции выделения в `world.cpp`. Переход проверяется на двух независимых мирах, сохранении после удаления наибольшего ID и атомарном отказе у верхней границы. В проверенном pin `SeqId<Tag>` использует общий счётчик для тега. [API](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Core/Counted.hpp) |
| [Условное резервирование и перенос количеств в памяти, #8](https://git.faumaray.com/Void/Library/issues/8) | Для реестра резервов [S04](systems/S04.md) и передачи между владельцами [S06](systems/S06.md). Проверка замены должна покрыть конкуренцию за последнюю единицу, полный откат отказа, отмену с грузом и однократное применение повторной доставки после загрузки. Закреплённая `Storage::Batch` применяет условия к ключам и значениям движка хранения. Правила собственности и рецепты определяет игра. [API пакетных операций](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Storage/Batch.hpp) |
При подготовке последовательного эталона 2 декабря 2026 года публичный `main` указывал на закреплённый `7b0fea6`. Для сравнения прототипа доступны `World::write_save` поверх Void Binary/Core и проверки Void Testing. Игровая ветка эталона может прямо вызвать тот же расчёт назначения, маршрута и движения без создания исполнителя. Она сохраняет тот же порядок применения результатов. Журнал приказов и сравнение состояния конкретной колонии принадлежат тесту игры. Новый универсальный исполнитель для этого не требуется. [Кодек игры](../../engine/src/world_save.cpp) · [Набор проверок игры](../../tests/core_tests.cpp)
Для будущей замены пула `FuturePool::try_submit` принимает работу через `ThreadExecutor` и возвращает future. Занятые исполнением задачи входят в предел допуска. При отказе вызываемая функция остаётся у отправителя. Остановка закрывает допуск и завершает принятые задачи. Режим после `join()` не обслуживает новые отправки в `FuturePool`. При замене игрового пула проверить повтор или исполнение каждой отклонённой работы, завершение уже принятых задач до разрушения их данных, исключения и частичный запуск на Windows. [Публичный FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/FuturePool.hpp) · [Контракт ThreadExecutor](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/ThreadExecutor.hpp)
У текущего `settlement::WorkerPool` есть отправка функции, получение future, число потоков и ожидание принятых работ при завершении. Сверить эти четыре операции с `ThreadExecutor + FuturePool`. Начать перенос с эталонной партии, затем испытать переполнение, частичный запуск и остановку. При переполнении симуляция должна выполнить тот же набор логических работ с тем же результатом. Выбранный вариант измерить на малой партии и на нагруженном городе. Существующие тесты Void проверяют поведение утилит, игровые тесты должны дополнительно сравнить хеши мира. [Текущий пул](../../engine/src/worker_pool.cpp) · [Проверки FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/FuturePool.cpp) · [Проверки запуска потоков](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/ThreadExecutor.cpp)
## Подготовка воксельного мира M02
Для проверки порядка завершения реальных вычислений [S21](systems/S21.md) использует работающий `FuturePool`. У `Testing::DeterministicRun` есть очередь управляемых тестовых действий. Для потактного теста игры требуется отдельно зарегистрировать возврат конкретной функции исполнителя, переставить две такие операции и проверить тот же результат мира на 2/6/12 потоках и при заполненной очереди. Предложение относится к тестовому адаптеру реальных задач. [Void/Library #15](https://git.faumaray.com/Void/Library/issues/15) · [Адаптер исполнения игры](../../engine/include/settlement/core/worker_pool.hpp)
Для будущей генерации и навигации проверены публичные заголовки и тесты того же pin. Отдельная программа, собранная для Windows x64 GCC 16.2, прошла под Wine 11. Проверены граничная арифметика, побайтовый FNV-1a, начальное значение Xoshiro256 для seed 42, очередность обхода графа и ограничение объёма поиска. Координаты и seed можно кодировать фиксированными полями через `Binary::Writer::writeLittle` и хешировать средствами `Void::Hash`. Для равных приоритетов поиска порядок задаёт клиент. [Задание исследования](../agent-workflow/tasks/M02-R1.md) · [Числовые операции](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Math/Numeric.hpp)
| Запрос в Void/Library | Локальный потребитель и проверка замены |
|---|---|
| [Восстановление потока RNG и воспроизводимый выбор целого, #10](https://git.faumaray.com/Void/Library/issues/10) | [Генератор прототипа](../../engine/include/settlement/core/deterministic_rng.hpp) и [S02](systems/S02.md). Сохранять алгоритм и версию генератора. Сверить фиксированные значения последовательности, продолжение после смешанных вызовов и независимость двух потоков. Исторический SplitMix64 должен воспроизводить старый ландшафт. |
| [Частное и остаток для знаковых координат, #11](https://git.faumaray.com/Void/Library/issues/11) | [S02](systems/S02.md). У `checked_div(-1,32)` результат 0. Для чанка требуются чанк −1 и локальная координата 31. Проверить обе стороны каждой границы и предельные значения знакового типа. |
| [Обход вокселей лучом, #12](https://git.faumaray.com/Void/Library/issues/12) | [S17](systems/S17.md). Проверить выбранную ячейку и грань при попадании в угол 32³ с обеих сторон, на отрицательных координатах и при ограничении длины. Камера и отсечение высоты принадлежат клиенту. |
| [Набор прочитанных ревизий, #13](https://git.faumaray.com/Void/Library/issues/13) | [Маршруты S03](systems/S03.md) и [геометрия S17](systems/S17.md). Смена опоры в соседнем чанке сбрасывает маршрут, открытие границы делает прежний отрицательный ответ устаревшим, а правка непрочитанного чанка сохраняет результат. При смене инкарнации результат устаревает целиком. |
| [Ограниченные разреженные объёмы и атомарные правки страниц, #14](https://git.faumaray.com/Void/Library/issues/14) | [Каталог чанков S02](systems/S02.md). Проверить изменение двух чанков одной командой, точный отказ при устаревшей ревизии либо исчерпанном бюджете и воспроизводимый порядок дельт. Генератор, материалы и такт активации остаются в игре. |
[Мастер-план](../../PLAN.md)
@@ -15,7 +15,8 @@
namespace settlement {
inline constexpr std::uint32_t checkpoint_version = 1;
inline constexpr std::uint32_t checkpoint_version = 3;
inline constexpr std::string_view checkpoint_signature = "STHCHKPT";
inline constexpr std::size_t max_checkpoint_body_bytes = 128 * 1024 * 1024;
inline constexpr std::size_t max_checkpoint_metadata_bytes = 64 * 1024;
inline constexpr std::size_t max_checkpoint_bytes =
@@ -46,10 +47,11 @@ struct WorldCheckpoint {
RulesManifest rules;
};
// Version 1 stores magic, schema, metadata length and body length, then world UUID,
// All schemas store magic, schema, metadata length and body length, then world UUID,
// city, tick, rules fingerprint and the sorted complete package closure. Each
// package stores its ID, exact version and SHA-256. The body uses World's save
// codec. A final SHA-256 covers every preceding byte. Integers are little-endian.
// codec: schema 1 accepts bodies 1–13; schema 2 requires 14; schema 3 requires 15.
// A final SHA-256 covers every preceding byte. Integers are little-endian.
// The caller holds a stable World for the entire synchronous encode operation.
[[nodiscard]] std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city,
@@ -0,0 +1,77 @@
#pragma once
#include "settlement/core/save_service.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <expected>
#include <functional>
#include <vector>
namespace settlement {
enum class CheckpointFileError {
Io, TooLarge, UnsupportedFormat, InvalidCheckpoint, InvalidLegacy,
IdentityGeneration, ResourceFailure, ReaderFailure,
};
struct CheckpointFileDiagnostic {
CheckpointFileError code;
std::string message;
std::uint32_t native_error = 0;
// Present for a modern codec failure, including the exact incompatible package.
std::optional<CheckpointDiagnostic> checkpoint;
};
using CheckpointLoadResult = std::expected<WorldCheckpoint, CheckpointFileDiagnostic>;
enum class CheckpointLoadAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
struct CheckpointLoadSubmission {
CheckpointLoadAdmission admission = CheckpointLoadAdmission::InvalidRequest;
std::uint64_t request_id = 0;
std::future<CheckpointLoadResult> completion;
};
enum class CheckpointReadPhase { Opened, BeforeRead };
struct CheckpointFilesOptions {
std::size_t load_capacity = 4; // Includes the running read.
std::size_t save_capacity = 8;
std::size_t max_load_bytes = max_checkpoint_bytes;
// Diagnostic/test seam on the reader. Captures must outlive shutdown.
// Calling shutdown from this observer throws logic_error.
std::function<void(CheckpointReadPhase)> read_observer;
};
// Keep one instance for the window lifetime so accepted saves retain FIFO order
// across world/session replacements. Workers own their paths, catalog and held
// snapshots. The caller owns load-ticket fencing and UI completion handling.
class CheckpointFiles {
public:
explicit CheckpointFiles(CheckpointFilesOptions options = {});
explicit CheckpointFiles(std::vector<RulePackage> installed, CheckpointFilesOptions options = {});
~CheckpointFiles();
CheckpointFiles(const CheckpointFiles&) = delete;
CheckpointFiles& operator=(const CheckpointFiles&) = delete;
// Obtain a healthy immutable view with SimulationRuntime::snapshot_for_save().
// Materialization runs on the existing SaveService writer, bounded to
// max_checkpoint_bytes. Rejected calls do not retain the snapshot.
[[nodiscard]] SaveSubmission try_save(
const std::filesystem::path& destination,
const std::shared_ptr<const PublishedSnapshot>& snapshot);
// Opens once and checks actual size/EOF under the byte limit. Modern failures
// retain their diagnostics. Legacy imports receive a fresh stable world UUID
// and the exact supported default manifest from this instance's catalog.
[[nodiscard]] CheckpointLoadSubmission try_load(
const std::filesystem::path& source, std::size_t workers = min_worker_count,
ExecutionMode mode = ExecutionMode::Parallel);
// Closes admission and drains both services, without holding the admission
// mutex while joining. Destruction requires callers to stop using this object.
void shutdown();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace settlement
@@ -0,0 +1,38 @@
#pragma once
#include "settlement/core/checkpoint.hpp"
namespace settlement {
enum class ColonyProfile { Default, PlankBeds };
// Constructed only after the selected packages match an implemented profile.
class ColonyRules {
public:
[[nodiscard]] ColonyProfile profile() const noexcept { return profile_; }
[[nodiscard]] BedConstructionMode bed_mode() const noexcept { return bed_mode_; }
[[nodiscard]] const RulesManifest& manifest() const noexcept { return manifest_; }
private:
ColonyRules(ColonyProfile profile, BedConstructionMode beds, RulesManifest manifest);
ColonyProfile profile_;
BedConstructionMode bed_mode_;
RulesManifest manifest_;
friend std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest&);
};
[[nodiscard]] std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest&);
[[nodiscard]] std::expected<ColonyRules, RulesDiagnostic> colony_rules(ColonyProfile);
// Initializes both the enacted mechanics and their frozen package identities.
[[nodiscard]] std::expected<WorldCheckpoint, CheckpointDiagnostic> make_colony_checkpoint(
ColonyProfile profile, std::size_t workers = min_worker_count,
ExecutionMode mode = ExecutionMode::Parallel);
// Default rules preserve historical saved bed modes, including inactive worlds.
// The optional plank-bed profile requires a saved nonstaged mode. This gate is
// game-specific; generic codecs and SimulationRuntime accept caller-owned catalogs.
[[nodiscard]] std::expected<void, CheckpointDiagnostic> validate_colony_checkpoint(
const WorldCheckpoint&);
} // namespace settlement
+115
View File
@@ -0,0 +1,115 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace settlement {
enum class ItemType : std::uint8_t;
using StackId = std::uint64_t;
using ReservationId = std::uint64_t;
using TransferId = std::uint64_t;
// Recipe quantities are not property and never carry an identity.
struct ItemAmount {
ItemType type{};
std::uint32_t count = 0;
bool operator==(const ItemAmount&) const = default;
};
enum class OwnerKind : std::uint8_t { None, Storage, Resident, Production };
struct StockOwner {
OwnerKind kind = OwnerKind::None;
std::uint64_t id = 0;
bool operator==(const StockOwner&) const = default;
};
enum class ReservationKind : std::uint8_t { Item, Capacity, Worksite, Harvest, Tending };
struct Reservation {
ReservationId id = 0;
ReservationKind kind = ReservationKind::Item;
StockOwner owner{};
StackId stack = 0;
ItemType item{};
std::uint32_t count = 0;
ReservationId backing = 0;
std::uint64_t origin_storage = 0;
bool operator==(const Reservation&) const = default;
};
enum class TransferKind : std::uint8_t { Production, Harvest, Tending, Meal, Return };
enum class CustodyStatus : std::uint8_t {
Accepted, Conflict, Stale, Future, Invalid, Busy, Capacity, Exhausted, Overflow, NoDestination
};
enum class CustodyOperation : std::uint8_t { Admit, Pickup, Deliver, Complete, Cancel, Return, Harvest, Eat, Tend };
enum class CustodyKeyKind : std::uint8_t { Admission, Operation };
struct CustodyKey {
CustodyKeyKind kind = CustodyKeyKind::Admission;
std::uint64_t id = 0; // AgentId for admission, TransferId for operation.
std::uint64_t ordinal = 0;
bool operator==(const CustodyKey&) const = default;
};
struct CustodyLine {
std::uint64_t storage = 0;
ItemType item{};
std::uint32_t count = 0;
bool operator==(const CustodyLine&) const = default;
};
inline constexpr std::size_t custody_material_limit = 5;
inline constexpr std::size_t custody_reservation_limit = 8;
inline constexpr std::size_t custody_receipt_limit = 4096;
struct CustodyRequest {
CustodyKey key{};
CustodyOperation operation = CustodyOperation::Admit;
TransferKind kind = TransferKind::Production;
std::uint64_t production = 0;
std::uint64_t source = 0;
std::uint64_t destination = 0;
std::array<CustodyLine, custody_material_limit> lines{};
std::uint8_t line_count = 0;
bool operator==(const CustodyRequest&) const = default;
};
struct CustodyEffect {
StockOwner owner{};
StackId stack = 0;
ItemType item{};
std::uint32_t count = 0;
bool operator==(const CustodyEffect&) const = default;
};
struct CustodyResult {
CustodyStatus status = CustodyStatus::Invalid;
TransferId transfer = 0;
std::array<ReservationId, custody_reservation_limit> reservations{};
std::array<CustodyEffect, 11> effects{};
std::uint8_t reservation_count = 0;
std::uint8_t effect_count = 0;
bool terminal = false;
bool operator==(const CustodyResult&) const = default;
};
struct CustodyReceipt {
CustodyRequest request{};
CustodyResult result{};
};
struct TransferExecution {
TransferId id = 0;
TransferKind kind = TransferKind::Production;
std::uint64_t production = 0;
std::uint64_t source = 0;
std::uint64_t destination = 0;
std::uint64_t next_operation = 1;
std::array<Reservation, custody_reservation_limit> reservations{};
std::uint8_t reservation_count = 0;
CustodyStatus blocked = CustodyStatus::Accepted;
};
struct ItemBalance {
std::uint64_t opening = 0;
std::uint64_t grant = 0;
std::uint64_t harvest = 0;
std::uint64_t recipe_output = 0;
std::uint64_t recipe_input = 0;
std::uint64_t meal = 0;
std::uint64_t installation = 0;
std::uint64_t demolition = 0;
};
static_assert(sizeof(CustodyRequest) <= 1024 && sizeof(CustodyResult) <= 1024);
} // namespace settlement
@@ -0,0 +1,28 @@
#pragma once
#include "settlement/core/world.hpp"
#include <expected>
#include <span>
namespace settlement {
enum class QuantityTransferError {
InvalidStorage,
InvalidMaterial,
MissingSelection,
InvalidStock,
InsufficientStock,
Overflow,
Capacity,
};
// Pick up all lines for source.id; other delivery stops are left alone. Failure
// leaves both owners unchanged. Optional output capacity is reserved in the same
// commit, after accounting for the space freed by the pickup. No allocation.
// This is one physical pickup, not an idempotent transfer or recipe conversion.
[[nodiscard]] std::expected<void, QuantityTransferError> withdraw_reserved_materials(
Storage& source, Inventory& destination, std::span<const MaterialReservation> materials,
bool reserve_output_slot = false) noexcept;
} // namespace settlement
+87 -15
View File
@@ -7,16 +7,34 @@
#include <iosfwd>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include "settlement/core/worker_pool.hpp"
#include "settlement/core/custody.hpp"
namespace settlement {
using AgentId = std::uint64_t;
using JobId = std::uint64_t;
using ResourceNodeId = std::uint64_t;
using StorageId = std::uint64_t;
using ProductionId = std::uint64_t;
enum class WorldSaveFormat : std::uint32_t { Legacy13 = 13, Current14 = 14, Current15 = 15 };
class UnsupportedLegacyState : public std::runtime_error {
public:
UnsupportedLegacyState() : std::runtime_error("state has no exact legacy representation") {}
};
// Raised only by a complete production-ID preflight, before any domain effects.
class ProductionCapacityError : public std::overflow_error {
public:
ProductionCapacityError() : std::overflow_error("production identities exhausted") {}
};
struct GridPosition {
std::int32_t x = 0;
@@ -35,7 +53,8 @@ enum class AgentState : std::uint8_t {
GoingToEat,
Eating,
GoingToSleep,
Sleeping
Sleeping,
Returning
};
enum class JobState : std::uint8_t {
@@ -103,6 +122,7 @@ enum class RecipeId : std::uint8_t {
};
enum class BedBase : std::uint8_t { Wood, Stone };
enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow };
enum class BedConstructionMode : std::uint8_t { Staged, Plank };
constexpr RecipeId room_part_shape(RecipeId recipe) noexcept {
if (recipe == RecipeId::InstallDoorAlongX) return RecipeId::BuildDoorAlongX;
@@ -224,9 +244,13 @@ public:
void add(ItemType type, std::uint32_t count = 1) noexcept;
void remove(ItemType type, std::uint32_t count = 1) noexcept;
[[nodiscard]] ItemType first_item() const noexcept;
[[nodiscard]] StackId stack_id(ItemType type) const noexcept;
private:
friend class World;
friend struct WorldSaveCodec;
void set_stack_id(ItemType type, StackId id) noexcept;
std::array<std::uint32_t, item_type_count> counts_{};
std::array<StackId, item_type_count> stack_ids_{};
};
struct Agent {
@@ -237,16 +261,19 @@ struct Agent {
std::vector<GridPosition> route;
std::size_t route_cursor = 0;
std::uint32_t work_remaining = 0;
std::size_t resource_node_index = no_entity_index;
std::size_t storage_index = no_entity_index;
ResourceNodeId resource_node_id = 0;
StorageId storage_id = 0;
Inventory inventory;
std::vector<GridPosition> haul_route;
std::size_t production_index = no_entity_index;
ProductionId production_id = 0;
std::uint16_t hunger = 0;
std::uint16_t fatigue = 0;
bool resting_on_ground = false;
Profession profession = Profession::Generalist;
std::uint64_t next_admission = 1;
std::optional<TransferExecution> execution;
[[nodiscard]] bool hungry() const noexcept { return hunger >= hunger_threshold; }
[[nodiscard]] bool tired() const noexcept { return fatigue >= fatigue_threshold; }
};
@@ -260,7 +287,7 @@ struct WorkJob {
};
struct ResourceNode {
std::uint64_t id = 0;
ResourceNodeId id = 0;
GridPosition position;
ItemType type = ItemType::None;
std::uint32_t quantity = 0;
@@ -279,10 +306,11 @@ struct ItemStack {
ItemType type = ItemType::None;
std::uint32_t count = 0;
std::uint32_t reserved = 0;
StackId id = 0;
};
struct Storage {
std::uint64_t id = 0;
StorageId id = 0;
GridPosition position;
std::uint32_t capacity = 0;
std::uint32_t reserved_slots = 0;
@@ -317,17 +345,18 @@ struct Storage {
};
struct MaterialReservation {
std::size_t storage_index;
StorageId storage_id;
ItemType type;
std::uint32_t count;
};
struct ConstructionStop {
std::size_t storage_index;
StorageId storage_id;
std::vector<GridPosition> route_to_next;
};
struct ProductionOrder {
ProductionId id = 0; // Assigned once on insertion; never changed during its lifetime.
GridPosition position;
RecipeId recipe;
JobState state = JobState::Available;
@@ -337,6 +366,8 @@ struct ProductionOrder {
AgentId bed_owner = 0;
BedBase bed_base = BedBase::Wood;
BedStage bed_stage = BedStage::Legacy;
Inventory input;
bool suspended = false;
[[nodiscard]] ItemType bed_material() const noexcept {
if (bed_stage == BedStage::Legacy) return ItemType::Plank;
@@ -367,6 +398,13 @@ struct WorldState {
JobId next_job_id_ = 1;
std::uint64_t next_resource_node_id_ = 1;
std::uint64_t next_storage_id_ = 1;
ProductionId next_production_id_ = 1;
StackId next_stack_id_ = 1;
ReservationId next_reservation_id_ = 1;
TransferId next_transfer_id_ = 1;
std::array<ItemBalance, item_type_count> item_balances_{};
std::vector<std::shared_ptr<const CustodyReceipt>> custody_receipts_;
std::size_t custody_receipt_cursor_ = 0;
std::vector<std::uint8_t> blocked_;
std::vector<Agent> agents_;
std::vector<WorkJob> jobs_;
@@ -402,18 +440,25 @@ public:
StorageKind kind = StorageKind::Materials);
void stock_storage(std::uint64_t id, ItemType type, std::uint32_t count);
void enable_hunger() noexcept;
[[nodiscard]] CommandStatus cancel_production(ProductionId id);
[[nodiscard]] CommandStatus resume_production(ProductionId id);
[[nodiscard]] bool legacy_representable() const noexcept;
void validate_custody() const;
[[nodiscard]] CustodyResult custody_request(const CustodyRequest& request);
[[nodiscard]] const auto& item_balances() const noexcept { return item_balances_; }
[[nodiscard]] const auto& custody_receipts() const noexcept { return custody_receipts_; }
void queue_production(GridPosition position, RecipeId recipe);
[[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept;
[[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> construction_materials(RecipeId recipe, BedBase base) const;
[[nodiscard]] std::array<ItemAmount, 2> construction_materials(RecipeId recipe, BedBase base) const;
[[nodiscard]] RecipeId room_construction_recipe(RecipeId part) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> carpentry_materials(RecipeId recipe) const;
[[nodiscard]] std::array<ItemAmount, 2> carpentry_materials(RecipeId recipe) const;
[[nodiscard]] std::optional<GridPosition> carpenter_workshop() const noexcept {
if (!scenario_active_) return std::nullopt;
return scenario_sawmill_;
}
void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter);
void start_scenario(GridPosition sawmill);
void start_scenario(GridPosition sawmill, BedConstructionMode beds = BedConstructionMode::Staged);
[[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command);
[[nodiscard]] std::uint64_t next_command_sequence(std::uint8_t player) const noexcept;
[[nodiscard]] bool can_place_bed(GridPosition position) const noexcept;
@@ -427,7 +472,9 @@ public:
[[nodiscard]] ScenarioProgress scenario_progress() const noexcept;
void step(TickProfile* profile = nullptr);
void write_svg(const std::string& path) const;
void write_save(std::ostream& stream) const;
// Legacy13 preserves the historical positional wire format. Current14 also
// preserves production identities and their allocation history after deletion.
void write_save(std::ostream& stream, WorldSaveFormat format = WorldSaveFormat::Legacy13) const;
// Called by the owner after every stage has drained. The independent copy
// can be retained by readers on other threads while the owner advances.
[[nodiscard]] std::shared_ptr<const World> capture() const;
@@ -443,6 +490,9 @@ public:
[[nodiscard]] const std::vector<WorkJob>& jobs() const noexcept;
[[nodiscard]] const std::vector<ResourceNode>& resource_nodes() const noexcept;
[[nodiscard]] const std::vector<Storage>& storages() const noexcept;
[[nodiscard]] const Storage* find_storage(StorageId id) const noexcept;
[[nodiscard]] const ProductionOrder* find_production(ProductionId id) const noexcept;
[[nodiscard]] const ResourceNode* find_resource_node(ResourceNodeId id) const noexcept;
[[nodiscard]] const std::vector<ProductionOrder>& production_orders() const noexcept;
[[nodiscard]] const ProductionOrder* assigned_bed(AgentId agent) const noexcept;
[[nodiscard]] bool is_bed_cell(GridPosition position) const noexcept;
@@ -455,6 +505,20 @@ public:
private:
friend struct WorldSaveCodec;
void migrate_legacy_custody();
[[nodiscard]] bool admit_custody(Agent& agent, TransferKind kind, ProductionId production,
ResourceNodeId source, StorageId destination, const std::vector<MaterialReservation>& materials);
void finish_custody(Agent& agent) noexcept;
void advance_return(Agent& agent);
[[nodiscard]] bool pickup_custody(Agent& agent, Storage& source,
const std::vector<MaterialReservation>& materials, bool reserve_output);
[[nodiscard]] bool deliver_custody(Agent& agent, Inventory& destination, StockOwner owner);
[[nodiscard]] bool deposit_custody(Agent& agent, Storage& destination, ItemType type, std::uint32_t count);
void record_custody(std::shared_ptr<const CustodyReceipt> receipt) noexcept;
[[nodiscard]] std::shared_ptr<const CustodyReceipt> prepare_custody(
Agent& agent, CustodyOperation operation, CustodyStatus status = CustodyStatus::Accepted,
StorageId source = 0, StorageId destination = 0);
void commit_custody(Agent& agent, std::shared_ptr<const CustodyReceipt> receipt) noexcept;
struct CaptureTag {};
World(CaptureTag, const World& source);
struct PathResult {
@@ -463,6 +527,11 @@ private:
bool reachable = false;
};
[[nodiscard]] Storage& storage_by_id(StorageId id);
[[nodiscard]] ProductionOrder& production_by_id(ProductionId id);
[[nodiscard]] bool reserve_production(std::size_t count);
void append_production(ProductionOrder order);
[[nodiscard]] ResourceNode& resource_node_by_id(ResourceNodeId id);
[[nodiscard]] std::size_t cell_index(GridPosition position) const noexcept;
[[nodiscard]] PathResult find_path(GridPosition start, GridPosition goal) const;
[[nodiscard]] PathResult assignment_path(GridPosition start, GridPosition goal);
@@ -476,7 +545,8 @@ private:
void finish_rest_step(Agent& agent);
void advance_construction_delivery(Agent& agent);
void finish_production(Agent& agent);
[[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0) const;
[[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0,
StorageId excluded_storage = 0) const;
void update_scenario();
[[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept;
[[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept;
@@ -492,6 +562,8 @@ private:
};
inline constexpr std::int32_t first_colony_map_size = 32;
[[nodiscard]] std::unique_ptr<World> make_first_colony(std::size_t workers);
[[nodiscard]] std::unique_ptr<World> make_first_colony(
std::size_t workers, BedConstructionMode beds = BedConstructionMode::Staged,
ExecutionMode mode = ExecutionMode::Parallel);
} // namespace settlement
+15 -5
View File
@@ -16,7 +16,6 @@
namespace settlement {
namespace {
constexpr std::string_view magic = "STHCHKPT";
constexpr std::size_t header_size = 24;
constexpr std::size_t digest_size = 32;
constexpr std::size_t fixed_metadata_size = 68;
@@ -166,14 +165,14 @@ std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
fail(CheckpointError::LimitExceeded, "metadata_length", "Checkpoint metadata exceeds 64 KiB.");
}
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
world.write_save(stream, WorldSaveFormat::Current15);
auto body = std::move(stream).str();
if (body.size() > max_checkpoint_body_bytes) {
fail(CheckpointError::LimitExceeded, "body_length", "Checkpoint world exceeds 128 MiB.");
}
std::string bytes(header_size + metadata_size + body.size() + digest_size, '\0');
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}));
put_bytes(writer, wire_bytes(magic));
put_bytes(writer, wire_bytes(checkpoint_signature));
put(writer, checkpoint_version);
put(writer, static_cast<std::uint32_t>(metadata_size));
put(writer, static_cast<std::uint64_t>(body.size()));
@@ -210,10 +209,11 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
fail(CheckpointError::InvalidFrame, "frame", "Checkpoint is incomplete.");
}
Void::Binary::Reader header(wire_bytes(bytes).first(header_size));
if (!std::ranges::equal(get_bytes(header, magic.size(), "magic"), wire_bytes(magic))) {
if (!std::ranges::equal(get_bytes(header, checkpoint_signature.size(), "magic"), wire_bytes(checkpoint_signature))) {
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
}
if (get<std::uint32_t>(header, "version") != checkpoint_version) {
const auto schema = get<std::uint32_t>(header, "version");
if (schema != 1 && schema != 2 && schema != 3) {
fail(CheckpointError::UnsupportedVersion, "version", "Checkpoint schema is not supported.");
}
const auto metadata_size = get<std::uint32_t>(header, "metadata_length");
@@ -264,6 +264,16 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
}
auto rules = validate_rules(saved, fingerprint, installed);
const auto body = bytes.substr(header_size + metadata_size, static_cast<std::size_t>(body_size));
if (body.size() < 12 || body.substr(0, 8) != "SETTLERS") {
fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint world header is invalid.");
}
Void::Binary::Reader body_header(wire_bytes(body).subspan(8, 4));
const auto body_version = get<std::uint32_t>(body_header, "world.version");
if ((schema == 1 && (body_version < 1 || body_version > 13)) ||
(schema == 2 && body_version != 14) ||
(schema == 3 && body_version != 15)) {
fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint schema and world version do not match.");
}
std::ispanstream stream(std::span<const char>{body.data(), body.size()});
auto world = World::read_save(stream, workers, mode);
if (world->tick() != tick) {
+248
View File
@@ -0,0 +1,248 @@
#include "settlement/core/checkpoint_files.hpp"
#include <Void/Async/FuturePool.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <algorithm>
#include <array>
#include <limits>
#include <mutex>
#include <spanstream>
#include <stdexcept>
#include <utility>
namespace settlement {
namespace {
constexpr std::string_view legacy_signature = "SETTLERS";
bool valid_path(const std::filesystem::path& path) {
return path.is_absolute() && !path.filename().empty() &&
path.native().find(L'\0') == std::wstring::npos;
}
std::vector<RulePackage> default_catalog() {
auto catalog = builtin_rule_packages();
if (!catalog) throw std::runtime_error(catalog.error().message);
return std::move(*catalog);
}
struct OpenFile {
HANDLE handle;
~OpenFile() { CloseHandle(handle); }
};
CheckpointFileDiagnostic diagnostic(CheckpointFileError code, std::string message,
std::uint32_t native_error = 0) {
return {code, std::move(message), native_error, std::nullopt};
}
// Void::FileSystem::read_file_bounded is unsupported on Windows at the pin.
// https://git.faumaray.com/Void/Library/issues/9 tracks this adapter's replacement.
// Reuse it after checkpoint-file tests prove one-handle reads, Unicode paths,
// initial/growing-file limits, EOF checking and independent bounded admission.
CheckpointLoadResult prepare(const std::filesystem::path& path,
std::span<const RulePackage> catalog,
const CheckpointFilesOptions& options,
std::size_t workers, ExecutionMode mode) {
try {
OpenFile file{CreateFileW(path.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr)};
if (file.handle == INVALID_HANDLE_VALUE) {
return std::unexpected{diagnostic(CheckpointFileError::Io,
"Could not open the checkpoint file.", GetLastError())};
}
LARGE_INTEGER size{};
if (GetFileType(file.handle) != FILE_TYPE_DISK || !GetFileSizeEx(file.handle, &size)) {
return std::unexpected{diagnostic(CheckpointFileError::Io,
"Could not determine the checkpoint file size.", GetLastError())};
}
if (size.QuadPart < 0 ||
static_cast<std::uint64_t>(size.QuadPart) > options.max_load_bytes) {
return std::unexpected{diagnostic(CheckpointFileError::TooLarge,
"Checkpoint file exceeds the configured byte limit.")};
}
if (options.read_observer) options.read_observer(CheckpointReadPhase::Opened);
std::string bytes;
bytes.reserve(static_cast<std::size_t>(size.QuadPart));
std::array<char, 65536> buffer;
for (;;) {
if (options.read_observer) options.read_observer(CheckpointReadPhase::BeforeRead);
DWORD count = 0;
if (!ReadFile(file.handle, buffer.data(), static_cast<DWORD>(buffer.size()), &count, nullptr)) {
return std::unexpected{diagnostic(CheckpointFileError::Io,
"Could not read the checkpoint file.", GetLastError())};
}
if (count == 0) break;
if (count > options.max_load_bytes - bytes.size()) {
return std::unexpected{diagnostic(CheckpointFileError::TooLarge,
"Checkpoint file grew beyond the configured byte limit.")};
}
bytes.append(buffer.data(), count);
}
if (bytes.starts_with(checkpoint_signature)) {
auto candidate = decode_checkpoint(bytes, catalog, workers, mode);
if (!candidate) {
CheckpointFileDiagnostic error{CheckpointFileError::InvalidCheckpoint,
candidate.error().message, 0, std::move(candidate.error())};
return std::unexpected{std::move(error)};
}
return std::move(*candidate);
}
if (!bytes.starts_with(legacy_signature)) {
return std::unexpected{diagnostic(CheckpointFileError::UnsupportedFormat,
"File has neither a checkpoint nor a legacy settlement signature.")};
}
auto defaults = default_rules_manifest();
if (!defaults) {
return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure,
defaults.error().message)};
}
std::vector<std::string> selected;
selected.reserve(defaults->packages().size());
for (const auto& package : defaults->packages()) selected.push_back(package.id);
auto installed_defaults = resolve_rules(catalog, selected);
if (!installed_defaults || *installed_defaults != *defaults) {
CheckpointDiagnostic detail{CheckpointError::RulesMismatch, "rules.packages", {},
"Legacy imports require the exact supported default packages."};
if (!installed_defaults) {
detail.package = installed_defaults.error().package;
detail.message = installed_defaults.error().message;
} else {
for (const auto& package : defaults->packages()) {
const auto found = std::find(installed_defaults->packages().begin(),
installed_defaults->packages().end(), package);
if (found == installed_defaults->packages().end()) {
detail.package = package.id;
break;
}
}
}
return std::unexpected{CheckpointFileDiagnostic{CheckpointFileError::InvalidCheckpoint,
detail.message, 0, std::move(detail)}};
}
std::unique_ptr<World> world;
try {
std::ispanstream input{std::span<const char>{bytes.data(), bytes.size()}};
world = World::read_save(input, workers, mode);
} catch (const std::bad_alloc&) {
throw;
} catch (const std::exception& error) {
return std::unexpected{diagnostic(CheckpointFileError::InvalidLegacy, error.what())};
}
const auto id = Void::Uuid::try_v4();
if (!id || id->is_nil()) {
return std::unexpected{diagnostic(CheckpointFileError::IdentityGeneration,
"Could not create an identity for the imported world.")};
}
return WorldCheckpoint{std::move(world), *id, 1, std::move(*installed_defaults)};
} catch (const std::bad_alloc&) {
return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure, "Out of memory.")};
} catch (const std::exception& error) {
return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, error.what())};
} catch (...) {
return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, "Checkpoint reader failed.")};
}
}
} // namespace
struct CheckpointFiles::Impl {
Impl(std::vector<RulePackage> catalog, CheckpointFilesOptions configured)
: options(std::move(configured)), installed(std::move(catalog)),
writer(SaveServiceOptions{.capacity = options.save_capacity,
.max_bytes = max_checkpoint_bytes, .fault_hook = {}}) {
if (options.load_capacity == 0 || options.max_load_bytes == 0 ||
options.max_load_bytes > max_checkpoint_bytes) {
throw std::invalid_argument("checkpoint reader limits are invalid");
}
auto created = Void::Async::ThreadExecutor::create(
{.workers = 1, .max_admitted = options.load_capacity});
if (!created) throw std::runtime_error("cannot create checkpoint reader");
executor = std::move(*created);
pool = std::make_unique<Void::Async::FuturePool>(*executor);
if (!executor->start()) throw std::runtime_error("cannot start checkpoint reader");
}
CheckpointFilesOptions options;
std::vector<RulePackage> installed;
SaveService writer;
std::unique_ptr<Void::Async::ThreadExecutor> executor;
std::unique_ptr<Void::Async::FuturePool> pool;
std::mutex admission_mutex;
bool closed = false;
std::uint64_t next_id = 1;
};
CheckpointFiles::CheckpointFiles(CheckpointFilesOptions options)
: CheckpointFiles(default_catalog(), std::move(options)) {}
CheckpointFiles::CheckpointFiles(std::vector<RulePackage> installed, CheckpointFilesOptions options)
: impl_(std::make_unique<Impl>(std::move(installed), std::move(options))) {}
CheckpointFiles::~CheckpointFiles() { shutdown(); }
SaveSubmission CheckpointFiles::try_save(
const std::filesystem::path& destination,
const std::shared_ptr<const PublishedSnapshot>& snapshot) {
std::unique_lock lock(impl_->admission_mutex, std::try_to_lock);
if (!lock.owns_lock()) return {SaveAdmission::Busy, 0, {}};
if (impl_->closed) return {SaveAdmission::Closed, 0, {}};
if (!snapshot || !snapshot->world || !snapshot->rules ||
snapshot->identity.world.is_nil() || snapshot->identity.city == 0) {
return {SaveAdmission::InvalidRequest, 0, {}};
}
return impl_->writer.try_submit(SaveRequest{destination, snapshot->world->tick(),
snapshot->identity.session, [snapshot] {
auto bytes = encode_checkpoint(*snapshot->world, snapshot->identity.world,
snapshot->identity.city, *snapshot->rules);
if (!bytes) throw std::runtime_error(bytes.error().message);
return std::move(*bytes);
}});
}
CheckpointLoadSubmission CheckpointFiles::try_load(
const std::filesystem::path& source, std::size_t workers, ExecutionMode mode) {
std::unique_lock lock(impl_->admission_mutex, std::try_to_lock);
if (!lock.owns_lock()) return {CheckpointLoadAdmission::Busy, 0, {}};
if (impl_->closed) return {CheckpointLoadAdmission::Closed, 0, {}};
if (impl_->executor->admitted() >= impl_->options.load_capacity) {
return {CheckpointLoadAdmission::Busy, 0, {}};
}
if (!valid_path(source) ||
(mode == ExecutionMode::Parallel && (workers < min_worker_count || workers > max_worker_count)) ||
(mode != ExecutionMode::Parallel && mode != ExecutionMode::SerialReference)) {
return {CheckpointLoadAdmission::InvalidRequest, 0, {}};
}
if (impl_->next_id == 0) return {CheckpointLoadAdmission::IdExhausted, 0, {}};
auto future = impl_->pool->try_submit(
[state = impl_.get(), source = std::filesystem::path(source), workers, mode] {
return prepare(source, state->installed, state->options, workers, mode);
});
if (!future) {
return {future.error() == Void::Async::AdmissionError::overloaded ?
CheckpointLoadAdmission::Busy : CheckpointLoadAdmission::Closed, 0, {}};
}
const auto id = impl_->next_id++;
return {CheckpointLoadAdmission::Accepted, id, std::move(*future)};
}
void CheckpointFiles::shutdown() {
if (impl_->executor->is_executor_thread()) {
throw std::logic_error("checkpoint reader cannot join itself");
}
{
std::lock_guard lock(impl_->admission_mutex);
impl_->closed = true;
}
static_cast<void>(impl_->executor->join());
impl_->writer.shutdown();
}
} // namespace settlement
+134
View File
@@ -0,0 +1,134 @@
#include "settlement/core/colony_profile.hpp"
#include <Void/Data/StrictJson.hpp>
#include <algorithm>
#include <array>
#include <exception>
#include <utility>
namespace settlement {
namespace {
RulesDiagnostic unsupported(std::string package, std::string message) {
return {std::move(package), "builtin/colony-profile", "profile", std::move(message), 0};
}
std::expected<RulesManifest, RulesDiagnostic> resolve_profile(
ColonyProfile profile, std::span<const RulePackage> catalog) {
if (profile != ColonyProfile::Default && profile != ColonyProfile::PlankBeds) {
return std::unexpected{unsupported({}, "Unknown colony profile.")};
}
const std::array selected{std::string{profile == ColonyProfile::Default ?
"settlement.colony" : "settlement.plankbeds"}};
return resolve_rules(catalog, selected);
}
std::expected<BedConstructionMode, RulesDiagnostic> plank_bed_mode(const RulePackage& package) {
namespace json = Void::Json::Strict;
const auto definitions = package.definitions();
if (definitions.size() != 1 || definitions.front().id != "settlement.plankbeds:bed" ||
definitions.front().kind != "recipe") {
return std::unexpected{unsupported(package.identity().id, "Plank-bed recipe is missing.")};
}
const auto parsed = json::parse(definitions.front().canonical_data,
{.maximumDepth = 4, .allowDecimals = false});
const auto* fields = parsed ? std::get_if<json::Value::Object>(&parsed->value) : nullptr;
if (!fields || fields->size() != 5) {
return std::unexpected{unsupported(package.identity().id, "Invalid plank-bed recipe data.")};
}
const auto matches = [&]<class T>(std::string_view key, const T& expected) {
const auto entry = fields->find(key);
if (entry == fields->end()) return false;
const auto* value = std::get_if<T>(&entry->second.value);
return value && *value == expected;
};
// This finite profile binds typed content to the already implemented recipe.
// General recipe-data execution is scheduled separately in S19-W02.
if (!matches("assembly", std::string{"plank"}) ||
!matches("input", std::string{"settlement.colony:board"}) ||
!matches("input_count", std::int64_t{1}) ||
!matches("saw_work_ticks", std::int64_t{12}) ||
!matches("work_ticks", std::int64_t{14})) {
return std::unexpected{unsupported(package.identity().id, "Plank-bed recipe is not implemented.")};
}
return BedConstructionMode::Plank;
}
CheckpointDiagnostic checkpoint_error(const RulesDiagnostic& error) {
return {CheckpointError::RulesMismatch, error.field, error.package, error.message};
}
} // namespace
ColonyRules::ColonyRules(ColonyProfile profile, BedConstructionMode beds, RulesManifest manifest)
: profile_(profile), bed_mode_(beds), manifest_(std::move(manifest)) {}
std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest& manifest) {
const auto catalog = builtin_rule_packages();
if (!catalog) return std::unexpected{catalog.error()};
for (const auto& identity : manifest.packages()) {
const auto installed = std::find_if(catalog->begin(), catalog->end(),
[&](const auto& package) { return package.identity().id == identity.id; });
if (installed == catalog->end() || installed->identity() != identity) {
return std::unexpected{unsupported(identity.id, "Package has no matching compiled colony implementation.")};
}
}
const auto default_manifest = resolve_profile(ColonyProfile::Default, *catalog);
if (!default_manifest) return std::unexpected{default_manifest.error()};
if (manifest == *default_manifest) {
return ColonyRules{ColonyProfile::Default, BedConstructionMode::Staged, manifest};
}
const auto plank_manifest = resolve_profile(ColonyProfile::PlankBeds, *catalog);
if (!plank_manifest) return std::unexpected{plank_manifest.error()};
if (manifest != *plank_manifest) {
return std::unexpected{unsupported({}, "Selected package closure is not an implemented colony profile.")};
}
const auto package = std::find_if(catalog->begin(), catalog->end(),
[](const auto& entry) { return entry.identity().id == "settlement.plankbeds"; });
const auto mode = plank_bed_mode(*package);
if (!mode) return std::unexpected{mode.error()};
return ColonyRules{ColonyProfile::PlankBeds, *mode, manifest};
}
std::expected<ColonyRules, RulesDiagnostic> colony_rules(ColonyProfile profile) {
const auto catalog = builtin_rule_packages();
if (!catalog) return std::unexpected{catalog.error()};
const auto manifest = resolve_profile(profile, *catalog);
if (!manifest) return std::unexpected{manifest.error()};
return compile_colony_rules(*manifest);
}
std::expected<WorldCheckpoint, CheckpointDiagnostic> make_colony_checkpoint(
ColonyProfile profile, std::size_t workers, ExecutionMode mode) {
const auto rules = colony_rules(profile);
if (!rules) return std::unexpected{checkpoint_error(rules.error())};
const auto world_id = Void::Uuid::try_v4();
if (!world_id) {
return std::unexpected{CheckpointDiagnostic{
CheckpointError::ResourceFailure, "world_id", {}, "Could not create a world identity."}};
}
try {
return WorldCheckpoint{make_first_colony(workers, rules->bed_mode(), mode),
*world_id, 1, rules->manifest()};
} catch (const std::exception& error) {
return std::unexpected{CheckpointDiagnostic{
CheckpointError::ResourceFailure, "world", {}, error.what()}};
}
}
std::expected<void, CheckpointDiagnostic> validate_colony_checkpoint(const WorldCheckpoint& candidate) {
if (!candidate.world || candidate.world_id.is_nil() || candidate.city == 0) {
return std::unexpected{CheckpointDiagnostic{
CheckpointError::InvalidIdentity, "world", {}, "A colony needs an owned world and nonzero identities."}};
}
const auto rules = compile_colony_rules(candidate.rules);
if (!rules) return std::unexpected{checkpoint_error(rules.error())};
if (rules->profile() == ColonyProfile::PlankBeds && candidate.world->staged_beds()) {
return std::unexpected{CheckpointDiagnostic{CheckpointError::RulesMismatch, "world.staged_beds",
"settlement.plankbeds", "Saved bed assembly does not match the selected plank-bed package."}};
}
return {};
}
} // namespace settlement
+2
View File
@@ -78,6 +78,8 @@ CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const
const auto& payload = std::get<LegacyCabinPayload>(command.payload);
try {
world.queue_cabin(payload.cell, payload.sawmill, payload.stonecutter);
} catch (const ProductionCapacityError&) {
return CommandStatus::Busy;
} catch (const std::invalid_argument&) {
return CommandStatus::InvalidTarget;
}
+836
View File
@@ -0,0 +1,836 @@
#include "settlement/core/world.hpp"
#include "settlement/core/inventory_transaction.hpp"
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <limits>
#include <set>
#include <map>
#include <tuple>
namespace settlement {
namespace {
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
bool room(std::uint64_t next, std::uint64_t count) noexcept {
return next != 0 && count <= maximum - next;
}
auto stock(Storage& storage, ItemType item) {
return std::find_if(storage.items.begin(), storage.items.end(), [item](const auto& s) { return s.type == item; });
}
void retarget(TransferExecution& execution, StockOwner from, StackId old_id,
StockOwner to, StackId new_id) noexcept {
for (auto& claim : execution.reservations) {
if (claim.id && claim.kind == ReservationKind::Item && claim.owner == from && claim.stack == old_id) {
claim.owner = to;
claim.stack = new_id;
}
}
}
CustodyRequest operation_request(const Agent& agent, CustodyOperation operation,
StorageId source, StorageId destination) {
CustodyRequest request;
request.key = {CustodyKeyKind::Operation, agent.execution->id, agent.execution->next_operation};
request.operation = operation;
request.kind = agent.execution->kind;
request.production = agent.execution->production;
request.source = source;
request.destination = destination;
return request;
}
void effects(CustodyResult& result, const Inventory& inventory, StockOwner owner) {
for (std::size_t i = 1; i <= item_type_count; ++i) {
const auto item = static_cast<ItemType>(i);
if (inventory.item_count(item)) result.effects[result.effect_count++] =
{owner, inventory.stack_id(item), item, inventory.item_count(item)};
}
}
}
StackId Inventory::stack_id(ItemType type) const noexcept {
const auto i = static_cast<std::size_t>(type);
return i > 0 && i <= stack_ids_.size() ? stack_ids_[i - 1] : 0;
}
void Inventory::set_stack_id(ItemType type, StackId id) noexcept {
const auto i = static_cast<std::size_t>(type);
if (i > 0 && i <= stack_ids_.size()) stack_ids_[i - 1] = id;
}
void World::record_custody(std::shared_ptr<const CustodyReceipt> receipt) noexcept {
if (custody_receipts_.size() < custody_receipt_limit) custody_receipts_.push_back(std::move(receipt));
else {
custody_receipts_[custody_receipt_cursor_] = std::move(receipt);
custody_receipt_cursor_ = (custody_receipt_cursor_ + 1) % custody_receipt_limit;
}
}
std::shared_ptr<const CustodyReceipt> World::prepare_custody(Agent& agent, CustodyOperation operation,
CustodyStatus status, StorageId source, StorageId destination) {
if (!agent.execution || !room(agent.execution->next_operation, 1)) return {};
custody_receipts_.reserve(custody_receipt_limit);
auto receipt = std::make_shared<CustodyReceipt>();
receipt->request = operation_request(agent, operation, source, destination);
receipt->result.status = status;
receipt->result.transfer = agent.execution->id;
return receipt;
}
void World::commit_custody(Agent& agent, std::shared_ptr<const CustodyReceipt> receipt) noexcept {
agent.execution->blocked = receipt->result.status;
++agent.execution->next_operation;
record_custody(std::move(receipt));
}
CustodyResult World::custody_request(const CustodyRequest& request) {
// The scheduler issues operations. This endpoint recovers their exact result;
// it never admits unissued work through an out-of-order retry.
for (const auto& receipt : custody_receipts_) {
if (receipt->request.key == request.key) {
return receipt->request == request ? receipt->result : CustodyResult{CustodyStatus::Conflict};
}
}
if (request.key.id == 0 || request.key.ordinal == 0) return {CustodyStatus::Invalid};
if (request.key.kind == CustodyKeyKind::Admission) {
const auto actor = std::find_if(agents_.begin(), agents_.end(), [&](const auto& a) { return a.id == request.key.id; });
if (actor == agents_.end()) return {CustodyStatus::Invalid};
return {request.key.ordinal < actor->next_admission ? CustodyStatus::Stale : CustodyStatus::Future};
}
if (request.key.kind != CustodyKeyKind::Operation) return {CustodyStatus::Invalid};
for (const auto& agent : agents_) {
if (agent.execution && agent.execution->id == request.key.id) {
return {request.key.ordinal < agent.execution->next_operation ? CustodyStatus::Stale : CustodyStatus::Future};
}
}
return {request.key.id < next_transfer_id_ ? CustodyStatus::Stale : CustodyStatus::Future};
}
bool World::admit_custody(Agent& agent, TransferKind kind, ProductionId production,
ResourceNodeId source, StorageId destination, const std::vector<MaterialReservation>& materials) {
if (agent.execution || !room(next_transfer_id_, 1) || !room(agent.next_admission, 1) ||
materials.size() > custody_material_limit) return false;
TransferExecution execution;
execution.id = next_transfer_id_;
execution.kind = kind;
execution.production = production;
execution.source = source;
execution.destination = destination;
auto next = next_reservation_id_;
const auto add = [&](Reservation claim) {
if (!room(next, 1) || execution.reservation_count == custody_reservation_limit) return false;
claim.id = next++;
execution.reservations[execution.reservation_count++] = claim;
return true;
};
CustodyRequest request;
request.key = {CustodyKeyKind::Admission, agent.id, agent.next_admission};
request.kind = kind;
request.production = production;
request.source = source;
request.destination = destination;
for (const auto& material : materials) {
auto& store = storage_by_id(material.storage_id);
const auto stack = stock(store, material.type);
if (material.count == 0 || stack == store.items.end() || stack->id == 0 ||
stack->reserved > stack->count || material.count > stack->count - stack->reserved) return false;
if (!add({0, ReservationKind::Item, {OwnerKind::Storage, store.id}, stack->id,
material.type, material.count, 0, store.id})) return false;
request.lines[request.line_count++] = {store.id, material.type, material.count};
}
if (production && !add({0, ReservationKind::Worksite, {OwnerKind::Production, production}, 0, {}, 1})) return false;
if (source && !add({0, kind == TransferKind::Tending ? ReservationKind::Tending : ReservationKind::Harvest,
{}, 0, {}, 1})) return false;
if (destination) {
auto& store = storage_by_id(destination);
ReservationId backing = 0;
if (production) {
// Every production output replaces claimed input in this exact store.
for (const auto& claim : execution.reservations) {
if (claim.id && claim.kind == ReservationKind::Item && claim.origin_storage == destination) {
backing = claim.id;
break;
}
}
}
if (!backing && store.total_items() + store.reserved_slots >= store.capacity) return false;
if (!add({0, ReservationKind::Capacity, {OwnerKind::Storage, destination}, 0, {}, 1, backing})) return false;
}
custody_receipts_.reserve(custody_receipt_limit);
auto receipt = std::make_shared<CustodyReceipt>();
receipt->request = request;
receipt->result = {CustodyStatus::Accepted, execution.id};
receipt->result.reservation_count = execution.reservation_count;
for (std::size_t i = 0; i < execution.reservation_count; ++i) receipt->result.reservations[i] = execution.reservations[i].id;
// The caller has already allocated routes and material vectors. No operation
// below can throw; its existing cache increments follow immediately.
agent.execution = execution;
++agent.next_admission;
++next_transfer_id_;
next_reservation_id_ = next;
record_custody(std::move(receipt));
return true;
}
bool World::pickup_custody(Agent& agent, Storage& source,
const std::vector<MaterialReservation>& materials, bool reserve_output) {
Storage planned_source = source;
Inventory planned_inventory = agent.inventory;
auto execution = *agent.execution;
auto next = next_stack_id_;
custody_receipts_.reserve(custody_receipt_limit);
auto receipt = std::make_shared<CustodyReceipt>();
receipt->request = operation_request(agent, CustodyOperation::Pickup, source.id, 0);
receipt->result = {CustodyStatus::Accepted, execution.id};
const auto fail = [&](CustodyStatus status) {
receipt->result.status = status;
commit_custody(agent, receipt);
return false;
};
if (!room(execution.next_operation, 1)) return false;
if (!withdraw_reserved_materials(planned_source, planned_inventory, materials, reserve_output)) return fail(CustodyStatus::Invalid);
for (const auto& stack : source.items) {
const auto remaining = planned_source.item_count(stack.type);
if (remaining == stack.count) continue;
auto id = agent.inventory.stack_id(stack.type);
if (!id) {
if (remaining) {
if (!room(next, 1)) return fail(CustodyStatus::Exhausted);
id = next++;
} else id = stack.id;
}
if (!id) return fail(CustodyStatus::Invalid);
planned_inventory.set_stack_id(stack.type, id);
retarget(execution, {OwnerKind::Storage, source.id}, stack.id, {OwnerKind::Resident, agent.id}, id);
if (execution.kind == TransferKind::Meal) for (auto& claim : execution.reservations) {
if (claim.kind == ReservationKind::Item) claim.origin_storage = 0;
}
}
if (reserve_output) {
for (auto& claim : execution.reservations) {
if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == source.id) claim.backing = 0;
}
}
effects(receipt->result, planned_inventory, {OwnerKind::Resident, agent.id});
source.items.swap(planned_source.items);
source.reserved_slots = planned_source.reserved_slots;
agent.inventory = planned_inventory;
agent.execution = execution;
next_stack_id_ = next;
commit_custody(agent, receipt);
return true;
}
bool World::deliver_custody(Agent& agent, Inventory& destination, StockOwner owner) {
auto planned = destination;
auto execution = *agent.execution;
custody_receipts_.reserve(custody_receipt_limit);
auto receipt = std::make_shared<CustodyReceipt>();
receipt->request = operation_request(agent, CustodyOperation::Deliver, 0, 0);
receipt->result = {CustodyStatus::Accepted, execution.id};
if (!room(execution.next_operation, 1)) return false;
for (std::size_t i = 1; i <= item_type_count; ++i) {
const auto type = static_cast<ItemType>(i);
const auto count = agent.inventory.item_count(type);
if (!count) continue;
if (!Void::Numeric::checked_add(planned.item_count(type), count)) {
receipt->result.status = CustodyStatus::Overflow;
commit_custody(agent, receipt);
return false;
}
auto id = planned.stack_id(type);
if (!id) id = agent.inventory.stack_id(type);
planned.add(type, count);
planned.set_stack_id(type, id);
retarget(execution, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(type), owner, id);
}
effects(receipt->result, planned, owner);
destination = planned;
agent.inventory = {};
agent.execution = execution;
commit_custody(agent, receipt);
return true;
}
bool World::deposit_custody(Agent& agent, Storage& destination, ItemType type, std::uint32_t count) {
if (!count || count > agent.inventory.item_count(type) || !destination.accepts(type)) return false;
auto planned = destination;
auto inventory = agent.inventory;
auto next = next_stack_id_;
auto execution = *agent.execution;
custody_receipts_.reserve(custody_receipt_limit);
auto receipt = std::make_shared<CustodyReceipt>();
receipt->request = operation_request(agent, execution.kind == TransferKind::Return ? CustodyOperation::Return : CustodyOperation::Deliver, 0, destination.id);
receipt->request.lines[0] = {destination.id, type, count};
receipt->request.line_count = 1;
receipt->result = {CustodyStatus::Accepted, execution.id};
if (!room(execution.next_operation, 1)) return false;
const auto fail = [&](CustodyStatus status) {
receipt->result.status = status;
commit_custody(agent, receipt);
return false;
};
auto slots = planned.reserved_slots;
for (auto& claim : execution.reservations) {
if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == destination.id && !claim.backing) {
if (slots < claim.count) return fail(CustodyStatus::Invalid);
slots -= claim.count;
claim = {};
}
}
if (planned.total_items() + slots + count > planned.capacity) return fail(CustodyStatus::Capacity);
auto target = stock(planned, type);
StackId id = 0;
if (target != planned.items.end()) {
const auto amount = Void::Numeric::checked_add(target->count, count);
if (!amount) return fail(CustodyStatus::Overflow);
target->count = *amount;
id = target->id;
} else {
id = inventory.stack_id(type);
if (count < inventory.item_count(type)) {
if (!room(next, 1)) return fail(CustodyStatus::Exhausted);
id = next++;
}
planned.items.push_back({type, count, 0, id});
std::sort(planned.items.begin(), planned.items.end(), [](const auto& a, const auto& b) { return a.type < b.type; });
}
inventory.remove(type, count);
receipt->result.effects[0] = {{OwnerKind::Storage, destination.id}, id, type, planned.item_count(type)};
receipt->result.effect_count = 1;
receipt->result.terminal = inventory.empty();
for (auto& claim : execution.reservations) {
if (claim.id && claim.kind == ReservationKind::Item && claim.owner == StockOwner{OwnerKind::Resident, agent.id} && claim.item == type) {
if (claim.count <= count) claim = {};
else claim.count -= count;
}
}
destination.items.swap(planned.items);
destination.reserved_slots = slots;
agent.inventory = inventory;
agent.execution = execution;
next_stack_id_ = next;
commit_custody(agent, receipt);
return true;
}
void World::finish_custody(Agent& agent) noexcept { agent.execution.reset(); }
bool World::legacy_representable() const noexcept {
for (const auto& order : production_orders_) if (order.suspended) return false;
for (const auto& agent : agents_) {
if (agent.state == AgentState::Returning || (agent.execution && agent.execution->kind == TransferKind::Return && agent.state != AgentState::Hauling)) return false;
if ((agent.state == AgentState::Working || agent.state == AgentState::Gathering || agent.state == AgentState::Eating) && agent.work_remaining == 0) return false;
if (agent.production_id == 0 && !agent.inventory.empty()) {
const auto type = agent.inventory.first_item();
if (agent.state == AgentState::Eating) {
if (type != ItemType::Berries || agent.inventory.item_count(type) != 1) return false;
} else if (agent.state != AgentState::Hauling || agent.storage_id == 0 ||
type == ItemType::Plank || type == ItemType::StoneBlock || type == ItemType::Cloth ||
agent.inventory.item_count(type) != 1) return false;
for (std::size_t i = 1; i <= item_type_count; ++i) {
if (static_cast<ItemType>(i) != type && agent.inventory.item_count(static_cast<ItemType>(i))) return false;
}
}
}
return true;
}
CommandStatus World::cancel_production(ProductionId id) {
auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; });
if (it == production_orders_.end()) return CommandStatus::InvalidTarget;
if (it->state == JobState::Completed || it->suspended) return CommandStatus::Busy;
auto actor = std::find_if(agents_.begin(), agents_.end(), [id](const auto& a) { return a.production_id == id; });
const bool retain = it->recipe == RecipeId::WeaveCloth ||
(it->recipe == RecipeId::BuildBed && (it->bed_stage == BedStage::Bedding || it->bed_stage == BedStage::Pillow));
if (actor != agents_.end()) {
if (!actor->execution) return CommandStatus::Busy;
auto inventory = actor->inventory;
for (std::size_t i = 1; i <= item_type_count; ++i) {
const auto item = static_cast<ItemType>(i);
const auto count = it->input.item_count(item);
if (!Void::Numeric::checked_add(inventory.item_count(item), count)) return CommandStatus::Busy;
if (count) {
if (!inventory.stack_id(item)) inventory.set_stack_id(item, it->input.stack_id(item));
inventory.add(item, count);
}
}
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(*actor, CustodyOperation::Cancel));
if (!receipt) return CommandStatus::Busy;
effects(receipt->result, inventory, {OwnerKind::Resident, actor->id});
receipt->result.terminal = inventory.empty();
for (auto& claim : actor->execution->reservations) {
if (!claim.id) continue;
if (claim.kind == ReservationKind::Item && claim.owner.kind == OwnerKind::Storage) {
auto& store = storage_by_id(claim.owner.id);
stock(store, claim.item)->reserved -= claim.count;
} else if (claim.kind == ReservationKind::Capacity && !claim.backing) {
storage_by_id(claim.owner.id).reserved_slots -= claim.count;
}
claim = {};
}
actor->execution->reservation_count = 0;
actor->execution->kind = TransferKind::Return;
actor->execution->production = 0;
actor->execution->source = 0;
actor->execution->destination = 0;
actor->inventory = inventory;
actor->production_id = 0;
actor->storage_id = 0;
actor->work_remaining = 0;
actor->route.clear();
actor->route_cursor = 0;
actor->haul_route.clear();
actor->state = inventory.empty() ? AgentState::Idle : AgentState::Returning;
commit_custody(*actor, receipt);
if (inventory.empty()) finish_custody(*actor);
}
if (retain) {
it->input = {};
it->materials.clear();
it->delivery_stops.clear();
it->collected_stops = 0;
it->state = JobState::Available;
it->suspended = true;
} else production_orders_.erase(it);
return CommandStatus::Accepted;
}
CommandStatus World::resume_production(ProductionId id) {
auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; });
if (it == production_orders_.end()) return CommandStatus::InvalidTarget;
if (!it->suspended || it->state != JobState::Available) return CommandStatus::Busy;
it->suspended = false;
return CommandStatus::Accepted;
}
void World::advance_return(Agent& agent) {
if (agent.route_cursor < agent.route.size()) return;
agent.route.clear();
agent.route_cursor = 0;
const auto type = agent.inventory.first_item();
if (type == ItemType::None) { agent.state = AgentState::Idle; finish_custody(agent); return; }
for (auto& store : storages_) {
if (!store.accepts(type) || store.total_items() + store.reserved_slots >= store.capacity) continue;
auto path = assignment_path(agent.position, store.position);
if (!path.reachable) continue;
if (!path.positions.empty()) {
agent.route = std::move(path.positions);
agent.execution->blocked = CustodyStatus::Accepted;
return;
}
const auto free = store.capacity - store.total_items() - store.reserved_slots;
const auto count = static_cast<std::uint32_t>(std::min<std::uint64_t>(free, agent.inventory.item_count(type)));
if (!deposit_custody(agent, store, type, count)) return;
if (agent.inventory.empty()) { agent.state = AgentState::Idle; finish_custody(agent); }
return;
}
agent.execution->blocked = CustodyStatus::NoDestination;
}
void World::validate_custody() const {
const auto require = [](bool condition) { if (!condition) throw std::runtime_error("inconsistent custody state"); };
require(next_stack_id_ && next_reservation_id_ && next_transfer_id_);
struct Physical { StockOwner owner; ItemType item; std::uint32_t count; std::uint64_t claimed = 0; };
std::unordered_map<StackId, Physical> physical;
std::unordered_map<StorageId, std::array<std::uint64_t, item_type_count>> reserved;
std::unordered_map<StorageId, std::uint64_t> slots;
std::unordered_map<ResourceNodeId, std::uint64_t> workers;
std::array<std::uint64_t, item_type_count> live{};
const auto add = [&](StockOwner owner, ItemType item, std::uint32_t count, StackId id) {
require((count == 0) == (id == 0));
if (!count) return;
require(item > ItemType::None && item <= ItemType::Loom && id < next_stack_id_);
require(physical.emplace(id, Physical{owner, item, count}).second);
auto& total = live[static_cast<std::size_t>(item) - 1];
const auto amount = Void::Numeric::checked_add(total, std::uint64_t{count});
require(amount.has_value()); total = *amount;
};
const auto add_inventory = [&](const Inventory& inventory, StockOwner owner) {
for (std::size_t i = 1; i <= item_type_count; ++i) {
const auto item = static_cast<ItemType>(i);
add(owner, item, inventory.item_count(item), inventory.stack_id(item));
}
};
for (const auto& store : storages_) {
auto previous = ItemType::None;
for (const auto& stack : store.items) {
require(stack.type > previous && stack.count && store.accepts(stack.type) && stack.reserved <= stack.count);
previous = stack.type;
add({OwnerKind::Storage, store.id}, stack.type, stack.count, stack.id);
}
require(store.total_items() + store.reserved_slots <= store.capacity);
}
for (const auto& actor : agents_) add_inventory(actor.inventory, {OwnerKind::Resident, actor.id});
for (const auto& order : production_orders_) add_inventory(order.input, {OwnerKind::Production, order.id});
std::unordered_map<JobId, const WorkJob*> work_jobs;
std::set<JobId> assigned_jobs;
for (const auto& job : jobs_) require(work_jobs.emplace(job.id, &job).second);
std::unordered_map<AgentId, const Agent*> actors;
std::unordered_map<ProductionId, const Agent*> producers;
for (const auto& actor : agents_) {
require(actors.emplace(actor.id, &actor).second);
if (actor.production_id) require(producers.emplace(actor.production_id, &actor).second);
}
std::set<TransferId> transfers;
std::unordered_map<TransferId, std::uint64_t> active_ordinals;
std::set<ReservationId> reservation_ids;
std::set<ProductionId> work_sites;
std::set<ReservationId> backed;
for (const auto& actor : agents_) {
require(actor.next_admission != 0 && actor.route_cursor <= actor.route.size());
if (!actor.execution) {
require(actor.inventory.empty() && actor.production_id == 0 && actor.resource_node_id == 0 &&
actor.state != AgentState::Returning && actor.state != AgentState::Hauling &&
actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat &&
actor.state != AgentState::Gathering && actor.state != AgentState::FetchingMaterials &&
(actor.state != AgentState::Working || actor.current_job != 0));
require(actor.storage_id == 0 && actor.haul_route.empty());
if (actor.state == AgentState::Working || actor.state == AgentState::Travelling) {
const auto job = work_jobs.find(actor.current_job);
require(job != work_jobs.end() && job->second->state == JobState::InProgress &&
assigned_jobs.insert(actor.current_job).second && actor.work_remaining > 0 && actor.work_remaining <= job->second->work_required);
if (actor.state == AgentState::Working) require(actor.position == job->second->position && actor.route_cursor == actor.route.size());
else require(actor.route_cursor < actor.route.size() && actor.route.back() == job->second->position);
} else require(actor.current_job == 0 && actor.work_remaining == 0 &&
(actor.state == AgentState::Idle || actor.state == AgentState::GoingToSleep || actor.state == AgentState::Sleeping));
continue;
}
const auto& execution = *actor.execution;
require(actor.current_job == 0 && !actor.resting_on_ground);
require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second &&
execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 &&
execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination);
active_ordinals.emplace(execution.id, execution.next_operation);
require(execution.production == actor.production_id && execution.source == actor.resource_node_id);
if (execution.kind == TransferKind::Return) {
require(!actor.inventory.empty() && !actor.production_id && !actor.resource_node_id && actor.work_remaining == 0);
require(actor.haul_route.empty());
require((actor.state == AgentState::Returning && !actor.storage_id && !execution.destination && !execution.reservation_count) ||
(actor.state == AgentState::Hauling && actor.storage_id && find_storage(actor.storage_id) &&
execution.destination == actor.storage_id));
} else if (execution.kind == TransferKind::Meal) {
require(actor.state == AgentState::GoingToEat || actor.state == AgentState::Eating);
require(execution.production == 0 && execution.source == 0 && execution.destination == 0 && actor.haul_route.empty());
if (actor.state == AgentState::GoingToEat) {
const auto* pantry = find_storage(actor.storage_id);
require(pantry && pantry->kind == StorageKind::Pantry && actor.inventory.empty() && actor.work_remaining == 0);
require(actor.route.empty() ? actor.position == pantry->position : actor.route.back() == pantry->position);
} else require(!actor.storage_id && actor.route.empty() && actor.route_cursor == 0);
} else if (execution.kind == TransferKind::Harvest || execution.kind == TransferKind::Tending) {
require(actor.state == AgentState::Travelling || actor.state == AgentState::Gathering || actor.state == AgentState::Hauling);
require(execution.production == 0 && (execution.source != 0) == (actor.state != AgentState::Hauling));
if (execution.kind == TransferKind::Tending) require(actor.state != AgentState::Hauling && !actor.storage_id && !execution.destination && actor.haul_route.empty());
else require(execution.destination != 0 && actor.storage_id == execution.destination);
} else {
require(actor.state == AgentState::Travelling || actor.state == AgentState::Working ||
actor.state == AgentState::FetchingMaterials || actor.state == AgentState::Hauling);
if (execution.production) {
const auto* order = find_production(execution.production);
require(order && !actor.storage_id);
require(is_carpentry_recipe(order->recipe) || actor.haul_route.empty());
}
else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item()));
}
std::array<unsigned, 5> claim_kinds{};
std::array<std::uint64_t, item_type_count> resident_claims{};
for (std::size_t index = 0; index < custody_reservation_limit; ++index) {
const auto& claim = execution.reservations[index];
if (claim.id == 0) { require(claim == Reservation{}); continue; }
require(index < execution.reservation_count && claim.id < next_reservation_id_ &&
reservation_ids.insert(claim.id).second && claim.kind <= ReservationKind::Tending && claim.count);
++claim_kinds[static_cast<std::size_t>(claim.kind)];
if (claim.kind == ReservationKind::Item) {
if (claim.owner.kind == OwnerKind::Resident && claim.item > ItemType::None && claim.item <= ItemType::Loom)
resident_claims[static_cast<std::size_t>(claim.item) - 1] += claim.count;
auto entry = physical.find(claim.stack);
require(entry != physical.end() && entry->second.owner == claim.owner && entry->second.item == claim.item);
require(!claim.backing);
if (claim.origin_storage) require(find_storage(claim.origin_storage) != nullptr);
else require(claim.owner.kind == OwnerKind::Resident &&
(execution.kind == TransferKind::Meal || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling)));
require(claim.owner.kind != OwnerKind::Resident || claim.owner.id == actor.id);
require(claim.owner.kind != OwnerKind::Production || claim.owner.id == actor.production_id);
auto& amount = entry->second.claimed;
require(claim.count <= entry->second.count - amount);
amount += claim.count;
if (claim.owner.kind == OwnerKind::Storage) {
require(claim.owner.id == claim.origin_storage);
reserved[claim.owner.id][static_cast<std::size_t>(claim.item) - 1] += claim.count;
}
} else if (claim.kind == ReservationKind::Capacity) {
require(claim.owner.kind == OwnerKind::Storage && claim.owner.id == execution.destination &&
find_storage(claim.owner.id) && !claim.stack && claim.item == ItemType::None && !claim.origin_storage && claim.count == 1);
if (claim.backing) {
const auto input = std::find_if(execution.reservations.begin(), execution.reservations.end(),
[&](const auto& c) { return c.id == claim.backing; });
require(input != execution.reservations.end() && input->kind == ReservationKind::Item &&
input->owner == claim.owner && input->count >= claim.count && backed.insert(claim.backing).second);
} else slots[claim.owner.id] += claim.count;
} else if (claim.kind == ReservationKind::Worksite) {
require(claim.owner == StockOwner{OwnerKind::Production, execution.production} && execution.production &&
!claim.stack && claim.item == ItemType::None && claim.count == 1 && !claim.backing && !claim.origin_storage);
require(work_sites.insert(execution.production).second);
} else {
require(claim.owner == StockOwner{} && !claim.stack && claim.item == ItemType::None &&
claim.count == 1 && !claim.backing && !claim.origin_storage && execution.source && find_resource_node(execution.source));
workers[execution.source] += claim.count;
require((claim.kind == ReservationKind::Tending) == (execution.kind == TransferKind::Tending));
}
}
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Worksite)] == (execution.production ? 1U : 0U));
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Capacity)] == (execution.destination ? 1U : 0U));
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Harvest)] ==
(execution.kind == TransferKind::Harvest && execution.source ? 1U : 0U));
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Tending)] == (execution.kind == TransferKind::Tending ? 1U : 0U));
if (execution.kind == TransferKind::Harvest || execution.kind == TransferKind::Tending ||
(execution.kind == TransferKind::Production && !execution.production)) require(claim_kinds[0] == 0);
if (execution.kind == TransferKind::Meal) {
require(claim_kinds[0] == 1);
for (const auto& claim : execution.reservations) if (claim.id && claim.kind == ReservationKind::Item) {
require(claim.item == ItemType::Berries && claim.count == 1 && claim.owner ==
(actor.state == AgentState::Eating ? StockOwner{OwnerKind::Resident, actor.id} : StockOwner{OwnerKind::Storage, actor.storage_id}));
}
}
if (actor.state == AgentState::Eating || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling)) {
for (std::size_t i = 0; i < item_type_count; ++i) require(resident_claims[i] == actor.inventory.item_count(static_cast<ItemType>(i + 1)));
}
if (execution.source) {
const auto* node = find_resource_node(execution.source);
require(node && actor.inventory.empty() && (actor.state == AgentState::Gathering || actor.state == AgentState::Travelling));
require(execution.kind != TransferKind::Tending || node->needs_tending());
require(execution.kind != TransferKind::Harvest || (node->quantity && execution.destination && actor.storage_id == execution.destination));
if (actor.state == AgentState::Travelling) require(actor.work_remaining > 0 && actor.route_cursor < actor.route.size() && actor.route.back() == node->position);
else require(actor.position == node->position && actor.route_cursor == actor.route.size());
if (execution.kind == TransferKind::Harvest) {
const auto* destination = find_storage(execution.destination);
require(destination && destination->accepts(node->type));
require(actor.haul_route.empty() ? node->position == destination->position : actor.haul_route.back() == destination->position);
}
}
if (actor.state == AgentState::Hauling && !execution.production) {
require(actor.storage_id == execution.destination && execution.destination && actor.work_remaining == 0);
std::uint64_t carried = 0;
for (std::size_t i = 1; i <= item_type_count; ++i) carried += actor.inventory.item_count(static_cast<ItemType>(i));
require(carried == 1 && actor.haul_route.empty());
const auto cargo = actor.inventory.first_item();
const bool resource = cargo == ItemType::Wood || cargo == ItemType::Stone || cargo == ItemType::Berries || cargo == ItemType::Flax;
require(resource || is_carpentry_item(cargo));
if (execution.kind == TransferKind::Harvest) require(resource);
const auto* destination = find_storage(execution.destination);
require(destination && destination->accepts(cargo));
require(actor.route.empty() ? actor.position == destination->position : actor.route.back() == destination->position);
}
}
for (const auto& store : storages_) {
require(slots[store.id] == store.reserved_slots);
for (const auto& stack : store.items) require(reserved[store.id][static_cast<std::size_t>(stack.type) - 1] == stack.reserved);
}
for (const auto& node : resource_nodes_) require(workers[node.id] == node.reserved_workers);
for (const auto& job : jobs_) require((job.state == JobState::InProgress) == assigned_jobs.contains(job.id));
for (const auto& order : production_orders_) {
require(order.state <= JobState::Completed);
if (order.state == JobState::InProgress) {
require(!order.suspended && work_sites.contains(order.id) && !order.materials.empty());
const auto found_actor = producers.find(order.id);
require(found_actor != producers.end());
const auto actor = found_actor->second;
require(order.materials.size() <= custody_material_limit && order.collected_stops <= order.delivery_stops.size());
const bool delivery = delivers_materials(order.recipe);
const auto destination = is_construction(order.recipe) ? 0 : order.materials.front().storage_id;
require(actor->execution->destination == destination);
if (destination) {
ReservationId backing = 0;
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item &&
claim.owner == StockOwner{OwnerKind::Storage, destination}) { backing = claim.id; break; }
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Capacity) require(claim.backing == backing);
}
require(delivery || order.delivery_stops.empty());
// Delivered recipes never use the generic Travelling transition:
// that transition enters Working without performing any pickup.
if (delivery) {
require(actor->state == AgentState::FetchingMaterials || actor->state == AgentState::Hauling || actor->state == AgentState::Working);
if (actor->state == AgentState::Working) require(order.delivery_stops.empty() && order.collected_stops == 0 && actor->position == order.position);
else {
require(!order.delivery_stops.empty() && actor->work_remaining > 0);
require(actor->state == AgentState::FetchingMaterials ? order.collected_stops == 0 : order.collected_stops > 0);
auto target = order.position;
if (order.collected_stops < order.delivery_stops.size()) {
const auto* store = find_storage(order.delivery_stops[order.collected_stops].storage_id);
require(store != nullptr); target = store->position;
}
require(actor->route.empty() ? actor->position == target : actor->route.back() == target);
}
} else {
require(order.collected_stops == 0 && (actor->state == AgentState::Travelling || actor->state == AgentState::Working));
if (actor->state == AgentState::Travelling) require(actor->work_remaining > 0 && actor->route_cursor < actor->route.size() && actor->route.back() == order.position);
else require(actor->position == order.position);
}
std::array<std::uint64_t, item_type_count> required{}, planned{}, claimed{}, cargo{};
const auto need = [&](ItemType item, std::uint32_t count) { if (count) required[static_cast<std::size_t>(item) - 1] += count; };
if (order.recipe == RecipeId::SawPlank) need(ItemType::Wood, 1);
else if (order.recipe == RecipeId::CutStoneBlock) need(ItemType::Stone, 1);
else if (order.recipe == RecipeId::WeaveCloth) need(ItemType::Flax, 1);
else if (order.recipe == RecipeId::BuildBed) need(order.bed_material(), 1);
else for (const auto& item : is_carpentry_recipe(order.recipe) ? carpentry_materials(order.recipe) :
construction_materials(order.recipe, order.bed_base)) need(item.type, item.count);
StorageId previous_stop = 0;
for (const auto& stop : order.delivery_stops) {
require(stop.storage_id > previous_stop && find_storage(stop.storage_id)); previous_stop = stop.storage_id;
require(std::any_of(order.materials.begin(), order.materials.end(), [&](const auto& m) { return m.storage_id == stop.storage_id; }));
}
for (const auto& line : order.materials) {
require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count && find_storage(line.storage_id));
planned[static_cast<std::size_t>(line.type) - 1] += line.count;
StockOwner expected{OwnerKind::Storage, line.storage_id};
if (delivery) {
if (actor->state == AgentState::Working) expected = {OwnerKind::Production, order.id};
else {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(), [&](const auto& e) { return e.storage_id == line.storage_id; });
require(stop != order.delivery_stops.end());
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) expected = {OwnerKind::Resident, actor->id};
}
}
std::uint64_t line_claims = 0;
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item &&
claim.item == line.type && claim.origin_storage == line.storage_id) { require(claim.owner == expected); line_claims += claim.count; }
require(line_claims == line.count);
if (expected.kind == OwnerKind::Resident) cargo[static_cast<std::size_t>(line.type) - 1] += line.count;
}
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item)
claimed[static_cast<std::size_t>(claim.item) - 1] += claim.count;
require(planned == required && claimed == required);
for (std::size_t i = 0; i < item_type_count; ++i) require(cargo[i] == actor->inventory.item_count(static_cast<ItemType>(i + 1)));
if (actor->state == AgentState::Working) require(actor->route_cursor == actor->route.size() && order.delivery_stops.empty());
if (delivers_materials(order.recipe) && actor->state == AgentState::Working) {
std::array<std::uint32_t, item_type_count> expected{};
for (const auto& line : order.materials) {
require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count);
const auto i = static_cast<std::size_t>(line.type) - 1;
const auto amount = Void::Numeric::checked_add(expected[i], line.count);
require(amount.has_value()); expected[i] = *amount;
}
for (std::size_t i = 0; i < item_type_count; ++i) require(order.input.item_count(static_cast<ItemType>(i + 1)) == expected[i]);
require(actor->inventory.empty());
} else require(order.input.empty());
} else require(order.input.empty() && order.materials.empty() && order.delivery_stops.empty());
if (order.suspended) require(order.state == JobState::Available &&
(order.recipe == RecipeId::WeaveCloth || (order.recipe == RecipeId::BuildBed &&
(order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow))));
}
for (std::size_t i = 0; i < item_type_count; ++i) {
const auto& b = item_balances_[i];
std::uint64_t in = 0, out = live[i];
for (const auto value : {b.opening, b.grant, b.harvest, b.recipe_output}) {
const auto amount = Void::Numeric::checked_add(in, value); require(amount.has_value()); in = *amount;
}
for (const auto value : {b.recipe_input, b.meal, b.installation, b.demolition}) {
const auto amount = Void::Numeric::checked_add(out, value); require(amount.has_value()); out = *amount;
}
require(in == out);
}
require(custody_receipts_.size() <= custody_receipt_limit &&
(custody_receipts_.size() == custody_receipt_limit ? custody_receipt_cursor_ < custody_receipt_limit : custody_receipt_cursor_ == 0));
std::set<std::tuple<CustodyKeyKind, std::uint64_t, std::uint64_t>> keys;
std::map<std::pair<CustodyKeyKind, std::uint64_t>, std::uint64_t> last_ordinals;
TransferId last_admission = 0;
ReservationId last_issued_reservation = 0;
std::set<TransferId> terminal_transfers;
for (std::size_t receipt_index = 0; receipt_index < custody_receipts_.size(); ++receipt_index) {
const auto& receipt = custody_receipts_[(receipt_index + custody_receipt_cursor_) % custody_receipts_.size()];
require(static_cast<bool>(receipt));
const auto& request = receipt->request;
const auto& result = receipt->result;
require(request.key.kind <= CustodyKeyKind::Operation && request.key.id && request.key.ordinal &&
request.kind <= TransferKind::Return && request.operation <= CustodyOperation::Tend &&
request.line_count <= custody_material_limit && request.production < next_production_id_ &&
request.destination < next_storage_id_ && keys.emplace(request.key.kind, request.key.id, request.key.ordinal).second);
auto& last_ordinal = last_ordinals[{request.key.kind, request.key.id}];
require(last_ordinal == 0 || (last_ordinal != maximum && request.key.ordinal == last_ordinal + 1));
last_ordinal = request.key.ordinal;
require(!terminal_transfers.contains(result.transfer));
if (result.terminal) {
require(result.status == CustodyStatus::Accepted && !active_ordinals.contains(result.transfer));
require(request.operation == CustodyOperation::Complete || request.operation == CustodyOperation::Eat ||
request.operation == CustodyOperation::Tend || request.operation == CustodyOperation::Cancel ||
request.operation == CustodyOperation::Return ||
(request.operation == CustodyOperation::Deliver && request.destination != 0));
terminal_transfers.insert(result.transfer);
}
require(request.source < (((request.operation == CustodyOperation::Admit &&
(request.kind == TransferKind::Harvest || request.kind == TransferKind::Tending)) ||
request.operation == CustodyOperation::Harvest || request.operation == CustodyOperation::Tend) ? next_resource_node_id_ : next_storage_id_));
if (request.key.kind == CustodyKeyKind::Admission) {
require(result.transfer > last_admission && !result.terminal);
last_admission = result.transfer;
require(result.status == CustodyStatus::Accepted && request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit);
const auto actor = actors.find(request.key.id);
if (actor != actors.end()) require(request.key.ordinal < actor->second->next_admission);
} else {
require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit && result.transfer == request.key.id);
const auto active = active_ordinals.find(request.key.id);
if (active != active_ordinals.end()) require(request.key.ordinal < active->second);
}
for (std::size_t i = 0; i < custody_material_limit; ++i) {
const auto& line = request.lines[i];
if (i >= request.line_count) require(line == CustodyLine{});
else require(line.storage && line.storage < next_storage_id_ && line.item > ItemType::None && line.item <= ItemType::Loom && line.count);
}
if (request.operation == CustodyOperation::Admit) {
require(result.effect_count == 0);
require(result.reservation_count == request.line_count + static_cast<unsigned>(request.production != 0) +
static_cast<unsigned>(request.source != 0) + static_cast<unsigned>(request.destination != 0));
switch (request.kind) {
case TransferKind::Production: require(request.production && !request.source && request.line_count); break;
case TransferKind::Harvest: require(!request.production && request.source && request.destination && !request.line_count); break;
case TransferKind::Tending: require(!request.production && request.source && !request.destination && !request.line_count); break;
case TransferKind::Meal:
require(!request.production && !request.source && !request.destination && request.line_count == 1 &&
request.lines[0].item == ItemType::Berries && request.lines[0].count == 1); break;
case TransferKind::Return: require(false); break;
}
} else {
switch (request.operation) {
case CustodyOperation::Pickup:
require((request.kind == TransferKind::Production || request.kind == TransferKind::Meal) &&
request.source && !request.destination && !request.line_count &&
(request.production != 0) == (request.kind == TransferKind::Production)); break;
case CustodyOperation::Deliver:
require(!request.source && (request.kind == TransferKind::Production || request.kind == TransferKind::Harvest));
if (request.destination) require(!request.production && request.line_count == 1 && request.lines[0].storage == request.destination);
else require(request.kind == TransferKind::Production && request.production && !request.line_count);
break;
case CustodyOperation::Complete:
case CustodyOperation::Cancel:
require(request.kind == TransferKind::Production && request.production && !request.source && !request.destination && !request.line_count); break;
case CustodyOperation::Return:
require(request.kind == TransferKind::Return && !request.production && !request.source && request.destination &&
request.line_count == 1 && request.lines[0].storage == request.destination); break;
case CustodyOperation::Harvest:
case CustodyOperation::Tend:
require(request.kind == (request.operation == CustodyOperation::Harvest ? TransferKind::Harvest : TransferKind::Tending) &&
!request.production && request.source && !request.destination && !request.line_count); break;
case CustodyOperation::Eat:
require(request.kind == TransferKind::Meal && !request.production && !request.source && !request.destination && !request.line_count); break;
case CustodyOperation::Admit: require(false); break;
}
}
require(result.status <= CustodyStatus::NoDestination && result.transfer && result.transfer < next_transfer_id_ &&
result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count);
// Only admissions issue claims, in allocator order. Check their retained
// history without resolving already released claims to live objects.
require(request.operation == CustodyOperation::Admit || result.reservation_count == 0);
for (std::size_t i = 0; i < custody_reservation_limit; ++i) {
if (i >= result.reservation_count) { require(result.reservations[i] == 0); continue; }
require(result.reservations[i] > last_issued_reservation && result.reservations[i] < next_reservation_id_);
last_issued_reservation = result.reservations[i];
}
for (std::size_t i = 0; i < item_type_count; ++i) {
const auto& effect = result.effects[i];
if (i >= result.effect_count) { require(effect == CustodyEffect{}); continue; }
require(effect.stack && effect.stack < next_stack_id_ && effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.owner.id);
// Effects are final outcomes, not per-material deltas. Distinct
// owners/stack IDs may legitimately share an item type. Zero counts
// describe consumption of a historical stack and remain valid.
for (std::size_t prior = 0; prior < i; ++prior) {
const auto& other = result.effects[prior];
require(effect.owner != other.owner || effect.stack != other.stack || effect.item != other.item);
}
if (effect.owner.kind == OwnerKind::Storage) require(effect.owner.id < next_storage_id_);
else if (effect.owner.kind == OwnerKind::Resident) require(effect.owner.id < next_agent_id_);
else { require(effect.owner.kind == OwnerKind::Production); require(effect.owner.id < next_production_id_); }
}
}
}
} // namespace settlement
+3 -3
View File
@@ -5,9 +5,9 @@
namespace settlement {
std::unique_ptr<World> make_first_colony(std::size_t workers) {
std::unique_ptr<World> make_first_colony(std::size_t workers, BedConstructionMode beds, ExecutionMode mode) {
constexpr auto size = first_colony_map_size;
auto world = std::make_unique<World>(2026, size, size, workers);
auto world = std::make_unique<World>(2026, size, size, workers, mode);
DeterministicRng terrain_rng(0x534554544C454D45ULL);
for (int y = 2; y < size - 2; ++y) {
for (int x = 2; x < size - 2; ++x) {
@@ -28,7 +28,7 @@ std::unique_ptr<World> make_first_colony(std::size_t workers) {
for (const auto position : {GridPosition{13, 14}, {14, 12}, {18, 12}, {19, 14}}) {
static_cast<void>(world->add_resource_node(position, ItemType::Berries, 16));
}
world->start_scenario({15, 14});
world->start_scenario({15, 14}, beds);
return world;
}
+88
View File
@@ -0,0 +1,88 @@
#include "settlement/core/inventory_transaction.hpp"
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
#include <type_traits>
namespace settlement {
// Replace the conditional in-memory batch when Void/Library #8 supplies this
// contract: https://git.faumaray.com/Void/Library/issues/8
std::expected<void, QuantityTransferError> withdraw_reserved_materials(
Storage& source, Inventory& destination, std::span<const MaterialReservation> materials,
bool reserve_output_slot) noexcept {
using Error = QuantityTransferError;
if (source.id == 0 || source.kind > StorageKind::Pantry) return std::unexpected(Error::InvalidStorage);
std::array<std::uint32_t, item_type_count> amounts{};
bool selected = false;
std::uint64_t withdrawn = 0;
for (const auto& material : materials) {
if (material.storage_id != source.id) continue;
const auto type = static_cast<std::size_t>(material.type);
if (type == 0 || type > item_type_count || material.count == 0) {
return std::unexpected(Error::InvalidMaterial);
}
const auto amount = Void::Numeric::checked_add(amounts[type - 1], material.count);
const auto total = Void::Numeric::checked_add(withdrawn, std::uint64_t{material.count});
if (!amount || !total) return std::unexpected(Error::Overflow);
amounts[type - 1] = *amount;
withdrawn = *total;
selected = true;
}
if (!selected) return std::unexpected(Error::MissingSelection);
// Validate the entire source before indexing or changing any stack. Its
// sorted unique representation bounds all subsequent work by item_type_count.
auto previous = ItemType::None;
std::uint64_t total_items = 0;
std::array<bool, item_type_count> present{};
for (const auto& stack : source.items) {
const auto type = static_cast<std::size_t>(stack.type);
if (type == 0 || type > item_type_count || stack.type <= previous ||
!source.accepts(stack.type) || stack.count == 0 || stack.reserved > stack.count) {
return std::unexpected(Error::InvalidStock);
}
previous = stack.type;
present[type - 1] = true;
const auto total = Void::Numeric::checked_add(total_items, std::uint64_t{stack.count});
if (!total) return std::unexpected(Error::Overflow);
total_items = *total;
if (amounts[type - 1] > stack.reserved || amounts[type - 1] > stack.count) {
return std::unexpected(Error::InsufficientStock);
}
}
for (std::size_t i = 0; i < amounts.size(); ++i) {
if (amounts[i] == 0) continue;
if (!present[i]) return std::unexpected(Error::InsufficientStock);
if (!Void::Numeric::checked_add(destination.item_count(static_cast<ItemType>(i + 1)), amounts[i])) {
return std::unexpected(Error::Overflow);
}
}
const auto occupied = Void::Numeric::checked_add(total_items, std::uint64_t{source.reserved_slots});
if (!occupied || source.capacity == 0 || *occupied > source.capacity) return std::unexpected(Error::Capacity);
const auto slots = Void::Numeric::checked_add(source.reserved_slots, std::uint32_t{reserve_output_slot});
if (!slots) return std::unexpected(Error::Overflow);
const auto remaining = Void::Numeric::checked_sub(total_items, withdrawn);
if (!remaining) return std::unexpected(Error::InsufficientStock);
const auto final_occupied = Void::Numeric::checked_add(*remaining, std::uint64_t{*slots});
if (!final_occupied || *final_occupied > source.capacity) return std::unexpected(Error::Capacity);
// All operations after this point are nonthrowing. No stack iterator survives
// compaction, which removes every depleted stack while retaining source order.
static_assert(std::is_nothrow_move_assignable_v<ItemStack> && std::is_nothrow_destructible_v<ItemStack>);
for (auto& stack : source.items) {
const auto amount = amounts[static_cast<std::size_t>(stack.type) - 1];
stack.count -= amount;
stack.reserved -= amount;
if (amount != 0) destination.add(stack.type, amount);
}
std::erase_if(source.items, [](const ItemStack& stack) noexcept { return stack.count == 0; });
source.reserved_slots = *slots;
return {};
}
} // namespace settlement
+4 -1
View File
@@ -386,7 +386,10 @@ std::expected<std::vector<RulePackage>, RulesDiagnostic> builtin_rule_packages()
if (!first) return std::unexpected{first.error()};
auto second = load_rule_package("builtin/colony", colony);
if (!second) return std::unexpected{second.error()};
return std::vector<RulePackage>{std::move(*first), std::move(*second)};
constexpr std::string_view plankbeds = R"({"schema":1,"id":"settlement.plankbeds","version":"1.0.0","dependencies":[{"id":"settlement.colony","version":"1.0.0"}],"exclusive_capabilities":[],"definitions":[{"id":"settlement.plankbeds:bed","kind":"recipe","data":{"assembly":"plank","input":"settlement.colony:board","input_count":1,"saw_work_ticks":12,"work_ticks":14},"references":["settlement.colony:board"]}]})";
auto third = load_rule_package("builtin/plankbeds", plankbeds);
if (!third) return std::unexpected{third.error()};
return std::vector<RulePackage>{std::move(*first), std::move(*second), std::move(*third)};
}
std::expected<RulesManifest, RulesDiagnostic> default_rules_manifest() {
+353 -156
View File
@@ -1,6 +1,8 @@
#include "settlement/core/world.hpp"
#include "settlement/core/inventory_transaction.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
@@ -56,33 +58,33 @@ std::uint16_t initial_hunger(AgentId id) {
}
struct Recipe {
std::array<ItemStack, 2> ingredients;
std::array<ItemAmount, 2> ingredients;
ItemType output;
std::uint32_t ticks;
};
const Recipe& recipe_for(RecipeId id) {
static constexpr Recipe saw{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::Plank, 12};
static constexpr Recipe cut{{ItemStack{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16};
static constexpr Recipe cabin{{ItemStack{ItemType::Plank, 3}, ItemStack{ItemType::StoneBlock, 2}},
static constexpr Recipe saw{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::Plank, 12};
static constexpr Recipe cut{{ItemAmount{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16};
static constexpr Recipe cabin{{ItemAmount{ItemType::Plank, 3}, ItemAmount{ItemType::StoneBlock, 2}},
ItemType::None, 28};
static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14};
static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12};
static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6};
static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9};
static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10};
static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}},
static constexpr Recipe bed{{ItemAmount{ItemType::Plank, 1}, {}}, ItemType::None, 14};
static constexpr Recipe weave{{ItemAmount{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12};
static constexpr Recipe floor{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 6};
static constexpr Recipe wall{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 9};
static constexpr Recipe door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe cabinet{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 10};
static constexpr Recipe mining_rack{{ItemAmount{ItemType::Wood, 1}, ItemAmount{ItemType::Stone, 1}},
ItemType::None, 10};
static constexpr Recipe loom{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8};
static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14};
static constexpr Recipe loom{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe install_door{{ItemAmount{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8};
static constexpr Recipe craft_door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14};
static constexpr Recipe craft_cabinet{cabinet.ingredients, ItemType::MedicineCabinet, 14};
static constexpr Recipe craft_rack{mining_rack.ingredients, ItemType::MiningRack, 14};
static constexpr Recipe craft_loom{loom.ingredients, ItemType::Loom, 16};
static constexpr Recipe install_cabinet{{ItemStack{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8};
static constexpr Recipe install_rack{{ItemStack{ItemType::MiningRack, 1}, {}}, ItemType::None, 8};
static constexpr Recipe install_loom{{ItemStack{ItemType::Loom, 1}, {}}, ItemType::None, 8};
static constexpr Recipe install_cabinet{{ItemAmount{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8};
static constexpr Recipe install_rack{{ItemAmount{ItemType::MiningRack, 1}, {}}, ItemType::None, 8};
static constexpr Recipe install_loom{{ItemAmount{ItemType::Loom, 1}, {}}, ItemType::None, 8};
switch (id) {
case RecipeId::SawPlank: return saw;
case RecipeId::CutStoneBlock: return cut;
@@ -134,6 +136,19 @@ auto stack_position(Storage& storage, ItemType type) {
[](const ItemStack& stack, ItemType target) { return stack.type < target; });
}
template<class Records>
auto record_position(Records& records, std::uint64_t id) {
return std::lower_bound(records.begin(), records.end(), id,
[](const auto& record, std::uint64_t target) { return record.id < target; });
}
template<class Records>
auto& require_record(Records& records, std::uint64_t id) {
const auto found = record_position(records, id);
if (found == records.end() || found->id != id) throw std::logic_error("Missing simulation object ID.");
return *found;
}
std::size_t checked_cell_count(std::int32_t width, std::int32_t height) {
if (width <= 0 || height <= 0 || width > max_map_dimension || height > max_map_dimension) {
throw std::invalid_argument("map dimensions must be in the range 1..512");
@@ -261,6 +276,7 @@ void Inventory::remove(ItemType type, std::uint32_t count) noexcept {
const auto index = static_cast<std::size_t>(type);
assert(index != 0 && index <= counts_.size() && count <= counts_[index - 1]);
counts_[index - 1] -= count;
if (counts_[index - 1] == 0) stack_ids_[index - 1] = 0;
}
ItemType Inventory::first_item() const noexcept {
@@ -298,6 +314,47 @@ std::shared_ptr<const World> World::capture() const {
return std::shared_ptr<const World>(new const World(CaptureTag{}, *this));
}
const Storage* World::find_storage(StorageId id) const noexcept {
const auto found = record_position(storages_, id);
return found == storages_.end() || found->id != id ? nullptr : &*found;
}
const ResourceNode* World::find_resource_node(ResourceNodeId id) const noexcept {
const auto found = record_position(resource_nodes_, id);
return found == resource_nodes_.end() || found->id != id ? nullptr : &*found;
}
const ProductionOrder* World::find_production(ProductionId id) const noexcept {
const auto found = record_position(production_orders_, id);
return found == production_orders_.end() || found->id != id ? nullptr : &*found;
}
ProductionOrder& World::production_by_id(ProductionId id) {
return require_record(production_orders_, id);
}
// Replace with a restorable checked sequence when Void/Library#7 is available:
// https://git.faumaray.com/Void/Library/issues/7
bool World::reserve_production(std::size_t count) {
if (!Void::Numeric::checked_add(next_production_id_, static_cast<std::uint64_t>(count))) return false;
production_orders_.reserve(production_orders_.size() + count);
return true;
}
void World::append_production(ProductionOrder order) {
order.id = next_production_id_;
production_orders_.push_back(std::move(order));
++next_production_id_;
}
Storage& World::storage_by_id(StorageId id) {
return require_record(storages_, id);
}
ResourceNode& World::resource_node_by_id(ResourceNodeId id) {
return require_record(resource_nodes_, id);
}
std::size_t World::cell_index(GridPosition position) const noexcept {
return static_cast<std::size_t>(position.y) * static_cast<std::size_t>(width_) +
static_cast<std::size_t>(position.x);
@@ -349,12 +406,12 @@ void World::set_blocked(GridPosition position, bool blocked) {
}
}
for (const Agent& agent : agents_) {
if (agent.production_index != no_entity_index &&
is_carpentry_recipe(production_orders_[agent.production_index].recipe) &&
if (agent.production_id != 0 &&
is_carpentry_recipe(production_by_id(agent.production_id).recipe) &&
std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) {
throw std::logic_error("cannot block the carpenter's delivery route");
}
if (agent.production_index == no_entity_index &&
if (agent.production_id == 0 &&
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep &&
!is_carpentry_item(agent.inventory.first_item())) continue;
const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor);
@@ -372,12 +429,15 @@ AgentId World::spawn_agent(GridPosition position) {
if (!is_walkable(position)) {
throw std::invalid_argument("agent spawn cell is not walkable");
}
const AgentId id = next_agent_id_++;
const AgentId id = next_agent_id_;
const auto successor = Void::Numeric::checked_add(id, AgentId{1});
if (id == 0 || !successor) throw std::overflow_error("resident identities exhausted");
Agent agent;
agent.id = id;
agent.position = position;
if (hunger_enabled_) agent.hunger = initial_hunger(id);
agents_.push_back(std::move(agent));
next_agent_id_ = *successor;
return id;
}
@@ -388,8 +448,11 @@ JobId World::add_job(GridPosition position, std::uint32_t work_required) {
if (work_required == 0) {
throw std::invalid_argument("work duration must be greater than zero");
}
const JobId id = next_job_id_++;
const JobId id = next_job_id_;
const auto successor = Void::Numeric::checked_add(id, JobId{1});
if (id == 0 || !successor) throw std::overflow_error("job identities exhausted");
jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available});
next_job_id_ = *successor;
return id;
}
@@ -401,9 +464,14 @@ std::uint64_t World::add_resource_node(GridPosition position, ItemType type,
if ((type != ItemType::Wood && type != ItemType::Stone && type != ItemType::Berries) || quantity == 0) {
throw std::invalid_argument("resource node needs wood, stone, or berries and a positive quantity");
}
const std::uint64_t id = next_resource_node_id_++;
// Restorable counters stay with each World. Replacement contract and limits
// are tracked at https://git.faumaray.com/Void/Library/issues/7.
const std::uint64_t id = next_resource_node_id_;
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
if (!successor) throw std::overflow_error("resource node IDs exhausted");
const bool foraging = type != ItemType::Berries || !scenario_active_;
resource_nodes_.push_back(ResourceNode{id, position, type, quantity, quantity, 0, foraging});
next_resource_node_id_ = *successor;
return id;
}
@@ -418,10 +486,12 @@ std::uint64_t World::add_storage(GridPosition position, std::uint32_t capacity,
throw std::invalid_argument("unknown storage kind");
}
const std::uint64_t id = next_storage_id_;
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
if (!successor) throw std::overflow_error("storage IDs exhausted");
Storage storage{id, position, capacity, 0, {}, kind};
storage.items.reserve(kind == StorageKind::Pantry ? 1 : item_type_count - 1);
storages_.push_back(std::move(storage));
++next_storage_id_;
next_storage_id_ = *successor;
return id;
}
@@ -434,8 +504,20 @@ void World::stock_storage(std::uint64_t id, ItemType type, std::uint32_t count)
}
if (count == 0) return;
auto stack = stack_position(*storage, type);
if (stack != storage->items.end() && stack->type == type) stack->count += count;
else storage->items.insert(stack, ItemStack{type, count});
auto& balance = item_balances_[static_cast<std::size_t>(type) - 1];
const auto grant = Void::Numeric::checked_add(balance.grant, std::uint64_t{count});
if (!grant) throw std::overflow_error("stock grant balance exhausted");
if (stack != storage->items.end() && stack->type == type) {
const auto amount = Void::Numeric::checked_add(stack->count, count);
if (!amount) throw std::overflow_error("stock quantity exhausted");
stack->count = *amount;
} else {
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
if (next_stack_id_ == 0 || !next) throw std::overflow_error("stack identities exhausted");
storage->items.insert(stack, ItemStack{type, count, 0, next_stack_id_});
next_stack_id_ = *next;
}
balance.grant = *grant;
}
void World::enable_hunger() noexcept {
@@ -460,10 +542,11 @@ void World::queue_production(GridPosition position, RecipeId recipe) {
throw std::invalid_argument("a building occupies the production site");
}
}
if (!reserve_production(1)) throw ProductionCapacityError{};
ProductionOrder order{};
order.position = position;
order.recipe = recipe;
production_orders_.push_back(std::move(order));
append_production(std::move(order));
}
bool World::can_place_cabin(GridPosition position) const noexcept {
@@ -501,12 +584,12 @@ bool World::can_place_room(const RoomPlan& plan) const noexcept {
});
}
std::array<ItemStack, 2> World::construction_materials(RecipeId recipe, BedBase base) const {
std::array<ItemAmount, 2> World::construction_materials(RecipeId recipe, BedBase base) const {
if (recipe == RecipeId::BuildBed && staged_beds_) {
return {ItemStack{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1},
ItemStack{ItemType::Cloth, 2}};
return {ItemAmount{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1},
ItemAmount{ItemType::Cloth, 2}};
}
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemAmount, 2>{};
}
RecipeId World::room_construction_recipe(RecipeId part) const noexcept {
@@ -520,11 +603,12 @@ RecipeId World::room_construction_recipe(RecipeId part) const noexcept {
return part;
}
std::array<ItemStack, 2> World::carpentry_materials(RecipeId recipe) const {
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
std::array<ItemAmount, 2> World::carpentry_materials(RecipeId recipe) const {
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemAmount, 2>{};
}
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations) const {
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations,
StorageId excluded_storage) const {
const auto craft = recipe_for_carpentry_item(product);
std::uint64_t waiting_installations = new_installations, supply = 0;
for (const auto& order : production_orders_) {
@@ -535,11 +619,12 @@ std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_in
}
}
for (const auto& agent : agents_) {
if (agent.state == AgentState::Hauling && agent.production_index == no_entity_index) {
if (agent.state == AgentState::Hauling && agent.production_id == 0) {
supply += agent.inventory.item_count(product);
}
}
for (const auto& storage : storages_) {
if (storage.id == excluded_storage) continue;
const auto available = storage.available_item_count(product);
if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available;
}
@@ -561,8 +646,9 @@ void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPositio
throw std::invalid_argument("the cabin site is disconnected from the workshops");
}
const Recipe& cabin = recipe_for(RecipeId::BuildCabin);
production_orders_.reserve(production_orders_.size() + 1 +
cabin.ingredients[0].count + cabin.ingredients[1].count);
if (!reserve_production(1 + cabin.ingredients[0].count + cabin.ingredients[1].count)) {
throw ProductionCapacityError{};
}
for (std::uint32_t i = 0; i < cabin.ingredients[0].count; ++i) {
queue_production(sawmill, RecipeId::SawPlank);
}
@@ -572,13 +658,14 @@ void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPositio
queue_production(position, RecipeId::BuildCabin);
}
void World::start_scenario(GridPosition sawmill) {
if (scenario_active_ || !can_place_cabin(sawmill)) {
void World::start_scenario(GridPosition sawmill, BedConstructionMode beds) {
if (scenario_active_ || !can_place_cabin(sawmill) ||
(beds != BedConstructionMode::Staged && beds != BedConstructionMode::Plank)) {
throw std::invalid_argument("scenario needs a free sawmill cell");
}
enable_hunger();
scenario_active_ = true;
staged_beds_ = true;
staged_beds_ = beds == BedConstructionMode::Staged;
scenario_sawmill_ = sawmill;
for (auto& node : resource_nodes_) {
if (node.type == ItemType::Berries) node.foraging_enabled = false;
@@ -628,7 +715,7 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe
[](const auto& item) { return item.reserved != 0; })) return busy;
for (const auto& order : production_orders_) {
if (std::any_of(order.materials.begin(), order.materials.end(),
[i](const auto& material) { return material.storage_index == i; })) return busy;
[&storage](const auto& material) { return material.storage_id == storage.id; })) return busy;
}
return ready;
}
@@ -651,18 +738,13 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
return CommandStatus::InvalidTarget;
}
const auto at_position = [position](const auto& item) { return item.position == position; };
const auto shift_index = [](std::size_t& index, std::size_t removed) {
if (index != no_entity_index && index > removed) --index;
};
const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) {
return is_production_object(entry.recipe) && !is_finished_floor(entry) && at_position(entry);
});
if (order != production_orders_.end()) {
if (destination) order->position = *destination;
else {
const auto removed = static_cast<std::size_t>(order - production_orders_.begin());
production_orders_.erase(order);
for (auto& agent : agents_) shift_index(agent.production_index, removed);
}
return CommandStatus::Accepted;
}
@@ -670,25 +752,31 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
if (storage != storages_.end()) {
if (destination) storage->position = *destination;
else {
std::array<std::uint8_t, std::size(carpentry_products)> lost_products{};
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
lost_products[i] = storage->item_count(carpentry_products[i]) != 0;
}
const auto removed = static_cast<std::size_t>(storage - storages_.begin());
storages_.erase(storage);
for (auto& agent : agents_) shift_index(agent.storage_index, removed);
for (auto& entry : production_orders_) {
for (auto& material : entry.materials) shift_index(material.storage_index, removed);
for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed);
}
std::array<std::size_t, std::size(carpentry_products)> replacements{};
std::size_t total = 0;
if (scenario_active_) {
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
if (!lost_products[i]) continue;
for (std::size_t i = 0; i < replacements.size(); ++i) {
const auto product = carpentry_products[i];
const auto missing = missing_carpentry_orders(product);
for (std::size_t j = 0; j < missing; ++j) {
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
}
if (storage->item_count(product) == 0) continue;
replacements[i] = missing_carpentry_orders(product, 0, storage->id);
total += replacements[i];
}
}
// Demand is evaluated against the post-removal inventory, without
// losing stock or issuing any order until the entire batch fits.
if (!reserve_production(total)) return CommandStatus::Busy;
auto balances = item_balances_;
for (const auto& stack : storage->items) {
auto& sink = balances[static_cast<std::size_t>(stack.type) - 1].demolition;
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{stack.count});
if (!amount) return CommandStatus::Busy;
sink = *amount;
}
item_balances_ = balances;
storages_.erase(storage);
for (std::size_t i = 0; i < replacements.size(); ++i) {
for (std::size_t j = 0; j < replacements[i]; ++j) {
queue_production(scenario_sawmill_, recipe_for_carpentry_item(carpentry_products[i]));
}
}
}
@@ -699,16 +787,12 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
const auto floor = std::find_if(production_orders_.begin(), production_orders_.end(),
[&](const auto& entry) { return is_finished_floor(entry) && at_position(entry); });
if (floor == production_orders_.end() || destination) return CommandStatus::InvalidTarget;
const auto removed = static_cast<std::size_t>(floor - production_orders_.begin());
production_orders_.erase(floor);
for (auto& agent : agents_) shift_index(agent.production_index, removed);
return CommandStatus::Accepted;
}
if (destination) source->position = *destination;
else {
const auto removed = static_cast<std::size_t>(source - resource_nodes_.begin());
resource_nodes_.erase(source);
for (auto& agent : agents_) shift_index(agent.resource_node_index, removed);
}
return CommandStatus::Accepted;
}
@@ -738,12 +822,12 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
!can_place_bed(command.cell) || !find_path(scenario_sawmill_, command.cell).reachable) {
return receipt(CommandStatus::InvalidTarget);
}
if (!reserve_production(staged_beds_ ? 1 : 2)) return receipt(CommandStatus::Busy);
if (staged_beds_) {
queue_production(command.cell, RecipeId::BuildBed);
production_orders_.back().bed_base = static_cast<BedBase>(command.value);
production_orders_.back().bed_stage = BedStage::Foundation;
} else {
production_orders_.reserve(production_orders_.size() + 2);
queue_production(scenario_sawmill_, RecipeId::SawPlank);
queue_production(command.cell, RecipeId::BuildBed);
}
@@ -793,9 +877,11 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
} else if (!can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
const auto successor = Void::Numeric::checked_add(next_resource_node_id_, std::uint64_t{1});
if (!successor) return receipt(CommandStatus::Busy);
resource_nodes_.push_back({next_resource_node_id_, command.cell, site_resource(site), mine ? yield : 0,
yield, 0, true, site});
++next_resource_node_id_;
next_resource_node_id_ = *successor;
if (mine) {
blocked_[cell_index(command.cell)] = 0;
assignment_path_cache_.clear();
@@ -808,19 +894,22 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
}
if (scenario_active_) {
const auto missing = missing_carpentry_orders(ItemType::Loom, 1);
production_orders_.reserve(production_orders_.size() + 1 + missing);
if (!reserve_production(1 + missing)) return receipt(CommandStatus::Busy);
queue_production(command.cell, RecipeId::InstallLoom);
for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftLoom);
} else {
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
queue_production(command.cell, RecipeId::WeaveCloth);
}
break;
case CommandKind::CraftDoor:
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
break;
case CommandKind::CraftFurniture: {
const auto product = static_cast<ItemType>(command.value);
if (!is_carpentry_item(product) || product == ItemType::WoodenDoor) return receipt(CommandStatus::InvalidTarget);
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
break;
}
@@ -837,8 +926,8 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
const auto fixture = furnishings ? room_construction_recipe(furnishings->back().recipe) : RecipeId::BuildFloor;
const auto fixture_item = furnishings ? recipe_for(fixture).ingredients.front().type : ItemType::None;
const auto fixture_orders = furnishings ? missing_carpentry_orders(fixture_item, 1) : 0;
production_orders_.reserve(production_orders_.size() + width * height +
(furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders + fixture_orders);
if (!reserve_production(width * height + (furnishings ? furnishings->size() : 0) +
(legacy_bed ? 1U : 0U) + door_orders + fixture_orders)) return receipt(CommandStatus::Busy);
if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank);
if (furnishings) {
for (const auto& part : *furnishings) {
@@ -847,7 +936,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
order.recipe = room_construction_recipe(part.recipe);
order.bed_base = part.bed_base;
if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation;
production_orders_.push_back(std::move(order));
append_production(std::move(order));
}
}
for (int y = plan.first.y; y <= plan.last.y; ++y) {
@@ -856,7 +945,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
ProductionOrder order{};
order.position = cell;
order.recipe = room_construction_recipe(plan.recipe_at(cell));
production_orders_.push_back(std::move(order));
append_production(std::move(order));
}
}
for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
@@ -870,6 +959,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
if (!Void::Numeric::checked_add(next_storage_id_, std::uint64_t{1})) return receipt(CommandStatus::Busy);
static_cast<void>(add_storage(command.cell, 18, static_cast<StorageKind>(command.value)));
break;
case CommandKind::MoveObject:
@@ -1242,9 +1332,10 @@ void World::assign_resource_tasks(ResourceFocus focus) {
}
if (node.needs_tending()) {
if (!admit_custody(agent, TransferKind::Tending, 0, node.id, 0, {})) break;
++resource_nodes_[node_index].reserved_workers;
--untended_sites;
agent.resource_node_index = node_index;
agent.resource_node_id = node.id;
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
agent.work_remaining = tending_ticks;
@@ -1278,15 +1369,16 @@ void World::assign_resource_tasks(ResourceFocus focus) {
continue;
}
++resource_nodes_[node_index].reserved_workers;
Storage& storage = storages_[storage_index];
if (!admit_custody(agent, TransferKind::Harvest, 0, node.id, storage.id, {})) break;
++resource_nodes_[node_index].reserved_workers;
++storage.reserved_slots;
if (!has_space(storage)) {
if (storage.kind == StorageKind::Pantry) --open_pantry_count;
else --open_material_store_count;
}
agent.resource_node_index = node_index;
agent.storage_index = storage_index;
agent.resource_node_id = node.id;
agent.storage_id = storage.id;
agent.haul_route = std::move(path_to_storage.positions);
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
@@ -1306,7 +1398,7 @@ void World::assign_production_tasks(bool weaving) {
})) return;
for (std::size_t index = 0; index < production_orders_.size(); ++index) {
ProductionOrder& order = production_orders_[index];
if (order.state != JobState::Available || (order.recipe == RecipeId::WeaveCloth) != weaving) continue;
if (order.suspended || order.state != JobState::Available || (order.recipe == RecipeId::WeaveCloth) != weaving) continue;
const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(),
[&order](const ProductionOrder& other) {
@@ -1324,7 +1416,7 @@ void World::assign_production_tasks(bool weaving) {
std::vector<Access> storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown);
std::vector<MaterialReservation> materials;
bool supplied = true;
for (const ItemStack& ingredient : recipe.ingredients) {
for (const ItemAmount& ingredient : recipe.ingredients) {
std::uint32_t remaining = ingredient.count;
for (std::size_t storage_index = 0; storage_index < storages_.size() && remaining > 0;
++storage_index) {
@@ -1341,7 +1433,7 @@ void World::assign_production_tasks(bool weaving) {
}
if (access == Access::Unreachable) continue;
}
materials.push_back({storage_index, ingredient.type, count});
materials.push_back({storage.id, ingredient.type, count});
remaining -= count;
}
if (remaining != 0) {
@@ -1354,12 +1446,12 @@ void World::assign_production_tasks(bool weaving) {
std::vector<ConstructionStop> stops;
if (deliver_ingredients) {
for (std::size_t s = 0; s < storage_access.size(); ++s) {
if (storage_access[s] == Access::Reachable) stops.push_back({s, {}});
if (storage_access[s] == Access::Reachable) stops.push_back({storages_[s].id, {}});
}
for (std::size_t i = 0; i < stops.size(); ++i) {
const auto from = storages_[stops[i].storage_index].position;
const auto from = storage_by_id(stops[i].storage_id).position;
const auto to = i + 1 == stops.size()
? order.position : storages_[stops[i + 1].storage_index].position;
? order.position : storage_by_id(stops[i + 1].storage_id).position;
auto path = assignment_path(from, to);
// Each stop can reach the site on the same undirected map.
assert(path.reachable);
@@ -1367,7 +1459,7 @@ void World::assign_production_tasks(bool weaving) {
}
}
const GridPosition destination = deliver_ingredients
? storages_[stops.front().storage_index].position : order.position;
? storage_by_id(stops.front().storage_id).position : order.position;
for (Agent& agent : agents_) {
const bool can_craft = agent.profession == Profession::Carpenter;
const bool eligible = carpentry ? can_craft :
@@ -1375,17 +1467,20 @@ void World::assign_production_tasks(bool weaving) {
if (agent.state != AgentState::Idle || !eligible) continue;
auto path = assignment_path(agent.position, destination);
if (!path.reachable) continue;
std::vector<GridPosition> haul_route;
if (carpentry) {
agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions;
haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions;
}
const auto output_storage = recipe.output == ItemType::None ? 0 : materials.front().storage_id;
if (!admit_custody(agent, TransferKind::Production, order.id, 0, output_storage, materials)) break;
if (carpentry) agent.haul_route = std::move(haul_route);
for (const auto& material : materials) {
stack_position(storages_[material.storage_index], material.type)->reserved += material.count;
stack_position(storage_by_id(material.storage_id), material.type)->reserved += material.count;
}
order.materials = std::move(materials);
order.delivery_stops = std::move(stops);
order.state = JobState::InProgress;
agent.production_index = index;
agent.production_id = order.id;
agent.route = std::move(path.positions);
agent.route_cursor = 0;
agent.work_remaining = recipe.ticks;
@@ -1396,19 +1491,6 @@ void World::assign_production_tasks(bool weaving) {
}
}
namespace {
void take_reserved_material(Storage& storage, const MaterialReservation& material) {
auto stack = stack_position(storage, material.type);
assert(stack != storage.items.end() && stack->type == material.type);
assert(stack->reserved >= material.count && stack->count >= stack->reserved);
stack->reserved -= material.count;
stack->count -= material.count;
if (stack->count == 0) storage.items.erase(stack);
}
} // namespace
void World::assign_meals() {
for (Agent& agent : agents_) {
if (agent.hunger < max_hunger) ++agent.hunger;
@@ -1434,9 +1516,11 @@ void World::assign_meals() {
auto path = assignment_path(agent.position, storage.position);
if (!path.reachable) continue;
const std::vector meal{MaterialReservation{storage.id, ItemType::Berries, 1}};
if (!admit_custody(agent, TransferKind::Meal, 0, 0, 0, meal)) break;
auto stack = stack_position(storage, ItemType::Berries);
++stack->reserved;
agent.storage_index = *pantry;
agent.storage_id = storage.id;
agent.state = AgentState::GoingToEat;
agent.route = std::move(path.positions);
agent.route_cursor = 0;
@@ -1449,17 +1533,35 @@ void World::assign_meals() {
void World::finish_meal_step(Agent& agent) {
if (agent.state == AgentState::GoingToEat) {
if (agent.route_cursor != agent.route.size()) return;
take_reserved_material(storages_[agent.storage_index], {agent.storage_index, ItemType::Berries, 1});
agent.inventory.add(ItemType::Berries);
agent.storage_index = no_entity_index;
const std::vector meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}};
if (!pickup_custody(agent, storage_by_id(agent.storage_id), meal, false)) {
if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved meal pickup");
return;
}
agent.storage_id = 0;
agent.route.clear();
agent.route_cursor = 0;
agent.work_remaining = meal_ticks;
agent.state = AgentState::Eating;
return;
}
if (--agent.work_remaining != 0) return;
if (agent.work_remaining > 0) --agent.work_remaining;
if (agent.work_remaining != 0) return;
auto& sink = item_balances_[static_cast<std::size_t>(ItemType::Berries) - 1].meal;
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{1});
const auto meals = Void::Numeric::checked_add(meals_eaten_, std::uint64_t{1});
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Eat,
amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow));
if (!receipt) return;
receipt->result.terminal = amount && meals;
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, agent.inventory.stack_id(ItemType::Berries), ItemType::Berries,
amount && meals ? 0U : 1U};
receipt->result.effect_count = 1;
commit_custody(agent, receipt);
if (!amount || !meals) return;
sink = *amount;
agent.inventory.remove(ItemType::Berries);
finish_custody(agent);
agent.hunger = 0;
agent.state = AgentState::Idle;
++meals_eaten_;
@@ -1518,11 +1620,9 @@ void World::finish_rest_step(Agent& agent) {
}
void World::advance_construction_delivery(Agent& agent) {
ProductionOrder& order = production_orders_[agent.production_index];
ProductionOrder& order = production_by_id(agent.production_id);
if (order.collected_stops == order.delivery_stops.size()) {
for (const auto& material : order.materials) {
agent.inventory.remove(material.type, material.count);
}
if (!deliver_custody(agent, order.input, {OwnerKind::Production, order.id})) return;
order.delivery_stops.clear();
order.collected_stops = 0;
agent.state = AgentState::Working;
@@ -1531,16 +1631,15 @@ void World::advance_construction_delivery(Agent& agent) {
return;
}
auto& stop = order.delivery_stops[order.collected_stops];
for (const auto& material : order.materials) {
if (material.storage_index == stop.storage_index) {
take_reserved_material(storages_[stop.storage_index], material);
agent.inventory.add(material.type, material.count);
}
if (order.collected_stops > order.delivery_stops.size() || order.materials.empty()) {
throw std::logic_error("invalid construction pickup stop");
}
if (is_carpentry_recipe(order.recipe) && stop.storage_index == order.materials.front().storage_index) {
// Collecting the first ingredient frees a slot for the finished item.
++storages_[stop.storage_index].reserved_slots;
auto& stop = order.delivery_stops[order.collected_stops];
const bool reserve_output = is_carpentry_recipe(order.recipe) &&
stop.storage_id == order.materials.front().storage_id;
if (!pickup_custody(agent, storage_by_id(stop.storage_id), order.materials, reserve_output)) {
if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved construction pickup");
return;
}
++order.collected_stops;
agent.route = std::move(stop.route_to_next);
@@ -1549,28 +1648,103 @@ void World::advance_construction_delivery(Agent& agent) {
}
void World::finish_production(Agent& agent) {
ProductionOrder& order = production_orders_[agent.production_index];
ProductionOrder& order = production_by_id(agent.production_id);
const Recipe recipe = recipe_for(order);
assert(!order.materials.empty());
if (is_carpentry_recipe(order.recipe)) {
agent.inventory.add(recipe.output);
agent.storage_index = order.materials.front().storage_index;
auto balances = item_balances_;
auto input = order.input;
auto inventory = agent.inventory;
auto next = next_stack_id_;
std::vector<Storage> stores;
const bool delivered = delivers_materials(order.recipe);
const bool carpentry = is_carpentry_recipe(order.recipe);
auto status = CustodyStatus::Accepted;
for (const auto& material : order.materials) {
auto& balance = balances[static_cast<std::size_t>(material.type) - 1];
auto& sink = recipe.output == ItemType::None ? balance.installation : balance.recipe_input;
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{material.count});
if (!amount) { status = CustodyStatus::Overflow; break; }
sink = *amount;
if (delivered) {
if (input.item_count(material.type) < material.count) { status = CustodyStatus::Invalid; break; }
input.remove(material.type, material.count);
} else {
auto store = std::find_if(stores.begin(), stores.end(), [&](const auto& s) { return s.id == material.storage_id; });
if (store == stores.end()) { stores.push_back(storage_by_id(material.storage_id)); store = std::prev(stores.end()); }
const auto stack = stack_position(*store, material.type);
if (stack == store->items.end() || stack->type != material.type || stack->reserved < material.count || stack->count < material.count) {
status = CustodyStatus::Invalid; break;
}
stack->count -= material.count;
stack->reserved -= material.count;
if (stack->count == 0) store->items.erase(stack);
}
}
StackId output_id = 0;
if (status == CustodyStatus::Accepted && recipe.output != ItemType::None) {
auto& balance = balances[static_cast<std::size_t>(recipe.output) - 1].recipe_output;
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
if (!amount) status = CustodyStatus::Overflow;
else balance = *amount;
if (carpentry) {
if (next == 0 || next == std::numeric_limits<StackId>::max()) status = CustodyStatus::Exhausted;
else { output_id = next++; inventory.add(recipe.output); inventory.set_stack_id(recipe.output, output_id); }
} else {
auto& store = stores.front();
auto stack = stack_position(store, recipe.output);
if (stack != store.items.end() && stack->type == recipe.output) { ++stack->count; output_id = stack->id; }
else if (next == 0 || next == std::numeric_limits<StackId>::max()) status = CustodyStatus::Exhausted;
else { output_id = next++; store.items.insert(stack, {recipe.output, 1, 0, output_id}); }
}
}
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Complete, status));
if (!receipt) return;
if (status == CustodyStatus::Accepted) {
receipt->result.terminal = !carpentry;
for (const auto& material : order.materials) {
const auto& original_store = storage_by_id(material.storage_id);
StackId consumed_id = 0;
std::uint32_t remaining = 0;
StockOwner owner{OwnerKind::Production, order.id};
if (delivered) { consumed_id = order.input.stack_id(material.type); remaining = input.item_count(material.type); }
else {
owner = {OwnerKind::Storage, material.storage_id};
for (const auto& stack : original_store.items) if (stack.type == material.type) consumed_id = stack.id;
for (const auto& store : stores) if (store.id == material.storage_id) remaining = store.item_count(material.type);
}
// Several source lines can have merged into one physical site stack.
// Record its final outcome once, retaining the first material order.
const auto end = receipt->result.effects.begin() + receipt->result.effect_count;
const bool recorded = std::any_of(receipt->result.effects.begin(), end, [&](const auto& effect) {
return effect.owner == owner && effect.stack == consumed_id && effect.item == material.type;
});
if (!recorded) receipt->result.effects[receipt->result.effect_count++] = {owner, consumed_id, material.type, remaining};
}
if (output_id) {
receipt->result.effects[receipt->result.effect_count++] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} :
StockOwner{OwnerKind::Storage, stores.front().id}, output_id, recipe.output,
carpentry ? inventory.item_count(recipe.output) : stores.front().item_count(recipe.output)};
}
}
commit_custody(agent, receipt);
if (status != CustodyStatus::Accepted) return;
for (auto& store : stores) storage_by_id(store.id).items.swap(store.items);
item_balances_ = balances;
next_stack_id_ = next;
order.input = input;
agent.inventory = inventory;
for (auto& claim : agent.execution->reservations) if (claim.kind != ReservationKind::Capacity) claim = {};
if (carpentry) {
agent.storage_id = order.materials.front().storage_id;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
agent.production_index = no_entity_index;
agent.production_id = 0;
agent.execution->production = 0;
agent.state = AgentState::Hauling;
order.materials.clear();
order.state = JobState::Completed;
return;
}
if (recipe.output != ItemType::None) {
for (const auto& material : order.materials) {
take_reserved_material(storages_[material.storage_index], material);
}
// Crafting replaces one raw item with one finished item in the same store.
storages_[order.materials.front().storage_index].add_item(recipe.output);
}
order.materials.clear();
if (order.recipe == RecipeId::BuildBed &&
(order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) {
@@ -1581,13 +1755,12 @@ void World::finish_production(Agent& agent) {
order.state = JobState::Available;
} else if (order.recipe == RecipeId::WeaveCloth) {
order.state = JobState::Available;
} else {
order.state = JobState::Completed;
}
agent.production_index = no_entity_index;
} else order.state = JobState::Completed;
agent.production_id = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
finish_custody(agent);
}
void World::grow_sites() {
@@ -1644,11 +1817,11 @@ void World::step(TickProfile* profile) {
Agent& agent = agents_[index];
if ((agent.state == AgentState::Travelling || agent.state == AgentState::Hauling ||
agent.state == AgentState::FetchingMaterials || agent.state == AgentState::GoingToEat ||
agent.state == AgentState::GoingToSleep) &&
agent.state == AgentState::GoingToSleep || agent.state == AgentState::Returning) &&
agent.route_cursor < agent.route.size()) {
agent.position = agent.route[agent.route_cursor++];
if (agent.state == AgentState::Travelling && agent.route_cursor == agent.route.size()) {
agent.state = agent.resource_node_index == no_entity_index
agent.state = agent.resource_node_id == 0
? AgentState::Working : AgentState::Gathering;
}
}
@@ -1660,7 +1833,7 @@ void World::step(TickProfile* profile) {
if (agent.state != AgentState::Working) continue;
if (agent.work_remaining > 0 && can_work(agent)) --agent.work_remaining;
if (agent.work_remaining != 0) continue;
if (agent.production_index != no_entity_index) continue;
if (agent.production_id != 0) continue;
const auto job = std::lower_bound(
jobs_.begin(), jobs_.end(), agent.current_job,
@@ -1699,6 +1872,7 @@ void World::step(TickProfile* profile) {
}
for (Agent& agent : agents_) {
if (agent.state == AgentState::Returning) { advance_return(agent); continue; }
if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) {
finish_meal_step(agent);
continue;
@@ -1707,31 +1881,55 @@ void World::step(TickProfile* profile) {
finish_rest_step(agent);
continue;
}
if (agent.production_index != no_entity_index && agent.route_cursor == agent.route.size() &&
if (agent.production_id != 0 && agent.route_cursor == agent.route.size() &&
(agent.state == AgentState::FetchingMaterials || agent.state == AgentState::Hauling)) {
advance_construction_delivery(agent);
continue;
}
if (agent.state == AgentState::Working && agent.production_index != no_entity_index &&
if (agent.state == AgentState::Working && agent.production_id != 0 &&
agent.work_remaining == 0) {
finish_production(agent);
}
if (agent.state == AgentState::Gathering) {
if (agent.work_remaining == 0 && agent.resource_node_index < resource_nodes_.size()) {
ResourceNode& node = resource_nodes_[agent.resource_node_index];
if (agent.storage_index == no_entity_index) {
node.growth_at = tick_ + growing_time(node.site);
if (agent.work_remaining == 0 && agent.resource_node_id != 0) {
ResourceNode& node = resource_node_by_id(agent.resource_node_id);
if (agent.storage_id == 0) {
const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site));
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow, node.id));
if (!receipt) continue;
receipt->result.terminal = growth.has_value();
commit_custody(agent, receipt);
if (!growth) continue;
node.growth_at = *growth;
finish_custody(agent);
--node.reserved_workers;
agent.resource_node_index = no_entity_index;
agent.resource_node_id = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
continue;
}
if (node.quantity > 0) --node.quantity;
if (node.reserved_workers > 0) --node.reserved_workers;
auto& balance = item_balances_[static_cast<std::size_t>(node.type) - 1].harvest;
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Harvest,
!next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted, node.id));
if (!receipt) continue;
if (next && amount) {
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, next_stack_id_, node.type, 1};
receipt->result.effect_count = 1;
}
commit_custody(agent, receipt);
if (!next || !amount) continue;
--node.quantity;
--node.reserved_workers;
balance = *amount;
agent.inventory.add(node.type);
agent.resource_node_index = no_entity_index;
agent.inventory.set_stack_id(node.type, next_stack_id_);
next_stack_id_ = *next;
for (auto& claim : agent.execution->reservations) if (claim.kind == ReservationKind::Harvest) claim = {};
agent.execution->source = 0;
agent.resource_node_id = 0;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
@@ -1740,13 +1938,12 @@ void World::step(TickProfile* profile) {
}
if (agent.state == AgentState::Hauling && agent.route_cursor == agent.route.size() &&
agent.storage_index < storages_.size()) {
Storage& storage = storages_[agent.storage_index];
agent.storage_id != 0) {
Storage& storage = storage_by_id(agent.storage_id);
const ItemType cargo = agent.inventory.first_item();
if (storage.reserved_slots > 0) --storage.reserved_slots;
storage.add_item(cargo);
agent.inventory.remove(cargo);
agent.storage_index = no_entity_index;
if (!deposit_custody(agent, storage, cargo, 1)) continue;
finish_custody(agent);
agent.storage_id = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
+475 -48
View File
@@ -18,10 +18,20 @@ namespace settlement {
namespace {
constexpr std::string_view signature = "SETTLERS";
constexpr std::uint32_t save_version = 13;
constexpr std::uint32_t save_version = 15;
constexpr std::uint32_t last_legacy_footer_version = 8;
constexpr std::size_t max_records = 1'000'000;
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
// The wire limit is independent of decoded C++ layout: an old byte-light agent
// now includes an execution/claim array. Cover every bounded top-level pool,
// nested vectors (maximum element expansion <4x wire), and the receipt ring.
// This is an accounting ceiling, never a reserve() request from untrusted input.
constexpr std::size_t record_pool_bytes = sizeof(Agent) + sizeof(WorkJob) +
sizeof(ResourceNode) + sizeof(Storage) + sizeof(ProductionOrder);
static_assert(record_pool_bytes <= (std::numeric_limits<std::size_t>::max() -
4 * max_save_bytes - custody_receipt_limit * (sizeof(CustodyReceipt) + 32)) / max_records);
constexpr std::size_t max_decode_allocation_bytes = max_records * record_pool_bytes +
4 * max_save_bytes + custody_receipt_limit * (sizeof(CustodyReceipt) + 32);
void require_save(bool condition, const char* error) {
if (!condition) throw std::runtime_error(error);
@@ -86,6 +96,11 @@ public:
}
}
void allocate(std::size_t count, std::size_t size) {
require_save(count <= max_decode_allocation_bytes / size &&
allocations_.consume_field(count * size).has_value(), "Save allocation budget exceeded.");
}
void set_version(std::uint32_t version) {
legacy_footer_ = version <= last_legacy_footer_version;
}
@@ -104,6 +119,7 @@ private:
std::istream& stream_;
std::size_t bytes_ = 0;
// Legacy footers cover the signature and version, which are read first.
Void::Binary::DecodeBudget allocations_{{max_decode_allocation_bytes, max_decode_allocation_bytes, 64}};
bool legacy_footer_ = true;
std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis;
};
@@ -115,6 +131,7 @@ void sequence(Archive& archive, Vector& values, std::size_t limit, Visit visit)
archive.field(length);
require_save(length <= limit, "Save contains too many records.");
if constexpr (Archive::reading) {
archive.allocate(length, sizeof(typename Vector::value_type));
for (std::uint32_t i = 0; i < length; ++i) {
values.emplace_back();
visit(values.back());
@@ -146,6 +163,41 @@ void index(Archive& archive, Index& value) {
}
}
template<class Records>
std::size_t record_index(const Records& records, std::uint64_t id) {
const auto found = std::lower_bound(records.begin(), records.end(), id,
[](const auto& record, std::uint64_t target) { return record.id < target; });
require_save(found != records.end() && found->id == id, "Save contains an invalid object reference.");
return static_cast<std::size_t>(found - records.begin());
}
template<class Records>
std::uint64_t reference_id(const Records& records, std::size_t position) {
if (position == no_entity_index) return 0;
require_save(position < records.size(), "Save contains an invalid object index.");
return records[position].id;
}
template<class Records>
void validate_reference_pool(const Records& records, std::uint64_t next_id) {
std::uint64_t previous = 0;
for (const auto& record : records) {
require_save(record.id > previous, "Save contains unordered object IDs.");
previous = record.id;
}
require_save(next_id > previous, "Save contains an invalid next object ID.");
}
template<class Archive, class Id, class Records>
void reference(Archive& archive, Id& id, const Records& records) {
std::size_t position = no_entity_index;
if constexpr (!Archive::reading) {
if (id != 0) position = record_index(records, id);
}
index(archive, position);
if constexpr (Archive::reading) id = reference_id(records, position);
}
template<class Archive, class Size>
void offset(Archive& archive, Size& value) {
auto wire = static_cast<std::uint64_t>(value);
@@ -196,9 +248,13 @@ struct WorldSaveCodec {
archive.field(world.next_job_id_);
archive.field(world.next_resource_node_id_);
archive.field(world.next_storage_id_);
if (version >= 14) archive.field(world.next_production_id_);
const auto cells = world.blocked_.size();
for (auto& cell : world.blocked_) archive.field(cell);
// Agent links precede their pools in legacy saves. Raw positions stay
// loader-owned until the complete, ID-ordered pools are available.
std::vector<std::array<std::size_t, 3>> agent_links;
sequence(archive, world.agents_, max_records, [&](auto& agent) {
archive.field(agent.id);
position(archive, agent.position);
@@ -207,8 +263,18 @@ struct WorldSaveCodec {
route(archive, agent.route, cells);
offset(archive, agent.route_cursor);
archive.field(agent.work_remaining);
index(archive, agent.resource_node_index);
index(archive, agent.storage_index);
if (version >= 14) {
archive.field(agent.resource_node_id);
archive.field(agent.storage_id);
} else if constexpr (Archive::reading) {
std::array<std::size_t, 3> links{no_entity_index, no_entity_index, no_entity_index};
index(archive, links[0]);
index(archive, links[1]);
agent_links.push_back(links);
} else {
reference(archive, agent.resource_node_id, world.resource_nodes_);
reference(archive, agent.storage_id, world.storages_);
}
const auto inventory_types = version >= 3 ? max_item_count : static_cast<std::size_t>(ItemType::Berries);
for (std::size_t i = 1; i <= inventory_types; ++i) {
const auto type = static_cast<ItemType>(i);
@@ -219,7 +285,9 @@ struct WorldSaveCodec {
}
}
route(archive, agent.haul_route, cells);
index(archive, agent.production_index);
if (version >= 14) archive.field(agent.production_id);
else if constexpr (Archive::reading) index(archive, agent_links.back()[2]);
else reference(archive, agent.production_id, world.production_orders_);
archive.field(agent.hunger);
if (version >= 4) archive.field(agent.fatigue);
if (version >= 5) flag(archive, agent.resting_on_ground);
@@ -261,7 +329,17 @@ struct WorldSaveCodec {
storage.items.reserve(storage.kind == StorageKind::Pantry ? 1 : item_types - 1);
}
});
if constexpr (Archive::reading) {
validate_reference_pool(world.resource_nodes_, world.next_resource_node_id_);
validate_reference_pool(world.storages_, world.next_storage_id_);
for (std::size_t i = 0; i < agent_links.size(); ++i) {
world.agents_[i].resource_node_id = reference_id(world.resource_nodes_, agent_links[i][0]);
world.agents_[i].storage_id = reference_id(world.storages_, agent_links[i][1]);
}
}
sequence(archive, world.production_orders_, max_records, [&](auto& order) {
if (version >= 14) archive.field(order.id);
else if constexpr (Archive::reading) order.id = world.production_orders_.size();
position(archive, order.position);
archive.field(order.recipe);
require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version.");
@@ -272,13 +350,15 @@ struct WorldSaveCodec {
require_save(version >= 13 || order.recipe <= RecipeId::CraftWoodenDoor, "Unknown recipe for save version.");
archive.field(order.state);
sequence(archive, order.materials, item_types, [&](auto& material) {
index(archive, material.storage_index);
if (version >= 14) archive.field(material.storage_id);
else reference(archive, material.storage_id, world.storages_);
archive.field(material.type);
require_save(material.type <= max_item, "Unknown material for save version.");
archive.field(material.count);
});
sequence(archive, order.delivery_stops, item_types, [&](auto& stop) {
index(archive, stop.storage_index);
if (version >= 14) archive.field(stop.storage_id);
else reference(archive, stop.storage_id, world.storages_);
route(archive, stop.route_to_next, cells);
});
offset(archive, order.collected_stops);
@@ -288,6 +368,14 @@ struct WorldSaveCodec {
archive.field(order.bed_stage);
}
});
if constexpr (Archive::reading) {
if (version < 14) {
world.next_production_id_ = world.production_orders_.size() + 1;
for (std::size_t i = 0; i < agent_links.size(); ++i) {
world.agents_[i].production_id = reference_id(world.production_orders_, agent_links[i][2]);
}
}
}
if (version >= 2) {
flag(archive, world.scenario_active_);
flag(archive, world.paused_);
@@ -300,10 +388,192 @@ struct WorldSaveCodec {
}
}
static void validate(const World& world);
template<class Archive, class State>
static void custody(Archive& archive, State& world);
static void validate(const World& world, bool modern = false);
};
void WorldSaveCodec::validate(const World& world) {
namespace {
template<class Archive, class Owner>
void owner_fields(Archive& archive, Owner& owner) {
archive.field(owner.kind);
archive.field(owner.id);
require_save(owner.kind <= OwnerKind::Production, "Unknown custody owner.");
require_save((owner.kind == OwnerKind::None) == (owner.id == 0), "Invalid custody owner identity.");
}
template<class Archive, class Claim>
void claim_fields(Archive& archive, Claim& claim) {
archive.field(claim.id);
archive.field(claim.kind);
owner_fields(archive, claim.owner);
archive.field(claim.stack);
archive.field(claim.item);
archive.field(claim.count);
archive.field(claim.backing);
archive.field(claim.origin_storage);
require_save(claim.kind <= ReservationKind::Tending && claim.item <= ItemType::Loom,
"Unknown reservation kind or item.");
require_save(claim.id != 0 || claim == Reservation{}, "Noncanonical released reservation.");
}
template<class Archive, class Request>
void request_fields(Archive& archive, Request& request) {
// These are exact tagged little-endian fields, never an object image or hash.
std::uint16_t size = static_cast<std::uint16_t>(44 + 13 * request.line_count);
archive.field(size);
require_save(size <= 1024, "Custody request exceeds 1024 bytes.");
archive.field(request.key.kind);
archive.field(request.key.id);
archive.field(request.key.ordinal);
archive.field(request.operation);
archive.field(request.kind);
archive.field(request.production);
archive.field(request.source);
archive.field(request.destination);
archive.field(request.line_count);
require_save(request.line_count <= custody_material_limit && size == 44 + 13 * request.line_count,
"Noncanonical custody request length.");
require_save(request.key.kind <= CustodyKeyKind::Operation && request.operation <= CustodyOperation::Tend &&
request.kind <= TransferKind::Return && request.key.id != 0 && request.key.ordinal != 0 &&
((request.key.kind == CustodyKeyKind::Admission) == (request.operation == CustodyOperation::Admit)),
"Invalid custody request tag or key.");
for (std::size_t i = 0; i < request.line_count; ++i) {
auto& line = request.lines[i];
archive.field(line.storage);
archive.field(line.item);
archive.field(line.count);
require_save(line.storage != 0 && line.item > ItemType::None && line.item <= ItemType::Loom && line.count != 0,
"Invalid custody request line.");
}
for (std::size_t i = request.line_count; i < request.lines.size(); ++i) {
require_save(request.lines[i] == CustodyLine{}, "Noncanonical unused request line.");
}
}
template<class Archive, class Result>
void result_fields(Archive& archive, Result& result) {
std::uint16_t size = static_cast<std::uint16_t>(12 + 8 * result.reservation_count + 22 * result.effect_count);
archive.field(size);
require_save(size <= 1024, "Custody result exceeds 1024 bytes.");
archive.field(result.status);
archive.field(result.transfer);
archive.field(result.reservation_count);
archive.field(result.effect_count);
flag(archive, result.terminal);
require_save(result.status <= CustodyStatus::NoDestination &&
result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count &&
size == 12 + 8 * result.reservation_count + 22 * result.effect_count,
"Noncanonical custody result length or tag.");
for (std::size_t i = 0; i < result.reservation_count; ++i) archive.field(result.reservations[i]);
for (std::size_t i = result.reservation_count; i < result.reservations.size(); ++i) {
require_save(result.reservations[i] == 0, "Noncanonical unused result reservation.");
}
for (std::size_t i = 0; i < result.effect_count; ++i) {
auto& effect = result.effects[i];
owner_fields(archive, effect.owner);
archive.field(effect.stack);
archive.field(effect.item);
archive.field(effect.count);
require_save(effect.owner.kind != OwnerKind::None && effect.stack != 0 &&
effect.item > ItemType::None && effect.item <= ItemType::Loom,
"Invalid custody result effect.");
}
for (std::size_t i = result.effect_count; i < result.effects.size(); ++i) {
require_save(result.effects[i] == CustodyEffect{}, "Noncanonical unused result effect.");
}
}
} // namespace
template<class Archive, class State>
void WorldSaveCodec::custody(Archive& archive, State& world) {
archive.field(world.next_stack_id_);
archive.field(world.next_reservation_id_);
archive.field(world.next_transfer_id_);
const auto inventory = [&](auto& value, bool quantities) {
for (std::size_t i = 1; i <= item_type_count; ++i) {
const auto type = static_cast<ItemType>(i);
auto count = value.item_count(type);
if (quantities) archive.field(count);
auto id = value.stack_id(type);
archive.field(id);
require_save((id == 0) == (count == 0), "Noncanonical custody stack identity.");
if constexpr (Archive::reading) {
if (quantities && count != 0) value.add(type, count);
value.set_stack_id(type, id);
}
}
};
for (auto& storage : world.storages_) {
for (auto& stack : storage.items) archive.field(stack.id);
}
for (auto& agent : world.agents_) {
inventory(agent.inventory, false);
archive.field(agent.next_admission);
bool present = agent.execution.has_value();
flag(archive, present);
if constexpr (Archive::reading) { if (present) agent.execution.emplace(); }
if (!present) continue;
auto& execution = *agent.execution;
archive.field(execution.id);
archive.field(execution.kind);
archive.field(execution.production);
archive.field(execution.source);
archive.field(execution.destination);
archive.field(execution.next_operation);
archive.field(execution.blocked);
archive.field(execution.reservation_count);
require_save(execution.kind <= TransferKind::Return && execution.blocked <= CustodyStatus::NoDestination &&
execution.reservation_count <= custody_reservation_limit, "Invalid custody execution fields.");
for (std::size_t i = 0; i < execution.reservation_count; ++i) claim_fields(archive, execution.reservations[i]);
for (std::size_t i = execution.reservation_count; i < execution.reservations.size(); ++i) {
require_save(execution.reservations[i] == Reservation{}, "Noncanonical unused reservation.");
}
}
for (auto& order : world.production_orders_) {
inventory(order.input, true);
flag(archive, order.suspended);
}
for (auto& balance : world.item_balances_) {
archive.field(balance.opening);
archive.field(balance.grant);
archive.field(balance.harvest);
archive.field(balance.recipe_output);
archive.field(balance.recipe_input);
archive.field(balance.meal);
archive.field(balance.installation);
archive.field(balance.demolition);
}
auto count = static_cast<std::uint32_t>(world.custody_receipts_.size());
require_save(world.custody_receipts_.size() <= custody_receipt_limit, "Too many custody receipts.");
archive.field(count);
require_save(count <= custody_receipt_limit, "Too many custody receipts.");
if constexpr (Archive::reading) {
archive.allocate(count, sizeof(CustodyReceipt) + sizeof(std::shared_ptr<const CustodyReceipt>));
world.custody_receipts_.reserve(count);
for (std::uint32_t i = 0; i < count; ++i) {
auto receipt = std::make_shared<CustodyReceipt>();
request_fields(archive, receipt->request);
result_fields(archive, receipt->result);
world.custody_receipts_.push_back(std::move(receipt));
}
world.custody_receipt_cursor_ = 0;
} else {
require_save(count == custody_receipt_limit ? world.custody_receipt_cursor_ < count :
world.custody_receipt_cursor_ == 0, "Invalid custody receipt cursor.");
for (std::size_t i = 0; i < count; ++i) {
const auto index = (i + world.custody_receipt_cursor_) % count;
const auto& receipt = world.custody_receipts_[index];
require_save(receipt != nullptr, "Missing custody receipt.");
request_fields(archive, receipt->request);
result_fields(archive, receipt->result);
}
}
}
void WorldSaveCodec::validate(const World& world, bool modern) {
const auto invalid = [](bool good) { require_save(good, "Save contains inconsistent simulation state."); };
const auto inside = [&](GridPosition p) {
return p.x >= 0 && p.x < world.width_ && p.y >= 0 && p.y < world.height_;
@@ -323,6 +593,7 @@ void WorldSaveCodec::validate(const World& world) {
check_ids(world.jobs_, world.next_job_id_);
check_ids(world.resource_nodes_, world.next_resource_node_id_);
check_ids(world.storages_, world.next_storage_id_);
check_ids(world.production_orders_, world.next_production_id_);
invalid(world.work_priority_ <= WorkPriority::BuildingFirst);
std::uint64_t revision = 0;
for (const auto sequence : world.player_sequences_) {
@@ -371,8 +642,10 @@ void WorldSaveCodec::validate(const World& world) {
}
}
std::vector<ItemCounts> reserved_items(world.storages_.size());
std::vector<ItemCounts> expected_cargo(world.production_orders_.size());
const auto storage_index = [&](StorageId id) { return record_index(world.storages_, id); };
const auto node_index = [&](ResourceNodeId id) { return record_index(world.resource_nodes_, id); };
std::vector<ItemCounts> reserved_items(modern ? 0 : world.storages_.size());
std::vector<ItemCounts> expected_cargo(modern ? 0 : world.production_orders_.size());
std::vector<AgentId> bed_owners;
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
const auto& order = world.production_orders_[i];
@@ -392,6 +665,21 @@ void WorldSaveCodec::validate(const World& world) {
invalid(resident != world.agents_.end() && resident->id == order.bed_owner);
bed_owners.push_back(order.bed_owner);
}
if (modern) {
invalid(order.materials.size() <= custody_material_limit &&
order.collected_stops <= order.delivery_stops.size());
for (const auto& material : order.materials) {
static_cast<void>(item_index(material.type));
invalid(material.count > 0 && world.find_storage(material.storage_id) != nullptr);
}
StorageId previous_stop = 0;
for (const auto& stop : order.delivery_stops) {
invalid(stop.storage_id > previous_stop && world.find_storage(stop.storage_id) != nullptr);
previous_stop = stop.storage_id;
valid_route(stop.route_to_next);
}
continue;
}
if (order.state != JobState::InProgress) {
invalid(order.materials.empty() && order.delivery_stops.empty() && order.collected_stops == 0);
continue;
@@ -399,33 +687,33 @@ void WorldSaveCodec::validate(const World& world) {
const bool delivery = delivers_materials(order.recipe);
invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty()));
std::size_t last_storage = 0;
StorageId last_storage = 0;
bool first_stop = true;
for (const auto& stop : order.delivery_stops) {
invalid(stop.storage_index < world.storages_.size() && (first_stop || last_storage < stop.storage_index));
invalid(world.find_storage(stop.storage_id) != nullptr && (first_stop || last_storage < stop.storage_id));
invalid(std::any_of(order.materials.begin(), order.materials.end(),
[&](const auto& material) { return material.storage_index == stop.storage_index; }));
[&](const auto& material) { return material.storage_id == stop.storage_id; }));
valid_route(stop.route_to_next);
first_stop = false;
last_storage = stop.storage_index;
last_storage = stop.storage_id;
}
ItemCounts ingredients{};
for (const auto& material : order.materials) {
const auto type = item_index(material.type);
invalid(material.storage_index < world.storages_.size() && material.count > 0 &&
world.storages_[material.storage_index].kind == StorageKind::Materials);
invalid(world.find_storage(material.storage_id) != nullptr && material.count > 0 &&
world.storages_[storage_index(material.storage_id)].kind == StorageKind::Materials);
ingredients[type] += material.count;
if (!delivery) {
reserved_items[material.storage_index][type] += material.count;
reserved_items[storage_index(material.storage_id)][type] += material.count;
} else if (!order.delivery_stops.empty()) {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(),
[&](const auto& entry) { return entry.storage_index == material.storage_index; });
[&](const auto& entry) { return entry.storage_id == material.storage_id; });
invalid(stop != order.delivery_stops.end());
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) {
expected_cargo[i][type] += material.count;
} else {
reserved_items[material.storage_index][type] += material.count;
reserved_items[storage_index(material.storage_id)][type] += material.count;
}
}
}
@@ -477,7 +765,7 @@ void WorldSaveCodec::validate(const World& world) {
std::vector<GridPosition> rest_destinations;
for (const auto& agent : world.agents_) {
using enum AgentState;
invalid(agent.state <= Sleeping && agent.route_cursor <= agent.route.size() && agent.hunger <= max_hunger &&
invalid(agent.state <= (modern ? Returning : Sleeping) && agent.route_cursor <= agent.route.size() && agent.hunger <= max_hunger &&
(world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue &&
(world.scenario_active_ || agent.fatigue == 0));
invalid(!agent.resting_on_ground || agent.state == Sleeping || agent.state == GoingToSleep);
@@ -485,13 +773,14 @@ void WorldSaveCodec::validate(const World& world) {
valid_route(agent.route);
valid_route(agent.haul_route);
const bool has_job = agent.current_job != 0;
const bool has_order = agent.production_index != no_entity_index;
const bool has_source = agent.resource_node_index != no_entity_index;
const bool has_storage = agent.storage_index != no_entity_index;
invalid(!has_storage || agent.storage_index < world.storages_.size());
const bool carpentry = has_order && agent.production_index < world.production_orders_.size() &&
is_carpentry_recipe(world.production_orders_[agent.production_index].recipe);
invalid(agent.haul_route.empty() || has_source || carpentry);
const bool has_order = agent.production_id != 0;
const auto* production = world.find_production(agent.production_id);
invalid(!has_order || production != nullptr);
const bool has_source = agent.resource_node_id != 0;
const bool has_storage = agent.storage_id != 0;
invalid(!has_storage || world.find_storage(agent.storage_id) != nullptr);
const bool carpentry = has_order && is_carpentry_recipe(production->recipe);
invalid(modern || agent.haul_route.empty() || has_source || carpentry);
if (has_job) {
invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() &&
(agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0);
@@ -501,58 +790,63 @@ void WorldSaveCodec::validate(const World& world) {
auto& claimed = job_claims[static_cast<std::size_t>(job - world.jobs_.begin())];
invalid(claimed == 0);
claimed = 1;
} else if (modern && agent.state != GoingToSleep && agent.state != Sleeping) {
invalid(!has_source || world.find_resource_node(agent.resource_node_id) != nullptr);
// Live property, claims, execution phase and zero-time pending work
// are checked together by the authoritative custody validator.
continue;
} else if (has_order) {
invalid(!has_storage && !has_source && agent.production_index < world.production_orders_.size() &&
agent.work_remaining > 0);
const auto& order = world.production_orders_[agent.production_index];
invalid(order.state == JobState::InProgress && order_claims[agent.production_index] == 0);
order_claims[agent.production_index] = 1;
invalid(!has_storage && !has_source && agent.work_remaining > 0);
const auto order_index = static_cast<std::size_t>(production - world.production_orders_.data());
const auto& order = *production;
invalid(order.state == JobState::InProgress && order_claims[order_index] == 0);
order_claims[order_index] = 1;
if (!order.delivery_stops.empty()) {
invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling));
} else {
invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe)));
}
if (carpentry) {
const auto storage = order.materials.front().storage_index;
const auto storage = storage_index(order.materials.front().storage_id);
const auto destination = world.storages_[storage].position;
invalid(agent.haul_route.empty() ? destination == order.position : agent.haul_route.back() == destination);
const auto& stops = order.delivery_stops;
const auto output_stop = std::find_if(stops.begin(), stops.end(),
[storage](const auto& stop) { return stop.storage_index == storage; });
[&order](const auto& stop) { return stop.storage_id == order.materials.front().storage_id; });
const bool collected = stops.empty() ||
static_cast<std::size_t>(output_stop - stops.begin()) < order.collected_stops;
if (collected) ++reserved_slots[storage];
}
for (std::size_t i = 0; i < item_types; ++i) {
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]);
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[order_index][i]);
}
} else if (has_source) {
invalid(agent.resource_node_index < world.resource_nodes_.size() &&
invalid(world.find_resource_node(agent.resource_node_id) != nullptr &&
(agent.state == Travelling || agent.state == Gathering) && agent.inventory.empty() &&
agent.work_remaining > 0);
const auto& source = world.resource_nodes_[agent.resource_node_index];
const auto& source = world.resource_nodes_[node_index(agent.resource_node_id)];
if (has_storage) {
invalid(source.quantity > 0 && world.storages_[agent.storage_index].accepts(source.type));
++reserved_slots[agent.storage_index];
invalid(source.quantity > 0 && world.storages_[storage_index(agent.storage_id)].accepts(source.type));
++reserved_slots[storage_index(agent.storage_id)];
} else {
invalid(source.needs_tending() && agent.haul_route.empty());
}
++reserved_nodes[agent.resource_node_index];
++reserved_nodes[node_index(agent.resource_node_id)];
} else if (agent.state == Hauling) {
const auto cargo = agent.inventory.first_item();
invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone ||
cargo == ItemType::Berries || cargo == ItemType::Flax || is_carpentry_item(cargo)) &&
agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 &&
world.storages_[agent.storage_index].accepts(cargo));
world.storages_[storage_index(agent.storage_id)].accepts(cargo));
for (std::size_t i = 1; i <= item_types; ++i) {
const auto type = static_cast<ItemType>(i);
invalid(type == cargo || agent.inventory.item_count(type) == 0);
}
++reserved_slots[agent.storage_index];
++reserved_slots[storage_index(agent.storage_id)];
} else if (agent.state == GoingToEat) {
invalid(world.hunger_enabled_ && has_storage && agent.inventory.empty() &&
world.storages_[agent.storage_index].kind == StorageKind::Pantry);
++reserved_items[agent.storage_index][item_index(ItemType::Berries)];
world.storages_[storage_index(agent.storage_id)].kind == StorageKind::Pantry);
++reserved_items[storage_index(agent.storage_id)][item_index(ItemType::Berries)];
} else if (agent.state == Eating) {
invalid(world.hunger_enabled_ && !has_storage && agent.work_remaining > 0 &&
agent.inventory.item_count(ItemType::Berries) == 1 &&
@@ -582,6 +876,7 @@ void WorldSaveCodec::validate(const World& world) {
for (std::size_t i = 0; i < world.jobs_.size(); ++i) {
invalid((job_claims[i] != 0) == (world.jobs_[i].state == JobState::InProgress));
}
if (modern) { world.validate_custody(); return; }
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
invalid((order_claims[i] != 0) == (world.production_orders_[i].state == JobState::InProgress));
}
@@ -599,14 +894,141 @@ void WorldSaveCodec::validate(const World& world) {
}
}
void World::write_save(std::ostream& stream) const {
void World::migrate_legacy_custody() {
// This function runs only after historical fields, phases, reservations and
// (for versions 1–8) the historical footer have all passed validation.
next_stack_id_ = next_reservation_id_ = next_transfer_id_ = 1;
item_balances_ = {};
custody_receipts_.clear();
custody_receipt_cursor_ = 0;
for (auto& order : production_orders_) {
if (order.state == JobState::InProgress && delivers_materials(order.recipe) && order.delivery_stops.empty()) {
for (const auto& material : order.materials) order.input.add(material.type, material.count);
}
}
const auto identity = [&](ItemType item, std::uint32_t count) {
require_save(next_stack_id_ != std::numeric_limits<StackId>::max(), "Migrated stack identities exhausted.");
auto& opening = item_balances_[item_index(item)].opening;
require_save(count <= std::numeric_limits<std::uint64_t>::max() - opening, "Migrated opening balance overflow.");
opening += count;
return next_stack_id_++;
};
// Stable owner-kind / owner-ID / item order, independent of worker count.
for (auto& storage : storages_) {
for (auto& stack : storage.items) stack.id = identity(stack.type, stack.count);
}
const auto identify_inventory = [&](Inventory& inventory) {
for (std::size_t i = 1; i <= item_type_count; ++i) {
const auto item = static_cast<ItemType>(i);
if (const auto count = inventory.item_count(item)) inventory.set_stack_id(item, identity(item, count));
}
};
for (auto& agent : agents_) identify_inventory(agent.inventory);
for (auto& order : production_orders_) identify_inventory(order.input);
for (auto& agent : agents_) {
agent.next_admission = 1;
agent.execution.reset();
const bool active = agent.production_id != 0 || agent.resource_node_id != 0 ||
agent.state == AgentState::Hauling || agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating;
if (!active) continue;
TransferExecution execution;
execution.id = next_transfer_id_++;
execution.production = agent.production_id;
execution.source = agent.resource_node_id;
execution.destination = agent.storage_id;
const auto add = [&](Reservation claim) -> ReservationId {
require_save(execution.reservation_count < custody_reservation_limit &&
next_reservation_id_ != std::numeric_limits<ReservationId>::max(),
"Migrated reservation limit exceeded.");
claim.id = next_reservation_id_++;
execution.reservations[execution.reservation_count++] = claim;
return claim.id;
};
const auto storage_stack = [&](StorageId storage, ItemType item) -> StackId {
const auto& items = storages_[record_index(storages_, storage)].items;
const auto found = std::lower_bound(items.begin(), items.end(), item,
[](const auto& stack, ItemType target) { return stack.type < target; });
require_save(found != items.end() && found->type == item, "Missing migrated reserved stock.");
return found->id;
};
ReservationId capacity_backing = 0;
if (agent.production_id != 0) {
execution.kind = TransferKind::Production;
const auto& order = production_orders_[record_index(production_orders_, agent.production_id)];
const bool delivery = delivers_materials(order.recipe);
const bool at_site = delivery && order.delivery_stops.empty();
if (!is_construction(order.recipe) || is_carpentry_recipe(order.recipe)) {
execution.destination = order.materials.front().storage_id;
}
for (const auto& material : order.materials) {
StockOwner owner{OwnerKind::Storage, material.storage_id};
StackId stack = 0;
if (at_site) {
owner = {OwnerKind::Production, order.id};
stack = order.input.stack_id(material.type);
} else if (delivery) {
const auto stop = std::lower_bound(order.delivery_stops.begin(), order.delivery_stops.end(), material.storage_id,
[](const auto& entry, StorageId id) { return entry.storage_id < id; });
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) {
owner = {OwnerKind::Resident, agent.id};
stack = agent.inventory.stack_id(material.type);
}
}
if (owner.kind == OwnerKind::Storage) stack = storage_stack(material.storage_id, material.type);
const auto claim = add({0, ReservationKind::Item, owner, stack, material.type, material.count, 0, material.storage_id});
if (!capacity_backing && execution.destination == material.storage_id && owner.kind == OwnerKind::Storage) {
capacity_backing = claim;
}
}
add({0, ReservationKind::Worksite, {OwnerKind::Production, order.id}, 0, {}, 1});
} else if (agent.resource_node_id != 0) {
execution.kind = agent.storage_id ? TransferKind::Harvest : TransferKind::Tending;
add({0, agent.storage_id ? ReservationKind::Harvest : ReservationKind::Tending, {}, 0, {}, 1});
} else if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) {
execution.kind = TransferKind::Meal;
execution.destination = 0;
if (agent.state == AgentState::GoingToEat) {
add({0, ReservationKind::Item, {OwnerKind::Storage, agent.storage_id},
storage_stack(agent.storage_id, ItemType::Berries), ItemType::Berries, 1, 0, agent.storage_id});
} else {
add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id},
agent.inventory.stack_id(ItemType::Berries), ItemType::Berries, 1});
}
} else {
execution.kind = TransferKind::Return;
for (std::size_t i = 1; i <= item_type_count; ++i) {
const auto item = static_cast<ItemType>(i);
if (const auto count = agent.inventory.item_count(item)) {
add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(item), item, count});
}
}
}
if (execution.destination != 0) {
add({0, ReservationKind::Capacity, {OwnerKind::Storage, execution.destination}, 0, {}, 1, capacity_backing});
}
agent.execution = execution;
agent.next_admission = 2;
}
}
void World::write_save(std::ostream& stream, WorldSaveFormat format) const {
const auto version = static_cast<std::uint32_t>(format);
require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14 ||
format == WorldSaveFormat::Current15,
"Unsupported save output format.");
if (format != WorldSaveFormat::Current15 && !legacy_representable()) {
throw UnsupportedLegacyState{};
}
if (format == WorldSaveFormat::Current15) WorldSaveCodec::validate(*this, true);
SaveWriter archive(stream);
for (char letter : signature) archive.field(letter);
archive.field(save_version);
archive.field(version);
archive.field(seed_);
archive.field(width_);
archive.field(height_);
WorldSaveCodec::body(archive, *this, save_version);
WorldSaveCodec::body(archive, *this, version);
if (version >= 15) WorldSaveCodec::custody(archive, *this);
}
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode,
@@ -629,6 +1051,7 @@ std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t worker
archive.field(height);
auto world = std::make_unique<World>(seed, width, height, workers, mode, std::move(worker_options));
WorldSaveCodec::body(archive, *world, version);
if (version >= 15) WorldSaveCodec::custody(archive, *world);
archive.finish();
if (version < 5) {
std::vector<GridPosition> occupied_ground;
@@ -645,7 +1068,11 @@ std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t worker
}
}
}
WorldSaveCodec::validate(*world);
WorldSaveCodec::validate(*world, version >= 15);
if (version < 15) {
world->migrate_legacy_custody();
world->validate_custody();
}
return world;
}
+347
View File
@@ -0,0 +1,347 @@
#include "settlement/core/checkpoint_files.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Suite.hpp>
#include <atomic>
#include <chrono>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using namespace std::chrono_literals;
using Void::Testing::Test;
void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
struct TemporaryDirectory {
std::filesystem::path path = std::filesystem::temp_directory_path() /
("settlement-checkpoint-files-" + Void::Uuid::v4().to_string());
TemporaryDirectory() {
require(std::filesystem::create_directory(path), "cannot create exclusive test directory");
}
~TemporaryDirectory() {
std::error_code error;
std::filesystem::remove_all(path, error);
}
};
std::string saved(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return std::move(stream).str();
}
Void::Uuid::Uuid identity(std::uint8_t last) {
Void::Uuid::Uuid id;
id.bytes.back() = last;
return id;
}
std::shared_ptr<const PublishedSnapshot> snapshot(const World& world) {
auto rules = default_rules_manifest();
require(rules.has_value(), "cannot resolve fixture rules");
return std::make_shared<const PublishedSnapshot>(PublishedSnapshot{
{identity(1), identity(2), 7}, 1, world.capture(),
std::make_shared<const RulesManifest>(std::move(*rules)), {1, 1}});
}
std::string encoded(const World& world) {
const auto view = snapshot(world);
auto bytes = encode_checkpoint(*view->world, view->identity.world, view->identity.city, *view->rules);
require(bytes.has_value(), "cannot encode fixture");
return std::move(*bytes);
}
void write(const std::filesystem::path& path, std::string_view bytes, bool append = false) {
std::ofstream file(path, std::ios::binary | (append ? std::ios::app : std::ios::trunc));
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
file.close();
require(static_cast<bool>(file), "cannot write fixture");
}
template<class Submit>
auto admitted(Submit submit) {
const auto limit = std::chrono::steady_clock::now() + 10s;
for (;;) {
auto operation = submit();
if (operation.admission != decltype(operation.admission)::Busy) return operation;
require(std::chrono::steady_clock::now() < limit, "admission remained busy");
std::this_thread::yield();
}
}
CheckpointLoadResult loaded(CheckpointLoadSubmission operation) {
require(operation.admission == CheckpointLoadAdmission::Accepted && operation.request_id != 0,
"load was not accepted");
require(operation.completion.wait_for(10s) == std::future_status::ready, "load timed out");
return operation.completion.get();
}
CheckpointLoadResult load(CheckpointFiles& files, const std::filesystem::path& path) {
return loaded(admitted([&] { return files.try_load(path, 1, ExecutionMode::SerialReference); }));
}
SaveResult saved_file(SaveSubmission operation) {
require(operation.admission == SaveAdmission::Accepted && operation.request_id != 0,
"save was not accepted");
require(operation.completion.wait_for(10s) == std::future_status::ready, "save timed out");
auto result = operation.completion.get();
require(result.request_id == operation.request_id, "save completion lost identity");
return result;
}
struct Gate {
std::promise<void> entered;
std::future<void> arrival = entered.get_future();
std::promise<void> released;
std::shared_future<void> release = released.get_future().share();
std::atomic<bool> used = false;
std::atomic<bool> opened = false;
void block_once() {
if (used.exchange(true)) return;
entered.set_value();
require(release.wait_for(10s) == std::future_status::ready, "reader gate timed out");
}
void await_entry() {
require(arrival.wait_for(10s) == std::future_status::ready, "reader did not reach gate");
}
void open() {
if (!opened.exchange(true)) released.set_value();
}
};
struct [[= Void::Testing::name("CheckpointFileTests")]]
CheckpointFileTests : Void::Testing::Suite<CheckpointFileTests> {
[[= Void::Testing::tag("checkpoint-file")]] Test saves_held_snapshot_while_runtime_advances();
[[= Void::Testing::tag("checkpoint-file")]] Test legacy_versions_import_with_fresh_identity();
[[= Void::Testing::tag("checkpoint-file")]] Test modern_failures_retain_exact_diagnostics();
[[= Void::Testing::tag("checkpoint-file")]] Test bounds_cover_initial_size_and_growth();
[[= Void::Testing::tag("checkpoint-file")]] Test reader_bound_writer_progress_and_shutdown_drain();
[[= Void::Testing::tag("checkpoint-file")]] Test failures_recover_and_invalid_admission_preserves_inputs();
[[= Void::Testing::tag("checkpoint-file")]] Test reader_self_shutdown_is_rejected_without_closing();
};
Test CheckpointFileTests::saves_held_snapshot_while_runtime_advances() {
TemporaryDirectory directory;
CheckpointFiles files;
auto rules = default_rules_manifest();
require(rules.has_value(), "fixture rules unavailable");
auto clock = std::make_shared<Void::Time::ManualClock>();
SimulationRuntime runtime(
{make_first_colony(2), identity(23), 1, std::move(*rules)}, {.clock = clock});
auto healthy = runtime.snapshot_for_save();
require(healthy.has_value(), "healthy snapshot unavailable");
const auto old = *healthy;
const auto bytes = saved(*old->world);
const auto path = directory.path / L"Поселение_старый_снимок.settlement";
auto saving = admitted([&] { return files.try_save(path, old); });
require(clock->advance(1s).has_value(), "manual clock failed");
auto fence = admitted([&] { return runtime.synchronize(); });
require(fence.admission == RuntimeAdmission::Accepted, "runtime fence rejected");
require(fence.completion.wait_for(10s) == std::future_status::ready, "runtime did not advance");
require(fence.completion.get().outcome == RuntimeOutcome::Completed, "runtime fence failed");
require(runtime.latest()->world->tick() == old->world->tick() + 20, "live world did not progress");
const auto result = saved_file(std::move(saving));
require(result.succeeded() && result.tick == old->world->tick() &&
result.session == old->identity.session, "save metadata or publication changed");
runtime.shutdown();
auto restored = load(files, path);
require(restored.has_value(), "saved snapshot could not load");
require(restored->world_id == old->identity.world && restored->city == old->identity.city &&
restored->rules == *old->rules && saved(*restored->world) == bytes,
"background save read later mutable state");
}
Test CheckpointFileTests::legacy_versions_import_with_fresh_identity() {
TemporaryDirectory directory;
CheckpointFiles files;
World world(0x0102030405060708, 5, 5, 1, ExecutionMode::SerialReference);
const auto current = saved(world);
require(current.size() == 183, "legacy fixture layout changed");
std::vector<std::string> versions{current.substr(0, 146), current, current, current};
versions[0][8] = 1;
versions[0].append("\x58\xc1\x77\x19\x3a\x69\xca\x2c", 8);
versions[1][8] = 8;
versions[1].append("\x33\x73\x67\x28\xa8\x53\x56\xfa", 8);
versions[2][8] = 9;
const auto rules = default_rules_manifest();
require(rules.has_value(), "fixture default rules unavailable");
Void::Uuid::Uuid previous;
for (const auto& version : versions) {
const auto path = directory.path / L"старое.settlement";
write(path, version);
auto restored = load(files, path);
require(restored.has_value(), "historical fixture rejected");
require(!restored->world_id.is_nil() && restored->world_id != previous &&
restored->city == 1 && restored->rules == *rules && saved(*restored->world) == current,
"legacy import lost state or identity isolation");
previous = restored->world_id;
}
const auto path = directory.path / "legacy-trailing.settlement";
write(path, current + 'x');
const auto trailing = load(files, path);
require(!trailing && trailing.error().code == CheckpointFileError::InvalidLegacy,
"legacy trailing bytes were accepted");
}
Test CheckpointFileTests::modern_failures_retain_exact_diagnostics() {
TemporaryDirectory directory;
CheckpointFiles files;
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto current = encoded(world);
const auto path = directory.path / "modern.settlement";
for (const auto& invalid : {current.substr(0, 8), current.substr(0, current.size() - 1), current + 'x'}) {
write(path, invalid);
const auto result = load(files, path);
require(!result && result.error().code == CheckpointFileError::InvalidCheckpoint &&
result.error().checkpoint.has_value() && !result.error().message.empty(),
"modern failure lost its codec diagnostic");
}
auto unsupported = current;
unsupported[8] = static_cast<char>(checkpoint_version + 1);
write(path, unsupported);
const auto version = load(files, path);
require(!version && version.error().checkpoint &&
version.error().checkpoint->code == CheckpointError::UnsupportedVersion,
"modern unsupported version was downgraded or obscured");
write(path, current);
CheckpointFiles missing(std::vector<RulePackage>{});
const auto mismatch = load(missing, path);
require(!mismatch && mismatch.error().checkpoint &&
mismatch.error().checkpoint->code == CheckpointError::RulesMismatch &&
!mismatch.error().checkpoint->package.empty(), "missing package diagnostic was lost");
write(path, saved(world));
const auto legacy_mismatch = load(missing, path);
require(!legacy_mismatch && legacy_mismatch.error().checkpoint &&
legacy_mismatch.error().checkpoint->code == CheckpointError::RulesMismatch,
"legacy import bound unavailable default packages");
write(path, current);
require(load(files, path).has_value(), "reader did not recover after malformed files");
}
Test CheckpointFileTests::bounds_cover_initial_size_and_growth() {
TemporaryDirectory directory;
const auto path = directory.path / "oversized.settlement";
write(path, "");
std::filesystem::resize_file(path, max_checkpoint_bytes + 1);
CheckpointFiles files;
const auto large = load(files, path);
require(!large && large.error().code == CheckpointFileError::TooLarge,
"oversized initial file reached decoding");
write(path, "SETTLERS");
auto grew = std::make_shared<std::atomic<bool>>(false);
CheckpointFiles growing({.max_load_bytes = 512,
.read_observer = [grew, path](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && !grew->exchange(true)) {
write(path, std::string(1024, 'x'), true);
}
}});
const auto growth = load(growing, path);
require(!growth && growth.error().code == CheckpointFileError::TooLarge,
"growth after initial size check escaped the cap");
}
Test CheckpointFileTests::reader_bound_writer_progress_and_shutdown_drain() {
TemporaryDirectory directory;
World world(7, 5, 5, 1, ExecutionMode::SerialReference);
const auto path = directory.path / "read.settlement";
write(path, encoded(world));
World newer(8, 5, 5, 1, ExecutionMode::SerialReference);
const auto new_path = directory.path / "newer.settlement";
write(new_path, encoded(newer));
auto gate = std::make_shared<Gate>();
CheckpointFiles files({.load_capacity = 2, .read_observer = [gate](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened) gate->block_once();
}});
auto unblock = Void::Scope::on_exit([gate] { gate->open(); });
auto first = files.try_load(path);
require(first.admission == CheckpointLoadAdmission::Accepted, "first reader rejected");
gate->await_entry();
auto second = files.try_load(new_path);
require(second.admission == CheckpointLoadAdmission::Accepted && second.request_id > first.request_id,
"second reader did not queue in order");
require(files.try_load(path).admission == CheckpointLoadAdmission::Busy,
"running reader was excluded from bound");
const auto view = snapshot(world);
require(saved_file(admitted([&] { return files.try_save(directory.path / "write.settlement", view); })).succeeded(),
"held reader blocked independent writer");
require(first.completion.wait_for(0s) == std::future_status::timeout, "gate did not hold active read");
auto stopping = std::async(std::launch::async, [&] { files.shutdown(); });
auto release_shutdown = Void::Scope::on_exit([gate] { gate->open(); });
const auto deadline = std::chrono::steady_clock::now() + 10s;
for (;;) {
const auto operation = files.try_load(path);
if (operation.admission == CheckpointLoadAdmission::Closed) break;
require(operation.admission == CheckpointLoadAdmission::Busy, "shutdown unexpectedly admitted a read");
require(std::chrono::steady_clock::now() < deadline, "shutdown did not close admission");
std::this_thread::yield();
}
require(files.try_save(directory.path / "closed.settlement", view).admission == SaveAdmission::Closed,
"shutdown left save admission open");
gate->open();
auto first_result = loaded(std::move(first));
auto second_result = loaded(std::move(second));
require(first_result.has_value() && second_result.has_value() &&
first_result->world->seed() == world.seed() && second_result->world->seed() == newer.seed(),
"shutdown lost or mixed queued load candidates");
require(stopping.wait_for(10s) == std::future_status::ready, "shutdown did not finish");
stopping.get();
}
Test CheckpointFileTests::failures_recover_and_invalid_admission_preserves_inputs() {
TemporaryDirectory directory;
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto path = directory.path / "valid.settlement";
write(path, encoded(world));
auto fail = std::make_shared<std::atomic<bool>>(true);
CheckpointFiles files({.read_observer = [fail](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && fail->exchange(false)) {
throw std::runtime_error("injected read observer failure");
}
}});
require(files.try_load("relative.settlement").admission == CheckpointLoadAdmission::InvalidRequest,
"relative input was admitted");
require(files.try_load(path, 1).admission == CheckpointLoadAdmission::InvalidRequest,
"unsupported parallel worker count admitted");
require(files.try_save(path, {}).admission == SaveAdmission::InvalidRequest, "null snapshot admitted");
const auto view = snapshot(world);
require(files.try_save("relative.settlement", view).admission == SaveAdmission::InvalidRequest &&
view->world->tick() == world.tick(), "invalid save altered its input");
const auto failed = load(files, path);
require(!failed && failed.error().code == CheckpointFileError::ReaderFailure,
"observer failure did not settle future");
const auto missing = load(files, directory.path / "missing.settlement");
require(!missing && missing.error().code == CheckpointFileError::Io && missing.error().native_error != 0,
"missing file lost native error");
write(directory.path / "unknown.settlement", "arbitrary bytes");
const auto unknown = load(files, directory.path / "unknown.settlement");
require(!unknown && unknown.error().code == CheckpointFileError::UnsupportedFormat,
"unknown signature was accepted");
require(load(files, path).has_value(), "failed read poisoned the service");
}
Test CheckpointFileTests::reader_self_shutdown_is_rejected_without_closing() {
TemporaryDirectory directory;
World world(3, 5, 5, 1, ExecutionMode::SerialReference);
const auto path = directory.path / "self.settlement";
write(path, encoded(world));
CheckpointFiles* owner = nullptr;
auto first = std::make_shared<std::atomic<bool>>(true);
CheckpointFiles files({.read_observer = [&owner, first](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && first->exchange(false)) owner->shutdown();
}});
owner = &files;
const auto failure = load(files, path);
require(!failure && failure.error().code == CheckpointFileError::ReaderFailure,
"self shutdown did not report failure");
require(load(files, path).has_value(), "self shutdown closed admission before rejecting");
}
} // namespace
+77 -2
View File
@@ -112,7 +112,51 @@ std::string package_json(std::string_view id, std::string_view version = "1.0.0"
RulePackage load(std::string_view json) { return checked(load_rule_package("checkpoint-fixture.json", json)); }
// Captured before S04 with the baseline 4ba64f7 library, using seed 43,
// a 3x3 world, one SawPlank order, default rules, world_id and city 7.
// The v13 frame is byte-for-byte original (SHA256
// 28043dcc2a9faa6e1b217eb19df5807e159a0ac4bfdcd65de464034527557847).
// v1/v8 bodies apply their historical field/footer layout to that fixed fixture.
std::string old_checkpoint(std::size_t variant) {
constexpr std::array<std::string_view, 3> hex{
"53544843484b505401000000b6000000cb000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530d0000002b00000000000000030000000300000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000bd7066618db314e2ca874c7eae12d9f8cc45a222c446e23906dbd6645710cd62",
"53544843484b505401000000b6000000a4000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c455253010000002b00000000000000030000000300000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
"000000000000000000000000224ae83870bea33ac3afafcd0190d032cb7b517123fb4ac93479daa4cc71cc74ed17ba385446"
"aa69",
"53544843484b505401000000b6000000d3000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c455253080000002b00000000000000030000000300000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000f92cb77443aeca815745b0132cc684f43738865a4034d4474a373902a294e9c31801c47cf80037e4",
};
std::string result;
const auto value = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; };
for (std::size_t i = 0; i < hex[variant].size(); i += 2) {
result.push_back(static_cast<char>(value(hex[variant][i]) * 16 + value(hex[variant][i + 1])));
}
return result;
}
struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Testing::Suite<CheckpointTests> {
[[= Void::Testing::tag("production-id")]] Test test_authentic_v1_import_and_authenticated_schema_body_pairing();
[[= Void::Testing::tag("checkpoint")]] Test test_round_trip_preserves_identity_and_legacy_world_bytes();
[[= Void::Testing::tag("checkpoint")]] Test test_mid_carry_round_trip_continues_the_same_world();
[[= Void::Testing::tag("checkpoint")]] Test test_selected_rules_survive_catalog_reordering();
@@ -123,6 +167,35 @@ struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Test
[[= Void::Testing::tag("checkpoint")]] Test test_world_body_larger_than_one_shot_hash_limit();
};
Test CheckpointTests::test_authentic_v1_import_and_authenticated_schema_body_pairing() {
const auto catalog = checked(builtin_rule_packages());
const auto rules = checked(default_rules_manifest());
for (std::size_t variant = 0; variant < 3; ++variant) {
auto imported = decoded(old_checkpoint(variant), catalog);
require(imported.world_id == world_id && imported.city == 7 && imported.rules == rules &&
imported.world->production_orders().size() == 1 && imported.world->production_orders().front().id == 1,
"authentic schema-1 checkpoint did not import its legacy body");
imported.world->queue_production({2, 2}, RecipeId::SawPlank);
require(imported.world->production_orders().back().id == 2, "legacy import did not set its next production ID");
}
auto imported = decoded(old_checkpoint(0), catalog);
auto current = encoded(*imported.world, rules);
require(static_cast<unsigned char>(current[8]) == 3 &&
static_cast<unsigned char>(current[layout(current).body_begin + 8]) == 15,
"new checkpoint lacks the current schema/body pair");
auto false_legacy = current;
change(false_legacy, 8, std::uint32_t{1}); rehash(false_legacy);
rejected(false_legacy, catalog, CheckpointError::InvalidWorld, "world.version");
auto false_current = old_checkpoint(0);
change(false_current, 8, std::uint32_t{2}); rehash(false_current);
rejected(false_current, catalog, CheckpointError::InvalidWorld, "world.version");
for (std::size_t variant : {1U, 2U}) {
auto wrong = old_checkpoint(variant); // Inner FNV and outer SHA are both valid.
change(wrong, 8, std::uint32_t{2}); rehash(wrong);
rejected(wrong, catalog, CheckpointError::InvalidWorld, "world.version");
}
}
Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes() {
const auto catalog = checked(builtin_rule_packages());
const auto rules = checked(default_rules_manifest());
@@ -137,8 +210,10 @@ Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes(
"checkpoint lost stable world identity, city or rules");
require(saved_state(*restored.world) == before && saved_state(world) == before,
"checkpoint changed the original or restored canonical state");
require(bytes.substr(layout(bytes).body_begin, before.size()) == before,
"checkpoint did not use the existing world serialization");
std::ostringstream modern(std::ios::binary);
world.write_save(modern, WorldSaveFormat::Current15);
require(bytes.substr(layout(bytes).body_begin, modern.str().size()) == modern.str(),
"checkpoint did not use the current world serialization");
require(before.substr(0, 8) == "SETTLERS" && static_cast<unsigned char>(before[8]) == 13,
"canonical serialization version changed");
require(encoded(*restored.world, restored.rules) == bytes, "re-encoding changed the checkpoint frame");
+21 -20
View File
@@ -242,7 +242,7 @@ Test CoreTests::test_production_reservations_and_construction() {
world.storages()[1].item_count(ItemType::StoneBlock) == 2,
"materials left a store before the builder reached it");
for (const auto& agent : world.agents()) {
if (agent.production_index != 0) continue;
if (agent.production_id != orders[0].id) continue;
require(agent.inventory.item_count(ItemType::Plank) == 3 &&
agent.inventory.item_count(ItemType::StoneBlock) == 0,
"the builder's bag does not match the first pickup");
@@ -253,14 +253,14 @@ Test CoreTests::test_production_reservations_and_construction() {
require(world.storages()[1].item_count(ItemType::StoneBlock) == 0,
"the builder did not pick up the second shipment");
for (const auto& agent : world.agents()) {
if (agent.production_index != 0) continue;
if (agent.production_id != orders[0].id) continue;
require(agent.inventory.item_count(ItemType::Plank) == 3 &&
agent.inventory.item_count(ItemType::StoneBlock) == 2,
"the builder's bag does not match the complete haul");
}
}
for (const auto& agent : world.agents()) {
if (agent.production_index != 0 || agent.state != settlement::AgentState::Working) continue;
if (agent.production_id != orders[0].id || agent.state != settlement::AgentState::Working) continue;
require(agent.position == orders[0].position && orders[0].delivery_stops.empty(),
"construction started before the builder reached the site with its materials");
require(agent.inventory.empty(), "the builder retained the cargo after unloading");
@@ -483,15 +483,16 @@ Test CoreTests::test_bed_parts_are_delivered_separately() {
for (int tick = 0; tick < 250 && world->scenario_progress().assigned_beds < 2; ++tick) {
world->step();
for (const auto& agent : world->agents()) {
if (agent.production_index == no_entity_index || agent.state != AgentState::Hauling) continue;
const auto& order = world->production_orders()[agent.production_index];
if (agent.production_id == 0 || agent.state != AgentState::Hauling) continue;
const auto& order = *world->find_production(agent.production_id);
const auto order_index = static_cast<std::size_t>(&order - world->production_orders().data());
const auto expected = order.bed_stage == BedStage::Foundation
? (order.position == wood_bed ? ItemType::Wood : ItemType::Stone) : ItemType::Cloth;
require(agent.inventory.item_count(expected) == 1,
"the resident did not carry the raw material required by this stage");
const auto bit = 1U << static_cast<unsigned>(order.bed_stage);
if ((seen[agent.production_index] & bit) == 0) {
seen[agent.production_index] |= bit;
if ((seen[order_index] & bit) == 0) {
seen[order_index] |= bit;
auto copy = save_roundtrip(*world);
copy->step();
}
@@ -694,12 +695,12 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
CommandStatus::Accepted, "could not schedule the specialist jobs");
world.step();
for (std::size_t index = 0; index < 3; ++index) {
require(world.agents()[index].resource_node_index == index, "a specialist chose the wrong resource");
require(world.agents()[index].resource_node_id == world.resource_nodes()[index].id, "a specialist chose the wrong resource");
}
require(world.agents()[3].production_index == 0 && world.agents()[3].resource_node_index == no_entity_index,
require(world.agents()[3].production_id == world.production_orders().front().id && world.agents()[3].resource_node_id == 0,
"the builder did not take the construction job");
require(assign(miner, Profession::Woodcutter) == CommandStatus::Accepted &&
world.agents()[2].resource_node_index == 2,
world.agents()[2].resource_node_id == world.resource_nodes()[2].id,
"changing professions interrupted a reserved mining job");
auto copy = save_roundtrip(world);
@@ -711,8 +712,8 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
require(save_contents(world) == save_contents(*copy), "specialist jobs diverged after loading");
const auto& resident = world.agents()[2];
if (resident.inventory.item_count(ItemType::Stone) > 0) delivered_stone = true;
if (resident.resource_node_index == 1) later_cut_wood = true;
if (later_cut_wood) require(resident.resource_node_index != 2, "a woodcutter kept selecting mining jobs");
if (resident.resource_node_id == world.resource_nodes()[1].id) later_cut_wood = true;
if (later_cut_wood) require(resident.resource_node_id != world.resource_nodes()[2].id, "a woodcutter kept selecting mining jobs");
}
require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood");
require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed");
@@ -774,7 +775,7 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() {
saved_flax_in_transit = true;
}
if (!saved_active_weaving && loom_order.recipe == RecipeId::WeaveCloth && loom_order.state == JobState::InProgress) {
require(world.agents()[1].production_index == 0 &&
require(world.agents()[1].production_id == world.production_orders().front().id &&
world.object_status(moved_loom, true) == CommandStatus::Busy,
"the loom was assigned to the wrong worker or could move while active");
restored = save_roundtrip(world);
@@ -812,7 +813,7 @@ Test CoreTests::test_field_growth_requires_a_worker() {
"could not assign the farmer");
world.step();
require(world.agents().front().state == AgentState::Travelling &&
world.agents().front().storage_index == no_entity_index &&
world.agents().front().storage_id == 0 &&
world.object_status(field, true) == CommandStatus::Busy, "the farmer did not reserve and walk to the field");
auto restored = save_roundtrip(world);
for (int i = 0; i < 100; ++i) {
@@ -840,7 +841,7 @@ Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() {
require(world.apply_command({1, 2, CommandKind::PlaceMine, {3, 4}}).status == CommandStatus::Accepted,
"failed to open a passage");
world.step();
require(world.agents().front().resource_node_index == 0 &&
require(world.agents().front().resource_node_id == world.resource_nodes()[0].id &&
world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache");
}
@@ -1041,7 +1042,7 @@ Test CoreTests::test_carpenter_delivers_the_door_before_installation() {
}
if (!delivered_door && resident.inventory.item_count(ItemType::WoodenDoor) == 1) {
delivered_door = true;
require(resident.state == AgentState::Hauling && resident.storage_index == 0 &&
require(resident.state == AgentState::Hauling && resident.storage_id == world->storages()[0].id &&
world->storages()[0].item_count(ItemType::WoodenDoor) == 0,
"the finished door appeared on the store before being delivered");
world = save_roundtrip(*world);
@@ -1126,8 +1127,8 @@ Test CoreTests::test_carpenter_makes_furnishings_for_rooms() {
world->step();
const auto& maker = world->agents()[1];
if (variant.item == ItemType::MiningRack && !saved_stone_stop &&
maker.production_index != no_entity_index &&
world->production_orders()[maker.production_index].recipe == variant.craft &&
maker.production_id != 0 &&
world->find_production(maker.production_id)->recipe == variant.craft &&
maker.inventory.item_count(ItemType::Stone) != 0 && maker.inventory.item_count(ItemType::Wood) == 0) {
require(world->storages()[1].reserved_slots == 0, "output space was reserved before collecting wood");
saved_stone_stop = true;
@@ -1135,8 +1136,8 @@ Test CoreTests::test_carpenter_makes_furnishings_for_rooms() {
continue;
}
if (!saved_workshop && maker.state == AgentState::Working && maker.position == workshop &&
maker.production_index != no_entity_index &&
world->production_orders()[maker.production_index].recipe == variant.craft) {
maker.production_id != 0 &&
world->find_production(maker.production_id)->recipe == variant.craft) {
require(world->storages()[1].reserved_slots == 1, "output space was not reserved while crafting");
saved_workshop = true;
world = save_roundtrip(*world);
+431
View File
@@ -0,0 +1,431 @@
#include "settlement/core/checkpoint.hpp"
#include "fixtures/custody_v14/fixtures.hpp"
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/Core/Hash.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <cstring>
#include <limits>
#include <sstream>
#include <stdexcept>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
std::string unhex(std::string_view hex) {
const auto digit = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; };
std::string result;
for (std::size_t i = 0; i < hex.size(); i += 2) result.push_back(static_cast<char>(digit(hex[i]) * 16 + digit(hex[i + 1])));
return result;
}
std::string raw(const World& world, WorldSaveFormat format = WorldSaveFormat::Current15) {
std::ostringstream stream(std::ios::binary); world.write_save(stream, format); return stream.str();
}
WorldCheckpoint load(std::string_view bytes, std::size_t workers = 1) {
const auto catalog = builtin_rule_packages();
auto result = decode_checkpoint(bytes, *catalog, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string save(const WorldCheckpoint& saved) {
auto result = encode_checkpoint(*saved.world, saved.world_id, saved.city, saved.rules);
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
const custody_v14::Fixture& fixture(std::string_view name) {
for (const auto& entry : custody_v14::fixtures) if (entry.name == name) return entry;
throw std::runtime_error("missing historical fixture");
}
std::size_t body_begin(std::string_view bytes) {
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(), bytes.size()}).subspan(12));
return 24 + reader.readLittle<std::uint32_t>().value();
}
template<class T> void change(std::string& bytes, std::size_t offset, T value) {
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset));
if constexpr(std::is_enum_v<T>) require(writer.writeLittle(static_cast<std::underlying_type_t<T>>(value)).has_value(), "mutation exceeded frame");
else require(writer.writeLittle(value).has_value(), "mutation exceeded frame");
}
void rehash(std::string& bytes) {
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
require(hasher && hasher->update(std::string_view(bytes).substr(0,bytes.size()-32)), "hash failed");
auto digest = hasher->finalize(); require(digest.has_value(), "hash finalization failed");
std::memcpy(bytes.data()+bytes.size()-32, digest->data(), 32);
}
void reject(std::string bytes, std::string_view message="authenticated malformed custody was accepted") {
rehash(bytes);
auto catalog = builtin_rule_packages();
require(!decode_checkpoint(bytes,*catalog,1,ExecutionMode::SerialReference), message);
}
struct CustodyOffsets {
std::size_t extension, agent_state, agent_timer, first_execution, receipts;
std::vector<std::size_t> node_reserved, storage_reserved;
std::vector<std::pair<std::size_t,std::size_t>> entries;
};
CustodyOffsets offsets(const World& world, const std::string& bytes) {
CustodyOffsets result{};
const auto body=body_begin(bytes);
Void::Binary::Reader prefix(std::as_bytes(std::span{bytes.data(),bytes.size()}));
const auto skip=[&](std::size_t n){require(prefix.skip(n).has_value(),"incomplete historical prefix");};
const auto count=[&]{return prefix.readLittle<std::uint32_t>().value();};
const auto route_fields=[&]{const auto n=count();skip(static_cast<std::size_t>(n)*8);};
skip(body+109+static_cast<std::size_t>(world.width())*world.height());
const auto agents=count();
for(std::uint32_t i=0;i<agents;++i){skip(25);route_fields();skip(28+4*item_type_count);route_fields();skip(14);}
const auto jobs=count();skip(static_cast<std::size_t>(jobs)*25);
const auto nodes=count();
for(std::uint32_t i=0;i<nodes;++i){result.node_reserved.push_back(prefix.position()+25);skip(39);}
const auto stores=count();
for(std::uint32_t i=0;i<stores;++i){result.storage_reserved.push_back(prefix.position()+20);skip(25);const auto items=count();skip(static_cast<std::size_t>(items)*9);}
const auto orders=count();
for(std::uint32_t i=0;i<orders;++i){skip(18);const auto materials=count();skip(static_cast<std::size_t>(materials)*13);const auto stops=count();for(std::uint32_t j=0;j<stops;++j){skip(8);route_fields();}skip(18);}
skip(37);result.extension=prefix.position();
result.first_execution=result.extension+24+8*item_type_count+9;
for(const auto& store:world.storages())result.first_execution+=8*store.items.size();
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(),bytes.size()}));
require(reader.skip(body+109+static_cast<std::size_t>(world.width())*world.height()+4+16).has_value(),"missing agent state");
result.agent_state=reader.position();
require(reader.skip(9).has_value(),"missing agent route");
const auto route=reader.readLittle<std::uint32_t>().value();
require(reader.skip(static_cast<std::size_t>(route)*8+8).has_value(),"missing agent timer");
result.agent_timer=reader.position();
std::size_t extension_size=24+world.production_orders().size()*(12*item_type_count+1)+64*item_type_count;
for(const auto& store:world.storages()) extension_size+=store.items.size()*8;
for(const auto& agent:world.agents()) extension_size+=8*item_type_count+9+
(agent.execution?43+47*agent.execution->reservation_count:0);
result.receipts=result.extension+extension_size;
Void::Binary::Reader receipts(std::as_bytes(std::span{bytes.data(),bytes.size()}).subspan(result.receipts));
const auto receipt_count=receipts.readLittle<std::uint32_t>().value();
for(std::uint32_t i=0;i<receipt_count;++i){
const auto request=result.receipts+receipts.position();
const auto request_size=receipts.readLittle<std::uint16_t>().value();require(receipts.skip(request_size).has_value(),"bad request fixture");
const auto response=result.receipts+receipts.position();
const auto result_size=receipts.readLittle<std::uint16_t>().value();require(receipts.skip(result_size).has_value(),"bad result fixture");
result.entries.emplace_back(request,response);
}
return result;
}
void legacy_reject(const World& world) {
for (auto format : {WorldSaveFormat::Legacy13, WorldSaveFormat::Current14}) {
std::ostringstream out(std::ios::binary);
bool failed = false;
try { world.write_save(out,format); } catch (const UnsupportedLegacyState&) { failed=true; }
require(failed && out.str().empty(), "unsupported projection wrote a prefix or lost typed error");
}
}
WorldCheckpoint split_carpenter() {
auto metadata=load(unhex(fixture("carpenter-output").checkpoint));
metadata.world=std::make_unique<World>(43,24,24,1,ExecutionMode::SerialReference);
auto& world=*metadata.world;world.start_scenario({2,2});
const auto a=world.add_storage({3,3},20),b=world.add_storage({8,3},20);
world.stock_storage(a,ItemType::Wood,1);world.stock_storage(b,ItemType::Wood,1);
const auto actor=world.spawn_agent({1,3});
require(world.apply_command({1,1,CommandKind::AssignProfession,{},static_cast<std::uint8_t>(Profession::Carpenter),{},actor}).status==CommandStatus::Accepted,"carpenter assignment failed");
world.queue_production({2,2},RecipeId::CraftWoodenDoor);
return metadata;
}
struct [[= Void::Testing::name("CustodyMigrationTests")]] CustodyMigrationTests : Void::Testing::Suite<CustodyMigrationTests> {
[[= Void::Testing::tag("custody-migration")]] Test authentic_historical_phases_keep_eighty_tick_projection();
[[= Void::Testing::tag("custody-migration")]] Test opening_stock_and_admission_are_reconstructed_without_receipts();
[[= Void::Testing::tag("custody-migration")]] Test modern_frames_reject_identity_balance_and_pair_corruption();
[[= Void::Testing::tag("custody-migration")]] Test cancellation_is_durable_and_legacy_refusal_is_before_output();
[[= Void::Testing::tag("custody-migration")]] Test completed_receipts_keep_retired_stock_and_order_references();
[[= Void::Testing::tag("custody-migration")]] Test single_finished_material_and_partial_return_use_modern_format();
[[= Void::Testing::tag("custody-migration")]] Test suspended_sites_and_zero_completion_use_modern_format();
[[= Void::Testing::tag("custody-mutation")]] Test authenticated_phase_and_receipt_mutations_are_rejected();
[[= Void::Testing::tag("custody-mutation")]] Test retired_zero_effect_and_bounded_receipt_fields();
[[= Void::Testing::tag("custody-migration")]] Test truncated_collection_counts_allocate_incrementally();
[[= Void::Testing::tag("custody-mutation")]] Test full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals();
[[= Void::Testing::tag("custody-mutation")]] Test admission_result_reservations_are_distinct();
[[= Void::Testing::tag("custody-mutation")]] Test result_effects_are_unique_with_retired_and_distinct_owners();
[[= Void::Testing::tag("custody-mutation")]] Test source_less_harvesting_and_reserved_return_destination_are_rejected();
};
Test CustodyMigrationTests::authentic_historical_phases_keep_eighty_tick_projection() {
for (const auto& original : custody_v14::fixtures) {
const auto bytes=unhex(original.checkpoint);
const auto digest=Void::Crypto::sha256(std::string_view(bytes));
require(digest.has_value(), "fixture hashing failed");
const auto expected_digest=unhex(original.sha256);
require(std::ranges::equal(*digest,std::as_bytes(std::span{expected_digest.data(),expected_digest.size()})), "historical fixture SHA differs");
for (auto workers : {1U,2U,6U,12U}) {
auto restored=load(bytes,workers);
require(raw(*restored.world,WorldSaveFormat::Current14)==bytes.substr(body_begin(bytes),bytes.size()-body_begin(bytes)-32), original.name);
for (std::size_t tick=0;tick<original.ticks.size();++tick) {
require(Void::Hash::fnv1a64(raw(*restored.world,WorldSaveFormat::Legacy13))==original.ticks[tick],
std::string(original.name)+" historical tick "+std::to_string(tick));
const auto modern=save(restored);
auto roundtrip=load(modern,workers);
require(save(roundtrip)==modern,"modern migration roundtrip changed canonical bytes");
restored.world->step();
roundtrip.world->step();
require(raw(*roundtrip.world)==raw(*restored.world), "modern continuation diverged");
}
}
}
}
Test CustodyMigrationTests::opening_stock_and_admission_are_reconstructed_without_receipts() {
for(const auto& original:custody_v14::fixtures) {
auto restored=load(unhex(original.checkpoint)); const auto& world=*restored.world;
world.validate_custody();
require(world.custody_receipts().empty(),"migration invented historical receipts");
const auto& actor=world.agents().front();
require(actor.execution && actor.next_admission==2 && actor.execution->next_operation==1,"active legacy admission was not marked consumed");
CustodyRequest retry;retry.key={CustodyKeyKind::Admission,actor.id,1};
require(restored.world->custody_request(retry).status==CustodyStatus::Stale,"migrated admission was executed again");
if(original.name=="cabin-working") {
const auto& input=world.production_orders().front().input;
require(input.item_count(ItemType::Plank)==3&&input.item_count(ItemType::StoneBlock)==2&&actor.inventory.empty(),"implicit worksite stock was not restored");
require(world.item_balances()[2].opening==3&&world.item_balances()[3].opening==2,"opening was measured before worksite restoration");
}
if(original.name.starts_with("direct-")) require(world.production_orders().front().input.empty(),"direct recipe debited input during migration");
}
}
Test CustodyMigrationTests::modern_frames_reject_identity_balance_and_pair_corruption() {
auto restored=load(unhex(fixture("cabin-before-pickup").checkpoint));
const auto good=save(restored), before=raw(*restored.world);
const auto extension=body_begin(good)+raw(*restored.world,WorldSaveFormat::Current14).size();
for(auto offset:{extension,extension+8,extension+16}) {
auto bad=good;change(bad,offset,std::uint64_t{0});reject(std::move(bad));
}
auto duplicate=good;change(duplicate,extension+24+8,std::uint64_t{1});reject(std::move(duplicate));
auto bad_balance=good; // Last 11*64 bytes before receipt count are the balance ledger.
const auto balance=good.size()-32-4-item_type_count*64;
change(bad_balance,balance,std::uint64_t{1});reject(std::move(bad_balance));
for(auto schema:{1U,2U}){auto bad=good;change(bad,8,schema);reject(std::move(bad));}
auto false_three=unhex(fixture("cabin-working").checkpoint);change(false_three,8,3U);reject(std::move(false_three));
require(raw(*restored.world)==before,"decoding corrupt candidate mutated active owner");
}
Test CustodyMigrationTests::cancellation_is_durable_and_legacy_refusal_is_before_output() {
for(auto name:{"cabin-between-stops","cabin-to-site","cabin-working"}) {
auto restored=load(unhex(fixture(name).checkpoint));
const auto id=restored.world->production_orders().front().id;
require(restored.world->cancel_production(id)==CommandStatus::Accepted,"cancel refused historical active construction");
legacy_reject(*restored.world);
const auto bytes=save(restored);auto loaded=load(bytes);
require(save(loaded)==bytes,"return cargo lost in modern checkpoint");
for(int tick=0;tick<80;++tick){restored.world->step();loaded.world->step();require(raw(*restored.world)==raw(*loaded.world),"return differed after restore");}
}
}
Test CustodyMigrationTests::completed_receipts_keep_retired_stock_and_order_references() {
auto restored=load(unhex(fixture("cabin-working").checkpoint));
require(restored.world->cancel_production(restored.world->production_orders().front().id)==CommandStatus::Accepted,"fixture active order removal failed");
require(!restored.world->custody_receipts().empty(),"fixture did not create cancellation receipt");
const auto remembered=restored.world->custody_receipts().back();
for(int tick=0;tick<80;++tick)restored.world->step();
const auto bytes=save(restored);auto loaded=load(bytes);
require(loaded.world->custody_request(remembered->request)==remembered->result,"historical result was lost after referenced stock/order retirement");
}
Test CustodyMigrationTests::single_finished_material_and_partial_return_use_modern_format() {
for (auto item : {ItemType::Plank, ItemType::StoneBlock}) {
auto metadata = load(unhex(fixture("cabin-working").checkpoint));
auto world = std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
const auto first=world->add_storage({3,3},20), second=world->add_storage({8,3},20);
world->stock_storage(first,item,1);
world->stock_storage(second,ItemType::Plank,item==ItemType::Plank?2:3);
world->stock_storage(second,ItemType::StoneBlock,item==ItemType::StoneBlock?1:2);
static_cast<void>(world->spawn_agent({1,3}));world->queue_production({14,3},RecipeId::BuildCabin);
for(int tick=0;tick<10&&world->agents().front().inventory.empty();++tick)world->step();
require(world->agents().front().inventory.item_count(item)==1,"fixture missed single-item pickup");
require(world->cancel_production(world->production_orders().front().id)==CommandStatus::Accepted,"single cargo cancellation failed");
legacy_reject(*world);metadata.world=std::move(world);
const auto encoded=save(metadata);require(save(load(encoded))==encoded,"single finished material did not roundtrip");
}
for (bool partial : {false,true}) {
auto restored=load(unhex(fixture("cabin-working").checkpoint));
restored.world->stock_storage(restored.world->storages()[0].id,ItemType::Wood,partial?19:20);
restored.world->stock_storage(restored.world->storages()[1].id,ItemType::Wood,20);
require(restored.world->cancel_production(restored.world->production_orders().front().id)==CommandStatus::Accepted,"full-store cancellation failed");
for(int tick=0;tick<40;++tick)restored.world->step();
require(restored.world->agents().front().inventory.item_count(ItemType::Plank)==(partial?2U:3U),"return did not respect exact available capacity");
require(restored.world->agents().front().inventory.item_count(ItemType::StoneBlock)==2,"mixed return dropped second item");
legacy_reject(*restored.world);const auto encoded=save(restored);require(save(load(encoded))==encoded,"partial or blocked return did not roundtrip");
}
}
Test CustodyMigrationTests::suspended_sites_and_zero_completion_use_modern_format() {
for(bool bed:{false,true}) {
auto metadata=load(unhex(fixture("cabin-working").checkpoint));
auto world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
world->start_scenario({2,2});const auto storage=world->add_storage({3,3},20);
world->stock_storage(storage,ItemType::Wood,bed?1:2);static_cast<void>(world->spawn_agent({1,3}));
if(bed)require(world->apply_command({1,1,CommandKind::PlaceBed,{6,3}}).status==CommandStatus::Accepted,"bed placement failed");
else world->queue_production({6,3},RecipeId::BuildLoom);
for(int tick=0;tick<45;++tick)world->step();
require(world->cancel_production(world->production_orders().front().id)==CommandStatus::Accepted,"residual site cancellation failed");
require(world->production_orders().front().suspended,"residual site was not suspended");
legacy_reject(*world);metadata.world=std::move(world);
const auto encoded=save(metadata);auto loaded=load(encoded);require(save(loaded)==encoded,"suspended site did not roundtrip");
require(loaded.world->resume_production(loaded.world->production_orders().front().id)==CommandStatus::Accepted,"suspended site cannot resume after restore");
}
auto metadata=load(unhex(fixture("cabin-working").checkpoint));
auto encoded=save(metadata);
// The historical prefix is kept in raw15. Parse its first agent timer rather
// than relying on native object layout; this is a valid pending completion.
const auto body=body_begin(encoded);
Void::Binary::Reader reader(std::as_bytes(std::span{encoded.data(),encoded.size()}).subspan(body));
require(reader.skip(20).has_value(),"missing dimensions");
const auto width=reader.readLittle<std::uint32_t>().value(),height=reader.readLittle<std::uint32_t>().value();
require(reader.skip(81+static_cast<std::size_t>(width)*height+4+25).has_value(),"missing first agent");
const auto route=reader.readLittle<std::uint32_t>().value();
require(reader.skip(static_cast<std::size_t>(route)*8+8).has_value(),"missing first route");
change(encoded,body+reader.position(),std::uint32_t{0});rehash(encoded);
auto pending=load(encoded);legacy_reject(*pending.world);
require(save(pending)==encoded,"pending zero timer did not roundtrip");
pending.world->step();pending.world->validate_custody();
}
Test CustodyMigrationTests::authenticated_phase_and_receipt_mutations_are_rejected() {
auto metadata=load(unhex(fixture("cabin-before-pickup").checkpoint));
metadata.world->step();
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
require(location.entries.size()==1,"pickup should produce one retained operation");
require(save(load(good))==good,"authentic active pickup original was rejected");
const auto [request,result]=location.entries.front();
auto wrong_transfer=good;
change(wrong_transfer,location.extension+16,std::uint64_t{3});
change(wrong_transfer,result+3,std::uint64_t{2});reject(std::move(wrong_transfer),"mismatched receipt transfer accepted");
auto terminal=good;change(terminal,result+13,std::uint8_t{1});reject(std::move(terminal),"terminal historical receipt for active transfer accepted");
auto future=good;change(future,request+11,std::numeric_limits<std::uint64_t>::max());reject(std::move(future),"future live operation accepted");
auto source=good;change(source,request+29,std::numeric_limits<std::uint64_t>::max());reject(std::move(source),"out-of-range historical source accepted");
auto fetching=load(unhex(fixture("cabin-before-pickup").checkpoint));
const auto fetching_bytes=save(fetching);const auto fetching_location=offsets(*fetching.world,fetching_bytes);
require(save(load(fetching_bytes))==fetching_bytes,"authentic fetching original was rejected");
auto travelling=fetching_bytes;change(travelling,fetching_location.agent_state,AgentState::Travelling);
reject(std::move(travelling),"delivery actor with remaining source stops accepted as Travelling");
metadata.world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
static_cast<void>(metadata.world->spawn_agent({1,3}));
const auto idle_storage=metadata.world->add_storage({3,3},10);
const auto idle=save(metadata); const auto idle_locations=offsets(*metadata.world,idle);
for(auto state:{AgentState::Travelling,AgentState::Working,AgentState::Gathering,AgentState::FetchingMaterials}) {
auto bad=idle;change(bad,idle_locations.agent_state,state);reject(std::move(bad));
}
auto timer=idle;change(timer,idle_locations.agent_timer,std::uint32_t{1});reject(std::move(timer),"idle resident with work timer accepted");
auto storage=idle;change(storage,idle_locations.agent_timer+12,idle_storage);reject(std::move(storage),"idle resident with live storage link accepted");
}
Test CustodyMigrationTests::retired_zero_effect_and_bounded_receipt_fields() {
auto metadata=load(unhex(fixture("meal-eating").checkpoint));
for(int tick=0;tick<8;++tick)metadata.world->step();
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
require(!location.entries.empty(),"meal did not produce historical result");
const auto [request,result]=location.entries.back();
auto loaded=load(good);
const auto receipt=metadata.world->custody_receipts().back();
require(receipt->result.effect_count==1&&receipt->result.effects[0].count==0,"terminal consumption lost retired zero-count effect");
require(loaded.world->custody_request(receipt->request)==receipt->result,"zero-count historical effect changed after restore");
auto oversized=good;change(oversized,request,std::uint16_t{1025});reject(std::move(oversized));
auto too_many=good;change(too_many,location.receipts,std::uint32_t{4097});reject(std::move(too_many));
auto bad_item=good;change(bad_item,result+2+12+17,ItemType::None);reject(std::move(bad_item));
auto bad_owner=good;change(bad_owner,result+2+12,OwnerKind::None);reject(std::move(bad_owner));
auto count=good;change(count,result+2+10,std::uint8_t{12});reject(std::move(count));
}
Test CustodyMigrationTests::truncated_collection_counts_allocate_incrementally() {
auto original=unhex(fixture("cabin-before-pickup").checkpoint);
const auto begin=body_begin(original);
std::string body=original.substr(begin,original.size()-begin-32);
constexpr std::size_t agents_count=109+20*8;
body.resize(agents_count+4);
for(auto count:{1'000'000U,1'000'001U}) {
change(body,agents_count,count);
std::istringstream input(body,std::ios::binary);
bool failed=false;
try{static_cast<void>(World::read_save(input,1,ExecutionMode::SerialReference));}
catch(const std::runtime_error&){failed=true;}
require(failed,"truncated huge agent declaration was accepted");
}
// Many byte-light historical agents remain valid despite larger modern
// in-memory Agent records; the wire ceiling does not become a sizeof cap.
World world(43,3,3,1,ExecutionMode::SerialReference);
for(int i=0;i<2000;++i)static_cast<void>(world.spawn_agent({1,1}));
const auto bytes=raw(world,WorldSaveFormat::Current14);
std::istringstream input(bytes,std::ios::binary);
auto loaded=World::read_save(input,1,ExecutionMode::SerialReference);
require(loaded->agents().size()==2000&&raw(*loaded,WorldSaveFormat::Current14)==bytes,"byte-light history failed migration");
}
Test CustodyMigrationTests::full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals() {
auto metadata=load(unhex(fixture("meal-eating").checkpoint));
metadata.world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
const auto storage=metadata.world->add_storage({3,3},2050);
metadata.world->stock_storage(storage,ItemType::Wood,2050);
static_cast<void>(metadata.world->spawn_agent({3,3}));
for(int i=0;i<2050;++i)metadata.world->queue_production({3,3},RecipeId::SawPlank);
for(int tick=0;tick<30000&&metadata.world->custody_receipts().size()<4096;++tick)metadata.world->step();
require(metadata.world->custody_receipts().size()==4096,"real production did not fill global receipt ring");
const auto remembered=metadata.world->custody_receipts().front();
const auto full=save(metadata);auto loaded=load(full);
require(save(loaded)==full&&loaded.world->custody_receipts().size()==4096,"full receipt ring was truncated or reordered");
require(full.size()<2*1024*1024,"typed receipt ring exceeded its proven wire budget");
require(loaded.world->custody_request(remembered->request)==remembered->result,"full ring lost exact replay");
auto conflicting=remembered->request;conflicting.destination=0;
require(loaded.world->custody_request(conflicting).status==CustodyStatus::Conflict,"exact request conflict was not detected");
for(int tick=0;tick<30;++tick)loaded.world->step();
require(loaded.world->custody_request(remembered->request).status==CustodyStatus::Stale,"evicted admission was eligible for replay");
const auto wrapped=save(loaded);auto copy=load(wrapped);
require(save(copy)==wrapped&&copy.world->custody_request(remembered->request).status==CustodyStatus::Stale,"wrapped ring changed order or stale fence on restore");
}
Test CustodyMigrationTests::admission_result_reservations_are_distinct() {
auto metadata=split_carpenter();metadata.world->step();
require(metadata.world->custody_receipts().size()==1,"expected real admission before pickup");
const auto receipt=metadata.world->custody_receipts().front();
require(receipt->request.key.kind==CustodyKeyKind::Admission&&receipt->result.reservation_count==4,"split carpenter admission lost its claims");
for(std::size_t i=1;i<receipt->result.reservation_count;++i)require(receipt->result.reservations[i-1]<receipt->result.reservations[i],"issued reservation order is not canonical");
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
auto duplicate=good;
change(duplicate,location.entries.front().second+14+8,receipt->result.reservations[0]);
reject(std::move(duplicate),"duplicate historical admission reservation accepted");
}
Test CustodyMigrationTests::result_effects_are_unique_with_retired_and_distinct_owners() {
auto metadata=split_carpenter();
for(int tick=0;tick<80&&metadata.world->production_orders().front().state!=JobState::Completed;++tick)metadata.world->step();
const auto receipt=metadata.world->custody_receipts().back();
require(receipt->request.operation==CustodyOperation::Complete,"carpenter did not reach actual completion");
require(receipt->result.effect_count==2,"split input emitted repeated final stock effects");
require(receipt->result.effects[0].owner.kind==OwnerKind::Production&&receipt->result.effects[0].count==0&&
receipt->result.effects[1].owner.kind==OwnerKind::Resident&&receipt->result.effects[1].count==1,"completion lost retired input or distinct output owner");
const auto good=save(metadata);const auto location=offsets(*metadata.world,good);
auto restored=load(good);
require(save(restored)==good&&restored.world->custody_request(receipt->request)==receipt->result,"mixed-owner historical result did not roundtrip");
const auto first=location.entries.back().second+14+8*receipt->result.reservation_count;
auto duplicate=good;duplicate.replace(first+22,22,good.substr(first,22));
reject(std::move(duplicate),"duplicate historical effect accepted");
}
Test CustodyMigrationTests::source_less_harvesting_and_reserved_return_destination_are_rejected() {
auto gathering=load(unhex(fixture("harvest-gathering").checkpoint));
const auto original=save(gathering); const auto location=offsets(*gathering.world,original);
require(save(load(original))==original,"authentic harvesting original was rejected");
auto missing=original;
change(missing,location.agent_timer+4,std::uint64_t{0});
change(missing,location.first_execution+17,std::uint64_t{0});
change(missing,location.node_reserved.front(),std::uint32_t{0});
// Remove the source claim together with its cached worker count, keeping the
// real destination capacity. A mere cache mismatch must not explain refusal.
require(gathering.world->agents().front().execution->reservations[0].kind==ReservationKind::Harvest,"source claim fixture changed");
missing.replace(location.first_execution+43,47,47,'\0');
reject(std::move(missing),"Gathering without source or source claim accepted");
auto returning=load(unhex(fixture("cabin-working").checkpoint));
require(returning.world->cancel_production(returning.world->production_orders().front().id)==CommandStatus::Accepted,"return fixture cancellation failed");
const auto good=save(returning);const auto cancelled=offsets(*returning.world,good);
require(save(load(good))==good,"authentic cancellation original was rejected");
require(returning.world->agents().front().execution->reservation_count==0,"cancel did not release all reservations");
Void::Binary::Reader counter(std::as_bytes(std::span{good.data(),good.size()}).subspan(cancelled.extension+8));
const auto next=counter.readLittle<std::uint64_t>().value();
const auto destination=returning.world->storages().front().id;
auto reserved=good;
change(reserved,cancelled.extension+8,next+1);
change(reserved,cancelled.first_execution+25,destination);
change(reserved,cancelled.first_execution+42,std::uint8_t{1});
change(reserved,cancelled.storage_reserved.front(),std::uint32_t{1});
std::string capacity(47,'\0');
change(capacity,0,next);change(capacity,8,ReservationKind::Capacity);
change(capacity,9,OwnerKind::Storage);change(capacity,10,destination);change(capacity,27,std::uint32_t{1});
reserved.insert(cancelled.first_execution+43,capacity);
change(reserved,16,static_cast<std::uint64_t>(reserved.size()-32-body_begin(reserved)));
reject(std::move(reserved),"Returning retained a destination and matching capacity reservation");
}
} // namespace
+416
View File
@@ -0,0 +1,416 @@
#include "settlement/core/world.hpp"
#include <Void/Testing/Suite.hpp>
#include <stdexcept>
#include <sstream>
#include <limits>
#include <chrono>
#include <algorithm>
#include <iostream>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); }
void ticks(World& world, int count) { for (int i = 0; i < count; ++i) { world.step(); world.validate_custody(); } }
std::unique_ptr<World> cabin(std::uint32_t stock = 3) {
auto w = std::make_unique<World>(7, 32, 32, 1, ExecutionMode::SerialReference);
auto storage = w->add_storage({3, 3}, 50);
w->stock_storage(storage, ItemType::Plank, stock);
w->stock_storage(storage, ItemType::StoneBlock, 2);
(void)w->spawn_agent({1, 3});
w->queue_production({16, 3}, RecipeId::BuildCabin);
return w;
}
struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::Suite<CustodyTests> {
[[= Void::Testing::tag("custody")]] Test ownership_delivery_and_consumption();
[[= Void::Testing::tag("custody")]] Test cancel_site_returns_all_types();
[[= Void::Testing::tag("custody")]] Test split_merge_and_snapshot();
[[= Void::Testing::tag("custody")]] Test exact_receipt_and_conflict();
[[= Void::Testing::tag("custody")]] Test original_colony_continuous_balance();
[[= Void::Testing::tag("custody")]] Test five_sources();
[[= Void::Testing::tag("custody")]] Test retained_result_uniqueness_and_canonical_operands();
[[= Void::Testing::tag("custody")]] Test active_terminal_and_delivery_phase_are_rejected();
[[= Void::Testing::tag("custody")]] Test harvest_source_and_return_capacity_are_required_by_phase();
[[= Void::Testing::tag("custody")]] Test merged_carpentry_effects_keep_distinct_owners();
[[= Void::Testing::tag("custody")]] Test blocked_return_retains_every_item();
[[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume();
[[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction();
[[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance();
[[= Void::Testing::tag("custody")]] Test rejects_missing_execution_and_claims();
[[= Void::Testing::tag("custody")]] Test persistent_counter_boundaries_and_pending_completion();
[[= Void::Testing::tag("custody")]] Test resident_and_job_id_allocation_is_checked();
[[= Void::Testing::tag("custody")]] Test modern_roundtrip_cancel_and_exact_retry();
[[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics();
};
Test CustodyTests::ownership_delivery_and_consumption() {
auto w = cabin();
const auto plank = w->storages()[0].items[0].id;
ticks(*w, 2);
require(w->agents()[0].inventory.stack_id(ItemType::Plank) == plank, "whole pickup changed ID");
for (int i = 0; i < 20 && w->agents()[0].state != AgentState::Working; ++i) ticks(*w, 1);
require(w->production_orders()[0].input.stack_id(ItemType::Plank) == plank, "site lost ID");
require(w->production_orders()[0].input.item_count(ItemType::Plank) == 3, "site lost physical count");
ticks(*w, 40);
require(w->production_orders()[0].state == JobState::Completed, "construction incomplete");
require(w->item_balances()[2].installation == 3, "installation sink missing");
}
Test CustodyTests::cancel_site_returns_all_types() {
auto w = cabin();
ticks(*w, 16);
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
w->validate_custody();
require(w->agents()[0].state == AgentState::Returning && !w->legacy_representable(), "cancel phase lost");
ticks(*w, 40);
require(w->agents()[0].inventory.empty() && w->storages()[0].item_count(ItemType::Plank) == 3 &&
w->storages()[0].item_count(ItemType::StoneBlock) == 2, "return lost cargo");
}
Test CustodyTests::split_merge_and_snapshot() {
auto w = cabin(5);
const auto original = w->storages()[0].items[0].id;
auto snapshot = w->capture();
ticks(*w, 2);
require(w->storages()[0].items[0].id == original && w->agents()[0].inventory.stack_id(ItemType::Plank) != original, "split identity wrong");
require(snapshot->storages()[0].item_count(ItemType::Plank) == 5 && snapshot->custody_receipts().empty(), "snapshot mutated");
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
ticks(*w, 10);
require(w->storages()[0].items[0].id == original && w->storages()[0].item_count(ItemType::Plank) == 5, "merge identity wrong");
}
Test CustodyTests::exact_receipt_and_conflict() {
auto w = cabin(); ticks(*w, 1);
auto receipt = *w->custody_receipts().front();
require(w->custody_request(receipt.request) == receipt.result, "exact retry differed");
++receipt.request.destination;
require(w->custody_request(receipt.request).status == CustodyStatus::Conflict, "changed retry accepted");
receipt.request.key.ordinal += 100;
require(w->custody_request(receipt.request).status == CustodyStatus::Future, "future retry accepted");
ticks(*w, 60);
}
Test CustodyTests::original_colony_continuous_balance() {
auto w = make_first_colony(1, BedConstructionMode::Staged, ExecutionMode::SerialReference);
w->validate_custody();
ticks(*w, 1000);
}
Test CustodyTests::five_sources() {
auto w = std::make_unique<World>(7, 32, 32, 1, ExecutionMode::SerialReference);
for (int i = 0; i < 5; ++i) {
const auto store = w->add_storage({3 + i, 3}, 10);
w->stock_storage(store, i < 3 ? ItemType::Plank : ItemType::StoneBlock, 1);
}
(void)w->spawn_agent({1, 3}); w->queue_production({16, 3}, RecipeId::BuildCabin);
ticks(*w, 1);
require(w->custody_receipts()[0]->request.line_count == 5, "admission omitted sources");
ticks(*w, 80);
require(w->production_orders()[0].state == JobState::Completed, "five-source cabin incomplete");
const auto completion = std::find_if(w->custody_receipts().begin(), w->custody_receipts().end(),
[](const auto& receipt) { return receipt->request.operation == CustodyOperation::Complete; });
require(completion != w->custody_receipts().end() && (*completion)->result.effect_count == 2,
"merged site inputs repeated the same final stack outcome");
require((*completion)->result.effects[0].item == ItemType::Plank && (*completion)->result.effects[1].item == ItemType::StoneBlock &&
(*completion)->result.effects[0].count == 0 && (*completion)->result.effects[1].count == 0,
"consumed outcomes lost first material order or zero counts");
std::ostringstream saved; w->write_save(saved, WorldSaveFormat::Current15);
std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
require(resumed->custody_request((*completion)->request) == (*completion)->result, "merged historical effect changed after restore");
}
Test CustodyTests::blocked_return_retains_every_item() {
auto w = cabin(); ticks(*w, 16);
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
auto& store = const_cast<Storage&>(w->storages()[0]); store.capacity = 1;
ticks(*w, 40);
require(w->agents()[0].state == AgentState::Returning && w->agents()[0].execution &&
w->agents()[0].execution->blocked == CustodyStatus::NoDestination, "blocked return lost execution");
require(w->agents()[0].inventory.item_count(ItemType::Plank) == 2 &&
w->agents()[0].inventory.item_count(ItemType::StoneBlock) == 2, "partial return lost items");
auto id = w->add_storage({4, 3}, 20);
ticks(*w, 20);
require(w->agents()[0].inventory.empty() && w->find_storage(id)->total_items() == 4, "unblocked return incomplete");
}
Test CustodyTests::suspended_bed_and_loom_resume() {
World w(9, 20, 20, 1, ExecutionMode::SerialReference);
const auto store = w.add_storage({2, 2}, 30);
w.stock_storage(store, ItemType::Wood, 4); w.stock_storage(store, ItemType::Cloth, 2);
const auto actor = w.spawn_agent({2, 2}); (void)actor; w.start_scenario({8, 8});
require(w.apply_command({1, 1, CommandKind::PlaceBed, {4, 2}}).status == CommandStatus::Accepted, "bed placement refused");
const auto id = w.production_orders()[0].id;
for (int i = 0; i < 80 && w.find_production(id)->bed_stage == BedStage::Foundation; ++i) ticks(w, 1);
require(w.find_production(id)->bed_stage == BedStage::Bedding, "bed foundation absent");
require(w.cancel_production(id) == CommandStatus::Accepted && w.find_production(id)->suspended, "partial bed not suspended");
ticks(w, 20); require(!w.legacy_representable(), "suspended bed projected");
require(w.resume_production(id) == CommandStatus::Accepted, "resume refused");
ticks(w, 100); require(w.find_production(id)->state == JobState::Completed, "bed resumed wrong stage");
require(w.item_balances()[0].installation == 1 && w.item_balances()[5].installation == 2, "bed installed twice");
require(w.cancel_production(id) == CommandStatus::Busy, "completed bed canceled");
w.queue_production({6, 2}, RecipeId::WeaveCloth); const auto loom = w.production_orders().back().id;
require(w.cancel_production(loom) == CommandStatus::Accepted && w.find_production(loom)->suspended, "loom not retained");
w.stock_storage(store, ItemType::Flax, 1);
require(w.resume_production(loom) == CommandStatus::Accepted, "loom resume refused");
ticks(w, 60); require(w.find_storage(store)->item_count(ItemType::Cloth) == 1, "loom failed after resume");
}
Test CustodyTests::admission_exhaustion_and_receipt_eviction() {
auto w = cabin();
auto& actor = const_cast<Agent&>(w->agents()[0]); actor.next_admission = std::numeric_limits<std::uint64_t>::max();
ticks(*w, 2);
require(!actor.execution && w->custody_receipts().empty() && w->storages()[0].items[0].reserved == 0, "exhausted admission mutated stock");
World loom(1, 16, 16, 1, ExecutionMode::SerialReference);
const auto store = loom.add_storage({2, 2}, 4000); loom.stock_storage(store, ItemType::Flax, 3000);
(void)loom.spawn_agent({3, 2}); loom.queue_production({3, 2}, RecipeId::WeaveCloth);
loom.step(); auto first = *loom.custody_receipts()[0]; auto snapshot = loom.capture();
for (int i = 0; i < 26000; ++i) loom.step();
loom.validate_custody();
require(loom.custody_receipts().size() == custody_receipt_limit &&
loom.custody_request(first.request).status == CustodyStatus::Stale, "evicted admission not stale");
require(snapshot->custody_receipts()[0]->request == first.request && snapshot->custody_receipts()[0]->result == first.result,
"retained snapshot receipt mutated");
for (const auto& receipt : loom.custody_receipts()) require(loom.custody_request(receipt->request) == receipt->result, "retained replay differed");
}
Test CustodyTests::recipes_meals_and_harvest_balance() {
World w(1, 20, 20, 1, ExecutionMode::SerialReference);
const auto store = w.add_storage({2, 2}, 100);
const auto pantry = w.add_storage({2, 3}, 20, StorageKind::Pantry);
w.stock_storage(store, ItemType::Wood, 10); w.stock_storage(store, ItemType::Stone, 3);
w.stock_storage(pantry, ItemType::Berries, 4);
(void)w.spawn_agent({2, 2}); (void)w.add_resource_node({3, 3}, ItemType::Wood, 5);
w.queue_production({4, 2}, RecipeId::SawPlank); w.queue_production({5, 2}, RecipeId::CutStoneBlock);
w.enable_hunger(); ticks(w, 300);
require(w.meals_eaten() > 0 && w.item_balances()[0].harvest == 5 && w.item_balances()[0].recipe_input == 1 &&
w.item_balances()[2].recipe_output == 1 && w.item_balances()[3].recipe_output == 1, "recipe/source/sink path omitted");
}
Test CustodyTests::snapshot_metrics() {
for (bool full : {false, true}) {
World w(1, 512, 512, 1, ExecutionMode::SerialReference);
if (full) {
auto store = w.add_storage({1, 1}, 4000); w.stock_storage(store, ItemType::Flax, 3000);
(void)w.spawn_agent({2, 1}); w.queue_production({2, 1}, RecipeId::WeaveCloth);
for (int i = 0; i < 26000; ++i) w.step();
}
while (w.agents().size() < 500) (void)w.spawn_agent({1, 1});
for (int i = 0; i < 1000; ++i) {
auto store = w.add_storage({i % 500, i / 500 + 5}, 1000);
for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast<ItemType>(j) != ItemType::Berries)
w.stock_storage(store, static_cast<ItemType>(j), 1);
}
while (w.production_orders().size() < 2000) {
const auto i = static_cast<std::int32_t>(w.production_orders().size());
w.queue_production({i % 100 + 3, i / 100 + 10}, RecipeId::SawPlank);
}
w.validate_custody();
std::vector<double> samples;
for (int i = 0; i < 101; ++i) {
const auto begin = std::chrono::steady_clock::now(); auto snapshot = w.capture();
samples.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
}
std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes);
std::ostringstream modern; w.write_save(modern, WorldSaveFormat::Current15);
std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size()
<< " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << " raw15_bytes=" << modern.str().size()
<< " receipt_object_bytes=" << sizeof(CustodyReceipt) << '\n';
std::vector<double> validation, serialization, advancement;
for (int i = 0; i < 21; ++i) {
auto begin = std::chrono::steady_clock::now(); w.validate_custody();
validation.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
begin = std::chrono::steady_clock::now(); std::ostringstream encoded; w.write_save(encoded, WorldSaveFormat::Current15);
serialization.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
begin = std::chrono::steady_clock::now(); w.step();
advancement.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
}
w.validate_custody();
for (auto pair : {std::pair{"validate", &validation}, std::pair{"serialize15", &serialization}, std::pair{"step", &advancement}}) {
std::sort(pair.second->begin(), pair.second->end());
std::cout << "custody metrics initial_receipts=" << (full ? 4096 : 0) << ' ' << pair.first
<< "_ms_p50=" << (*pair.second)[10] << " p95=" << (*pair.second)[19] << '\n';
}
}
}
Test CustodyTests::rejects_missing_execution_and_claims() {
auto w = cabin(); ticks(*w, 1);
const auto rejects = [&] { try { w->validate_custody(); } catch (const std::runtime_error&) { return true; } return false; };
auto& actor = const_cast<Agent&>(w->agents()[0]); auto execution = actor.execution;
actor.execution.reset(); require(rejects(), "active actor without execution accepted"); actor.execution = execution;
actor.execution->reservations[0] = {}; require(rejects(), "missing material reservation accepted"); actor.execution = execution;
actor.execution->reservations[1].id = actor.execution->reservations[0].id;
require(rejects(), "duplicate claim ID accepted"); actor.execution = execution;
auto& order = const_cast<ProductionOrder&>(w->production_orders()[0]); ++order.materials[0].count;
require(rejects(), "different recipe quantity accepted"); --order.materials[0].count;
w->validate_custody();
}
Test CustodyTests::modern_roundtrip_cancel_and_exact_retry() {
auto w = cabin(); ticks(*w, 16);
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
std::ostringstream encoded; w->write_save(encoded, WorldSaveFormat::Current15);
std::istringstream input(encoded.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
for (const auto& receipt : w->custody_receipts()) require(resumed->custody_request(receipt->request) == receipt->result, "restored exact receipt differed");
std::ostringstream legacy;
bool refused = false; try { w->write_save(legacy); } catch (const UnsupportedLegacyState&) { refused = true; }
require(refused && legacy.str().empty(), "legacy refusal wrote bytes");
for (int i = 0; i < 40; ++i) {
ticks(*w, 1); ticks(*resumed, 1);
std::ostringstream a,b; w->write_save(a, WorldSaveFormat::Current15); resumed->write_save(b, WorldSaveFormat::Current15);
require(a.str() == b.str(), "modern return continuation changed");
}
}
Test CustodyTests::persistent_counter_boundaries_and_pending_completion() {
const auto restored_counter = [](const World& world, std::size_t counter, std::uint64_t value) {
std::ostringstream old, modern;
world.write_save(old, WorldSaveFormat::Current14); world.write_save(modern, WorldSaveFormat::Current15);
auto bytes = modern.str(); const auto offset = old.str().size() + counter * 8;
require(offset + 8 <= bytes.size(), "custody extension missing");
for (std::size_t i = 0; i < 8; ++i) bytes[offset + i] = static_cast<char>((value >> (i * 8)) & 255U);
std::istringstream input(bytes); return World::read_save(input, 1, ExecutionMode::SerialReference);
};
auto initial = cabin();
for (std::size_t counter = 0; counter < 3; ++counter) {
bool invalid = false; try { auto ignored = restored_counter(*initial, counter, 0); } catch (const std::runtime_error&) { invalid = true; }
require(invalid, "zero durable highwater accepted");
if (counter == 0) continue;
auto exhausted = restored_counter(*initial, counter, std::numeric_limits<std::uint64_t>::max());
ticks(*exhausted, 3);
require(!exhausted->agents()[0].execution && exhausted->custody_receipts().empty() &&
exhausted->storages()[0].items[0].reserved == 0, "exhausted admission acquired claims");
}
World saw(1, 10, 10, 1, ExecutionMode::SerialReference);
const auto store = saw.add_storage({2, 2}, 10); saw.stock_storage(store, ItemType::Wood, 1);
(void)saw.spawn_agent({3, 2}); saw.queue_production({3, 2}, RecipeId::SawPlank);
auto exhausted = restored_counter(saw, 0, std::numeric_limits<std::uint64_t>::max());
ticks(*exhausted, 12);
const auto& actor = exhausted->agents()[0];
require(actor.state == AgentState::Working && actor.work_remaining == 0 && actor.execution->blocked == CustodyStatus::Exhausted,
"completion did not preserve pending zero timer");
require(exhausted->storages()[0].item_count(ItemType::Wood) == 1 && exhausted->storages()[0].item_count(ItemType::Plank) == 0,
"refused completion partially consumed input");
const auto ordinal = actor.execution->next_operation;
ticks(*exhausted, 3);
require(actor.work_remaining == 0 && actor.execution->next_operation == ordinal + 3 && !exhausted->legacy_representable(),
"pending retry underflowed timer or reused ordinal");
std::ostringstream saved; exhausted->write_save(saved, WorldSaveFormat::Current15);
std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
ticks(*resumed, 1); require(resumed->agents()[0].work_remaining == 0, "restored pending completion decremented zero");
}
Test CustodyTests::resident_and_job_id_allocation_is_checked() {
const auto bytes = [](const World& world) { std::ostringstream stream; world.write_save(stream, WorldSaveFormat::Current15); return stream.str(); };
for (std::size_t kind = 0; kind < 2; ++kind) {
World empty(1, 10, 10, 1, ExecutionMode::SerialReference);
auto encoded = bytes(empty);
// Signature/version/seed/dimensions, five u64 counters, hunger flag.
const std::size_t offset = 28 + 5 * 8 + 1 + kind * 8;
for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = static_cast<char>(255);
std::istringstream input(encoded); auto restored = World::read_save(input, 1, ExecutionMode::SerialReference);
const auto before = bytes(*restored);
bool exhausted = false;
try { if (kind == 0) (void)restored->spawn_agent({1,1}); else (void)restored->add_job({1,1}, 1); }
catch (const std::overflow_error&) { exhausted = true; }
require(exhausted && bytes(*restored) == before, "exhausted resident/job allocation changed state");
for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = 0;
bool rejected = false; try { std::istringstream zero(encoded); auto ignored = World::read_save(zero,1,ExecutionMode::SerialReference); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected, "zero resident/job counter accepted");
const auto valid_before = bytes(empty);
try { if (kind == 0) (void)empty.spawn_agent({-1,-1}); else (void)empty.add_job({1,1}, 0); }
catch (const std::invalid_argument&) {}
require(bytes(empty) == valid_before, "invalid insertion consumed ID");
}
World idle(1, 10, 10, 1, ExecutionMode::SerialReference); (void)idle.spawn_agent({1,1});
const_cast<Agent&>(idle.agents()[0]).work_remaining = 1;
bool rejected = false; try { idle.validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
require(rejected, "idle timer escaped phase validation");
}
Test CustodyTests::retained_result_uniqueness_and_canonical_operands() {
auto w = cabin(); ticks(*w, 60);
require(!w->agents()[0].execution, "test requires retired transfer");
auto& receipts = const_cast<std::vector<std::shared_ptr<const CustodyReceipt>>&>(w->custody_receipts());
const auto rejects = [&](std::size_t index, auto mutation) {
const auto original = receipts[index];
auto modified = std::make_shared<CustodyReceipt>(*original);
mutation(*modified); receipts[index] = modified;
bool rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
receipts[index] = original;
require(rejected, "noncanonical historical result accepted"); w->validate_custody();
};
rejects(0, [](auto& r) { r.result.reservations[1] = r.result.reservations[0]; });
rejects(0, [](auto& r) { std::swap(r.result.reservations[0], r.result.reservations[1]); });
rejects(0, [](auto& r) { r.request.source = 1; });
const auto completion = std::find_if(receipts.begin(), receipts.end(), [](const auto& r) { return r->request.operation == CustodyOperation::Complete; });
require(completion != receipts.end() && (*completion)->result.effect_count == 2, "missing multi-input completion");
const auto index = static_cast<std::size_t>(completion - receipts.begin());
rejects(index, [](auto& r) { r.result.effects[1] = r.result.effects[0]; });
rejects(index, [](auto& r) { r.result.effects[1] = r.result.effects[0]; r.result.effects[1].count = 1; });
rejects(index, [](auto& r) { r.request.source = 1; });
require(w->custody_request((*completion)->request) == (*completion)->result, "valid retired result no longer replays");
}
Test CustodyTests::merged_carpentry_effects_keep_distinct_owners() {
World world(3, 20, 20, 1, ExecutionMode::SerialReference);
const auto first = world.add_storage({3,3}, 10), second = world.add_storage({5,3}, 10);
world.stock_storage(first, ItemType::Wood, 1); world.stock_storage(second, ItemType::Wood, 1);
const auto actor = world.spawn_agent({1,3}); world.start_scenario({8,3});
require(world.apply_command({1,1,CommandKind::AssignProfession,{},static_cast<std::uint8_t>(Profession::Carpenter),{},actor}).status == CommandStatus::Accepted,
"carpenter setup refused");
world.queue_production({8,3}, RecipeId::CraftWoodenDoor);
const auto production = world.production_orders()[0].id;
for (int i = 0; i < 80 && world.find_production(production)->state != JobState::Completed; ++i) ticks(world,1);
require(world.find_production(production)->state == JobState::Completed, "two-source carpenter did not complete");
const auto completion = std::find_if(world.custody_receipts().begin(), world.custody_receipts().end(),
[](const auto& r) { return r->request.operation == CustodyOperation::Complete; });
require(completion != world.custody_receipts().end() && (*completion)->result.effect_count == 2, "merged carpenter input duplicated");
const auto& input = (*completion)->result.effects[0]; const auto& output = (*completion)->result.effects[1];
require(input.owner == StockOwner{OwnerKind::Production,production} && input.item == ItemType::Wood && input.count == 0 &&
output.owner == StockOwner{OwnerKind::Resident,actor} && output.item == ItemType::WoodenDoor && output.count == 1 && input.stack != output.stack,
"consumed site input or distinct resident output lost");
std::ostringstream saved; world.write_save(saved, WorldSaveFormat::Current15);
std::istringstream bytes(saved.str()); auto restored = World::read_save(bytes,1,ExecutionMode::SerialReference);
require(restored->custody_request((*completion)->request) == (*completion)->result, "carpentry result changed after restore");
ticks(*restored, 20);
}
Test CustodyTests::active_terminal_and_delivery_phase_are_rejected() {
auto w = cabin(); ticks(*w, 1);
auto& actor = const_cast<Agent&>(w->agents()[0]);
require(actor.state == AgentState::FetchingMaterials, "test needs uncollected first stop");
actor.state = AgentState::Travelling;
bool rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
actor.state = AgentState::FetchingMaterials;
require(rejected, "delivery source stop allowed generic Travelling transition");
ticks(*w, 1);
auto& receipts = const_cast<std::vector<std::shared_ptr<const CustodyReceipt>>&>(w->custody_receipts());
const auto index = receipts.size() - 1; const auto original = receipts[index];
require(original->request.operation == CustodyOperation::Pickup && actor.execution, "test needs active pickup receipt");
auto altered = std::make_shared<CustodyReceipt>(*original); altered->result.terminal = true; receipts[index] = altered;
rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
receipts[index] = original;
require(rejected, "active pickup was allowed to terminate transfer history");
ticks(*w, 60);
receipts[index] = altered;
rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
receipts[index] = original;
require(rejected, "retired history accepted premature pickup terminal"); w->validate_custody();
}
Test CustodyTests::harvest_source_and_return_capacity_are_required_by_phase() {
World harvest(1,10,10,1,ExecutionMode::SerialReference);
(void)harvest.add_storage({4,3},10); (void)harvest.add_resource_node({2,3},ItemType::Wood,2);
(void)harvest.spawn_agent({2,3}); ticks(harvest,1);
auto& actor = const_cast<Agent&>(harvest.agents()[0]);
auto& node = const_cast<ResourceNode&>(harvest.resource_nodes()[0]);
const auto original = actor; const auto original_node = node;
require(actor.state == AgentState::Gathering, "test needs live gather phase");
actor.resource_node_id = 0; actor.execution->source = 0;
for (auto& claim : actor.execution->reservations) if (claim.kind == ReservationKind::Harvest) claim = {};
node.reserved_workers = 0;
bool rejected = false; try { harvest.validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
actor = original; node = original_node;
require(rejected, "gathering with no source or source claim was accepted"); ticks(harvest,10);
auto returning = cabin(); ticks(*returning,16);
require(returning->cancel_production(returning->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
auto& carrier = const_cast<Agent&>(returning->agents()[0]); auto& store = const_cast<Storage&>(returning->storages()[0]);
carrier.execution->destination = store.id; carrier.execution->reservation_count = 1;
carrier.execution->reservations[0] = {1,ReservationKind::Capacity,{OwnerKind::Storage,store.id},0,{},1};
++store.reserved_slots;
rejected = false; try { returning->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
carrier.execution->destination = 0; carrier.execution->reservation_count = 0; carrier.execution->reservations[0] = {}; --store.reserved_slots;
require(rejected, "cancellation return kept a destination capacity claim"); ticks(*returning,40);
}
}
+7
View File
@@ -0,0 +1,7 @@
# Frozen schema 2 migration corpus
`fixtures.hpp` contains 13 authentic checkpoints and FNV-1a hashes of 80 subsequent raw13 states for each. They were emitted by `capture.cpp`, compiled exclusively against source and headers at `f6493e2d1cdb9e07eb18b9901fd8878b5d3fa51e`, using the pinned VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, Windows x64 GCC 16.2 and Wine 11. Each fixture includes its full SHA-256. These bytes were captured before the custody implementation and are never regenerated by the current writer.
Seed is 43. UUID is `91020304-0506-4708-890a-0b0c0d0e0f10`, city 7, built-in rules. The probe records exact states before pickup, between stops, approaching the worksite, Working with implicit consumed delivery, three direct recipes, finished carpenter cargo without a production link, harvesting, harvested cargo, both meal phases and tending. The `.continuation13` probe output stores 80 length-prefixed raw13 frames (32-bit little-endian lengths).
Reproduce in a separate historical checkout at that exact commit, build its `settlement_core`, then compile this probe with that checkout's headers and library. Pass an existing directory prefix including its trailing separator. Do not use current headers or objects with the historical probe. The generated fixture header retains only checkpoints and per-tick hashes; complete raw frames and build logs are verification artifacts outside the repository.
+59
View File
@@ -0,0 +1,59 @@
#include "settlement/core/checkpoint.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <set>
using namespace settlement;
constexpr Void::Uuid::Uuid uuid{{0x91,2,3,4,5,6,0x47,8,0x89,10,11,12,13,14,15,16}};
std::string prefix;
void capture(const World& world, const std::string& name) {
auto rules=default_rules_manifest(); auto data=encode_checkpoint(world,uuid,7,*rules);
if(!data) throw std::runtime_error(data.error().message);
std::ofstream(prefix+name+".checkpoint",std::ios::binary).write(data->data(),data->size());
std::ofstream raw(prefix+name+".raw14",std::ios::binary); world.write_save(raw,WorldSaveFormat::Current14);raw.close();
std::ofstream legacy(prefix+name+".raw13",std::ios::binary); world.write_save(legacy,WorldSaveFormat::Legacy13);legacy.close();
const auto&a=world.agents().front();
std::cout<<name<<" tick="<<world.tick()<<" agent_state="<<int(a.state)<<" production="<<a.production_id<<" inventory=";
for(unsigned i=1;i<=item_type_count;++i)std::cout<<a.inventory.item_count(ItemType(i))<<',';
std::cout<<" stops="<<(world.production_orders().empty()?0:world.production_orders().front().delivery_stops.size())<<"\n";
std::ostringstream frozen(std::ios::binary); world.write_save(frozen,WorldSaveFormat::Current14); std::istringstream input(frozen.str(),std::ios::binary); auto copy=World::read_save(input,1,ExecutionMode::SerialReference); std::ofstream continuation(prefix+name+".continuation13",std::ios::binary);
for(unsigned i=0;i<80;++i){std::ostringstream frame(std::ios::binary); copy->write_save(frame,WorldSaveFormat::Legacy13); const auto bytes=frame.str(); std::uint32_t count=bytes.size(); continuation.write(reinterpret_cast<const char*>(&count),4); continuation.write(bytes.data(),bytes.size()); copy->step();}
}
int main(int argc,char**argv){
if(argc!=2)return 2;prefix=argv[1];
World w(43,20,8,1,ExecutionMode::SerialReference);
auto a=w.add_storage({3,3},20),b=w.add_storage({8,3},20);
w.stock_storage(a,ItemType::Plank,3);w.stock_storage(b,ItemType::StoneBlock,2);
(void)w.spawn_agent({1,3}); w.queue_production({14,3},RecipeId::BuildCabin);
std::set<std::string> seen;
for(unsigned i=0;i<80;++i){w.step();const auto&agent=w.agents().front();const auto&o=w.production_orders().front();
std::string name;
if(agent.state==AgentState::FetchingMaterials)name="cabin-before-pickup";
if(agent.state==AgentState::Hauling&&o.collected_stops==1)name="cabin-between-stops";
if(agent.state==AgentState::Hauling&&o.collected_stops==2)name="cabin-to-site";
if(agent.state==AgentState::Working)name="cabin-working";
if(!name.empty()&&seen.insert(name).second)capture(w,name);
}
for(auto recipe:{RecipeId::SawPlank,RecipeId::CutStoneBlock,RecipeId::WeaveCloth}){
World d(43,20,8,1,ExecutionMode::SerialReference);auto s=d.add_storage({3,3},20);
d.stock_storage(s,recipe==RecipeId::SawPlank?ItemType::Wood:recipe==RecipeId::CutStoneBlock?ItemType::Stone:ItemType::Flax,1);
(void)d.spawn_agent({2,3});d.queue_production({6,3},recipe);
for(int i=0;i<40;++i){d.step();if(d.agents().front().state==AgentState::Working){capture(d,"direct-"+std::to_string(int(recipe)));break;}}
}
World c(43,24,24,1,ExecutionMode::SerialReference);c.start_scenario({2,2});auto s=c.add_storage({3,3},20);c.stock_storage(s,ItemType::Wood,5);
const auto carpenter=c.spawn_agent({2,3}); (void)c.apply_command({1,1,CommandKind::AssignProfession,{},static_cast<std::uint8_t>(Profession::Carpenter),{},carpenter});c.queue_production(*c.carpenter_workshop(),RecipeId::CraftWoodenDoor);
for(int i=0;i<120;++i){c.step();if(c.agents().front().state==AgentState::Hauling&&c.agents().front().production_id==0&&c.agents().front().inventory.item_count(ItemType::WoodenDoor)){capture(c,"carpenter-output");break;}}
World h(43,20,8,1,ExecutionMode::SerialReference);(void)h.add_storage({14,3},20);(void)h.add_resource_node({3,3},ItemType::Wood,1);(void)h.spawn_agent({1,3});
bool gathering=false,hauling=false;
for(int i=0;i<60;++i){h.step();if(!gathering&&h.agents().front().state==AgentState::Gathering){capture(h,"harvest-gathering");gathering=true;}if(!hauling&&h.agents().front().state==AgentState::Hauling){capture(h,"harvest-hauled");hauling=true;}}
World m(43,20,8,1,ExecutionMode::SerialReference);auto pantry=m.add_storage({14,3},20,StorageKind::Pantry);m.stock_storage(pantry,ItemType::Berries,5);(void)m.spawn_agent({1,3});m.enable_hunger();
bool going=false,eating=false;
for(int i=0;i<220;++i){m.step();if(!going&&m.agents().front().state==AgentState::GoingToEat){capture(m,"meal-going");going=true;}if(!eating&&m.agents().front().state==AgentState::Eating){capture(m,"meal-eating");eating=true;}}
World t(43,20,8,1,ExecutionMode::SerialReference);t.start_scenario({2,2});(void)t.spawn_agent({1,3});(void)t.apply_command({1,1,CommandKind::PlaceTreePlot,{5,3}});
bool tending=false;
for(int i=0;i<60;++i){t.step();if(t.agents().front().state==AgentState::Gathering&&t.agents().front().storage_id==0){capture(t,"tending");tending=true;break;}}
return seen.size()==4&&gathering&&hauling&&going&&eating&&tending?0:3;
}
+541
View File
@@ -0,0 +1,541 @@
// Frozen output of f6493e2d1cdb9e07eb18b9901fd8878b5d3fa51e; see capture.cpp.
#pragma once
#include <array>
#include <cstdint>
#include <string_view>
namespace custody_v14 {
struct Fixture { std::string_view name, sha256, checkpoint; std::array<std::uint64_t,80> ticks; };
inline constexpr std::array<Fixture,13> fixtures{{
{"cabin-before-pickup", "6fb53ddaf7d666a5e5b0e899ffbad1d7137dea4e7a037fcf824f521cf5f0b531",
"53544843484b505402000000b6000000cf020000000000009102030405064708890a0b0c0d0e0f1007000000000000000100"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000001000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000002000000030000000500000000"
"00000000020000000200000003000000030000000300000001000000000000001c0000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0100000000000000000000000000000000000000000002000000010000000000000003000000030000001400000000000000"
"0001000000030300000003000000020000000000000008000000030000001400000000000000000100000004020000000200"
"00000100000001000000000000000e0000000300000002010200000001000000000000000303000000020000000000000004"
"0200000002000000010000000000000005000000040000000300000005000000030000000600000003000000070000000300"
"0000080000000300000002000000000000000600000009000000030000000a000000030000000b000000030000000c000000"
"030000000d000000030000000e00000003000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000089063e25ca59b04935ace8779f45e200ab2acbca2dc88fec7e"
"c5f3504eda9248"
, {
0x599836ebcd30a29fULL, 0xcaac4531bb7bcf12ULL, 0xe100830a1464be03ULL, 0x027cbdd51f3b01c8ULL,
0x1df54a0c813e02d9ULL, 0x770d4f71d98b81f6ULL, 0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL,
0x8373c6a20d010194ULL, 0xadddce31831e3cabULL, 0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL,
0x2b7379835239007dULL, 0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL,
0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL,
0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL,
0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL,
0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL,
0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL,
0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL,
0x6681875fe5343f60ULL, 0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL,
0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL,
0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL,
0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL,
0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL,
0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL,
0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL,
0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL,
0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL,
0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL,
}},
{"cabin-between-stops", "daca83d48f48b53f986305655017c01e4d40a73e7085d81088e5f71f7073ef4b",
"53544843484b505402000000b6000000b6020000000000009102030405064708890a0b0c0d0e0f1007000000000000000200"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000002000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000400000000"
"0000000005000000040000000300000005000000030000000600000003000000070000000300000008000000030000000000"
"0000000000001c00000000000000000000000000000000000000000000000000000003000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000002000000"
"0100000000000000030000000300000014000000000000000000000000020000000000000008000000030000001400000000"
"00000000010000000402000000020000000100000001000000000000000e0000000300000002010200000001000000000000"
"0003030000000200000000000000040200000002000000010000000000000000000000020000000000000006000000090000"
"00030000000a000000030000000b000000030000000c000000030000000d000000030000000e000000030000000100000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"bfc296aeae849041ff62087240ac2f981e75d1791610f8f7c3bcc5e9792e6320"
, {
0xcaac4531bb7bcf12ULL, 0xe100830a1464be03ULL, 0x027cbdd51f3b01c8ULL, 0x1df54a0c813e02d9ULL,
0x770d4f71d98b81f6ULL, 0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL, 0x8373c6a20d010194ULL,
0xadddce31831e3cabULL, 0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL, 0x2b7379835239007dULL,
0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, 0xc3565d7aa175849dULL,
0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, 0x94f2e4644ed7432dULL,
0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, 0xdbb636c9dfd9f8edULL,
0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, 0x8e8a57a7244dff5dULL,
0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, 0xacd686b3f070f03dULL,
0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, 0x0964e2e7b7e27f6dULL,
0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, 0x6681875fe5343f60ULL,
0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, 0x44d6d03be494df34ULL,
0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, 0x75f2d8f87f7c8c38ULL,
0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL, 0x6f153cf79c35aaecULL,
0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, 0xdf427bdce3116ed0ULL,
0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, 0x94a094811f7cac64ULL,
0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, 0x1c546b250c06f528ULL,
0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, 0x1576cf2428c013dcULL,
0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, 0xf523c5258eda5e80ULL,
0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, 0xd3790e018e3afe54ULL,
0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, 0x049516be2922ab58ULL,
}},
{"cabin-to-site", "86b61386600533badf032b4a17ac75c38a302f4c2b78fed37a38a76232360178",
"53544843484b505402000000b600000085020000000000009102030405064708890a0b0c0d0e0f1007000000000000000700"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000007000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000008000000030000000400000000"
"000000000600000009000000030000000a000000030000000b000000030000000c000000030000000d000000030000000e00"
"00000300000000000000000000001c0000000000000000000000000000000000000000000000000000000300000002000000"
"0000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000"
"0000000002000000010000000000000003000000030000001400000000000000000000000002000000000000000800000003"
"000000140000000000000000000000000100000001000000000000000e000000030000000201020000000100000000000000"
"0303000000020000000000000004020000000200000001000000000000000000000002000000000000000000000002000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"00232dd846a1a33102aa254a632f5ad28dd7c9da49baab15e4af6c417b21fe8b28"
, {
0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL, 0x8373c6a20d010194ULL, 0xadddce31831e3cabULL,
0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL, 0x2b7379835239007dULL, 0xb581902af1f964a5ULL,
0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, 0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL,
0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, 0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL,
0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, 0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL,
0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, 0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL,
0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, 0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL,
0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, 0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL,
0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, 0x6681875fe5343f60ULL, 0xe9be99df149af205ULL,
0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, 0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL,
0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, 0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL,
0x259190664a78239aULL, 0x324e15c71a395c77ULL, 0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL,
0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, 0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL,
0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, 0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL,
0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, 0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL,
0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, 0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL,
0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, 0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL,
0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, 0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL,
0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, 0x049516be2922ab58ULL, 0x517ac5f58978ba7dULL,
0xb433ce2bf41e42baULL, 0xc0f0538cc3df7b97ULL, 0xfdb77abd45dbca0cULL, 0x2fd00ed188d95a51ULL,
}},
{"cabin-working", "f443380bc6ff9c74d2a24d80d0261b6cd9f7560796ae76548f2b7aa24e3ef505",
"53544843484b505402000000b60000003d020000000000009102030405064708890a0b0c0d0e0f1007000000000000000d00"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b0000000000000014000000080000000d000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000100000001000000000000000e000000030000000200000000"
"000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000"
"0000000000000200000001000000000000000300000003000000140000000000000000000000000200000000000000080000"
"0003000000140000000000000000000000000100000001000000000000000e00000003000000020102000000010000000000"
"0000030300000002000000000000000402000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000009318a0b695a881878b8800d4ac312fa11b89fe3b0"
"62514839b4bc0b5ac25594"
, {
0x2b7379835239007dULL, 0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL,
0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL,
0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL,
0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL,
0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL,
0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL,
0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL,
0x6681875fe5343f60ULL, 0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL,
0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL,
0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL,
0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL,
0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL,
0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL,
0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL,
0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL,
0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL,
0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL,
0x049516be2922ab58ULL, 0x517ac5f58978ba7dULL, 0xb433ce2bf41e42baULL, 0xc0f0538cc3df7b97ULL,
0xfdb77abd45dbca0cULL, 0x2fd00ed188d95a51ULL, 0xad56322b10d7616eULL, 0x8e557f49ef6553bbULL,
0x6de4b9a28cb78df0ULL, 0x60a1833ddb5cc755ULL, 0xa2f7aabb8d634dd2ULL, 0xc918d2f939ee65afULL,
}},
{"carpenter-output", "6a401e39d87c97a16fbe4e7bc4a5d7cc88f6f26b176b2551102e66aa14ace446",
"53544843484b505402000000b6000000bf030000000000009102030405064708890a0b0c0d0e0f1007000000000000001100"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000180000001800000011000000000000000400000000000000"
"0b00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000000"
"0000000200000002000000040000000000000000020000000300000002000000030000000300000000000000000000000000"
"0000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000001000000"
"0000000000000000000000000000000000000000000000003600110000050000000000000000010000000100000000000000"
"0300000003000000140000000100000000010000000103000000000000000100000001000000000000000200000002000000"
"0e02000000000000000000000000000000000000000000000000000001000000020000000200000001000000000000000000"
"000000000000010000000000000001abbc5e54e4c970fef93640a799432f9b3e1e0a0c462351d36c6d1bb3992b331b"
, {
0xa6ec0093d932ebd8ULL, 0x87baf2e646efc9a5ULL, 0x1ab6ff5ac2d06a08ULL, 0x5b21ac6329697a51ULL,
0x892f269f06860362ULL, 0x0ce6c8acfd0548abULL, 0x10128ab0047f29e4ULL, 0xcc8b9971929bb83dULL,
0xb18f7c65729d2eaeULL, 0x6cff10cc2991c957ULL, 0xee671e7028e38f80ULL, 0x836fd8346ea210a9ULL,
0x3b1e5c33e40d38baULL, 0xe2891c128cba04c3ULL, 0xab7996b49c542e9cULL, 0xfce08ee5878a2fb5ULL,
0xc8857c8fb93a4a66ULL, 0x5bcafda5a7a0d4cfULL, 0x9068789e8a217ab8ULL, 0x731f33f4164b9621ULL,
0xb33de24022b9c652ULL, 0x6bd1afe2193ce33bULL, 0xa1f25e81be2bc454ULL, 0x401ed1b4b68ba8cdULL,
0xbf6fdd789c7567deULL, 0x277fa8b37cd738a7ULL, 0xe79f2e754b0372b0ULL, 0x5e5b4caafb0549f9ULL,
0xede1e8920bdd2beaULL, 0x2545a8b9b6961593ULL, 0x68186f9c92fabe0cULL, 0xd7cc035c13ed6905ULL,
0x85245577afe0d9d6ULL, 0x0bf76d05f70a191fULL, 0x016493e3d5aabc68ULL, 0x4e0aa86aa2aecf71ULL,
0x6fdcbb28196055c2ULL, 0xb6fb2618e466474bULL, 0x68e55ff0b8ae7ec4ULL, 0x61f7a5cf724460ddULL,
0x0a6251a626cc838eULL, 0x026b1d2a093a71f7ULL, 0xe1501a77a228e4a0ULL, 0x7658d43be7e765c9ULL,
0x2e07583b5d528ddaULL, 0xd572181a05ff59e3ULL, 0xb30ae3ca1d51d9bcULL, 0xca772914473b3355ULL,
0x03131d7a6972f2c6ULL, 0x296197d46751d86fULL, 0xcaf619893a5a2318ULL, 0x71139dc19b0aeac1ULL,
0x443b4551b6f17632ULL, 0x69c619af9dfc37dbULL, 0xac222fcda9561bb4ULL, 0x86e7da1dcd2f53edULL,
0x3bc4ef7c28f4c1beULL, 0xe06df1d434cfe647ULL, 0x275b095bac0978d0ULL, 0x9e1727915c0b5019ULL,
0x34aaf0fb2280d70aULL, 0x6c0eb122cd39c0b3ULL, 0xaee17805a99e692cULL, 0xa5629d8ad39e6ca5ULL,
0xbfb1f66260198236ULL, 0x90b9689924d6c63fULL, 0x0b94652fc0d513c8ULL, 0x4bff1238276e2411ULL,
0x00da1e39ad9805a2ULL, 0x8491c047a4174aebULL, 0xe53a71f4452dd8a4ULL, 0x1ae5eef02a3d0e7dULL,
0x86b763a9b34bdd6eULL, 0xbb59664ac1331f97ULL, 0x9a3e63985a219240ULL, 0x2f471d5c9fe01369ULL,
0x2bfbc208e211e27aULL, 0xd36681e78abeae83ULL, 0xf9d3ec3333f584dcULL, 0x170e96d694ff8575ULL,
}},
{"direct-0", "ae9fb9da88ee94c6e06905ab4dbedc291ad42fd81dfd8f5e7c1d23ffbe5b0ad4",
"53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000"
"0500000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000"
"0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000b00"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000"
"0300000003000000140000000000000000010000000101000000010000000100000001000000000000000600000003000000"
"0001010000000100000000000000010100000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000007a31faff08de99b99ec1e7f1a71b99f6c6bbf004087d"
"dd0b81acf4ca14acd130"
, {
0xcb3aa5dfb03965c9ULL, 0xeabf911762701811ULL, 0x3267ff311c8f5285ULL, 0xc9a54b382b66e91dULL,
0x3eadc9b41b6a79c1ULL, 0x88d52de6de23fa69ULL, 0xda6625e9c8402245ULL, 0xdf431e91a4cc8a4dULL,
0x88968629292726d9ULL, 0x90616d8a80511ad1ULL, 0xefc3df7a957d1395ULL, 0x1e8ec6e4dc12bf8eULL,
0xdaf77dfbd58cb967ULL, 0x611d034605ba46f0ULL, 0x2fe16de272eb1379ULL, 0xd3cfbd66bb79843aULL,
0x91b047e412719a33ULL, 0x1a8b985c61eb123cULL, 0xf23946c97dcc7825ULL, 0x3f4e05a9cdb2c0f6ULL,
0xbcc048eb14dcb00fULL, 0x08ff6dc7f49a22f8ULL, 0x4b90993f02ab24c1ULL, 0xb5988855fac97ae2ULL,
0x737912d351c190dbULL, 0xfc54634ba13b08e4ULL, 0xd40211b8bd1c6ecdULL, 0x2116d0990d02b79eULL,
0x514c488aa75ce6b7ULL, 0x63a50cfa36aa3f00ULL, 0xa636387144bb40c9ULL, 0xd657c71aec697c4aULL,
0x9438519843619243ULL, 0x1d13a21092db0a4cULL, 0xf4c1507daebc7035ULL, 0xb5a2d0389f82ee46ULL,
0x33151379e6acdd5fULL, 0x7f543856c66a5048ULL, 0x4e18a2f3339b1cd1ULL, 0xb820920a2bb972f2ULL,
0x76011c8782b188ebULL, 0xfedc6cffd22b00f4ULL, 0xd68a1b6cee0c66ddULL, 0x976b9b27ded2e4eeULL,
0x53d4523ed84cdec7ULL, 0xd9f9d789087a6c50ULL, 0xa8be422575ab38d9ULL, 0x4cac91a9be39a99aULL,
0x0a8d1c271531bf93ULL, 0x93686c9f64ab379cULL, 0x6b161b0c808c9d85ULL, 0xb82ad9ecd072e656ULL,
0x359d1d2e179cd56fULL, 0x81dc420af75a4858ULL, 0xc46d6d82056b4a21ULL, 0x2e755c98fd89a042ULL,
0xec55e7165481b63bULL, 0x7531378ea3fb2e44ULL, 0x4cdee5fbbfdc942dULL, 0x99f3a4dc0fc2dcfeULL,
0xe6b5cbc19f1c7697ULL, 0xf90e90312e69cee0ULL, 0x3b9fbba83c7ad0a9ULL, 0x6bc14a51e4290c2aULL,
0x29a1d4cf3b212223ULL, 0xb27d25478a9a9a2cULL, 0x8a2ad3b4a67c0015ULL, 0x4b0c536f97427e26ULL,
0xc87e96b0de6c6d3fULL, 0x14bdbb8dbe29e028ULL, 0xe382262a2b5aacb1ULL, 0x4d8a1541237902d2ULL,
0x0b6a9fbe7a7118cbULL, 0x9445f036c9ea90d4ULL, 0x6bf39ea3e5cbf6bdULL, 0x2cd51e5ed69274ceULL,
0xe93dd575d00c6ea7ULL, 0x6f635ac00039fc30ULL, 0x3e27c55c6d6ac8b9ULL, 0xe21614e0b5f9397aULL,
}},
{"direct-1", "452313012591f9337c1410095355887d778a47c225d09b3fe550d9f8ec2cc67a",
"53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000"
"0500000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000"
"0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000f00"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000"
"0300000003000000140000000000000000010000000201000000010000000100000001000000000000000600000003000000"
"0101010000000100000000000000020100000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000d4e59fb1f410d7b6ab8e531ff066559d5d44677d61c6"
"544d069a18fd0269e030"
, {
0x37ae3152f9978e76ULL, 0x57331c8aabce40beULL, 0x1351af3574563b7aULL, 0xaa8efb3c832dd212ULL,
0xc09abf5a0172a736ULL, 0xdfcf4f278ad81e4eULL, 0xa5d66bbb835d0672ULL, 0xd5a638c8993d780aULL,
0xf50a119c72854f86ULL, 0xfcd4f8fdc9af437eULL, 0xd0ad8f7eed43fc8aULL, 0x5030d7afa10ed4d2ULL,
0x3d54d6a175847066ULL, 0x44cf6298a3dd292eULL, 0x0ad67f2c9c621152ULL, 0xcd445e1c36765956ULL,
0x1d1b333928ab77cbULL, 0x8f20ad074bb134a4ULL, 0xf8c4a61402cfa309ULL, 0x2f038e4a264230aaULL,
0x29580d1fd74f61dfULL, 0x9c67a99332277128ULL, 0x5bdb109eaa1bb50dULL, 0xaf0d290b75c64ffeULL,
0xfee3fe2867fb6e73ULL, 0x70e977f68b012b4cULL, 0xda8d7103421f99b1ULL, 0x10cc593965922752ULL,
0xbde40cbf69cf9887ULL, 0xf70d48c574378d30ULL, 0xb680afd0ec2bd115ULL, 0xcfcc67d067665166ULL,
0x1fa33ced599b6fdbULL, 0x91a8b6bb7ca12cb4ULL, 0xfb4cafc833bf9b19ULL, 0xa55858d8f8125dfaULL,
0x9facd7aea91f8f2fULL, 0x12bc742203f79e78ULL, 0x5e631a52db0bad1dULL, 0xb19532bfa6b6480eULL,
0x016c07dc98eb6683ULL, 0x737181aabbf1235cULL, 0xdd157ab7730f91c1ULL, 0x872123c8376254a2ULL,
0xc06c16739abf9097ULL, 0x6d6213544607ba80ULL, 0xb908b9851d1bc925ULL, 0x4621325f39367eb6ULL,
0x95f8077c2b6b9d2bULL, 0x07fd814a4e715a04ULL, 0x71a17a57058fc869ULL, 0xa7e0628d2902560aULL,
0xa234e162da0f873fULL, 0x15447dd634e79688ULL, 0xd4b7e4e1acdbda6dULL, 0x27e9fd4e7886755eULL,
0x77c0d26b6abb93d3ULL, 0xe9c64c398dc150acULL, 0x536a454644dfbf11ULL, 0x89a92d7c68524cb2ULL,
0x534d8ff6618f2867ULL, 0x8c76cbfc6bf71d10ULL, 0x4bea3307e3eb60f5ULL, 0x6535eb075f25e146ULL,
0xb50cc024515affbbULL, 0x271239f27460bc94ULL, 0x90b632ff2b7f2af9ULL, 0x3ac1dc0fefd1eddaULL,
0x35165ae5a0df1f0fULL, 0xa825f758fbb72e58ULL, 0xf3cc9d89d2cb3cfdULL, 0x46feb5f69e75d7eeULL,
0x96d58b1390aaf663ULL, 0x08db04e1b3b0b33cULL, 0x727efdee6acf21a1ULL, 0x1c8aa6ff2f21e482ULL,
0x55d599aa927f2077ULL, 0x02cb968b3dc74a60ULL, 0x4e723cbc14db5905ULL, 0xdb8ab59630f60e96ULL,
}},
{"direct-4", "34fddc7587d05b995c207d9db896146154ace52dc152e62004efac370c1258ec",
"53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000200000000000000"
"0900000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000"
"0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000b00"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000"
"0300000003000000140000000000000000010000000701000000010000000100000001000000000000000600000003000000"
"0401010000000100000000000000070100000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000db4ee0a01a3bdbe2c73bce9fb3c27baca13e5aaa12a1"
"d06e25ec370dcebd6e75"
, {
0x390c415e34d0166aULL, 0x554a4dca2da2d072ULL, 0x0a6d78876d939f76ULL, 0x3746c232f2e153feULL,
0x1dac5cc0bc01befaULL, 0x2230655659c7bab2ULL, 0xc98216266ea8b8ceULL, 0xcb18300291d12896ULL,
0x8c028e6e517d8faaULL, 0x15e0477b18051b22ULL, 0xcb03723857f5ea26ULL, 0x550bb6fd219fa238ULL,
0x6cf696b2deed2d21ULL, 0xb5fe1220613db27aULL, 0x134d258ced91df3bULL, 0xca82240862b0591cULL,
0x9e3eceaeb9118035ULL, 0xf8bc7d34089f3e3eULL, 0xd1d2bf535ea84f7fULL, 0xb666fe781169bcf0ULL,
0x0e2358ec20130a79ULL, 0x572ad459a2638fd2ULL, 0xb479e7c62eb7bc93ULL, 0x6baee641a3d63674ULL,
0x3f6b90e7fa375d8dULL, 0x6002defff95500f6ULL, 0xace5e1f9f03e4777ULL, 0x5793c0b1528f9a48ULL,
0xe34b6141b0bd5a71ULL, 0xb8861bd4922daa8aULL, 0x15d52f411e81d74bULL, 0xcd0a2dbc93a0512cULL,
0xa0c6d862ea017845ULL, 0xfb4486e8398f364eULL, 0x482789e230787ccfULL, 0x2cbbc906e339ea40ULL,
0x8478237af1e337c9ULL, 0x59b2de0dd35387e2ULL, 0xb701f17a5fa7b4a3ULL, 0x6e36eff5d4c62e84ULL,
0x41f39a9c2b27559dULL, 0xd657a98ecb252e46ULL, 0xaf6debae212e3f87ULL, 0xcde88b40245fc798ULL,
0xe5d36af5e1ad5281ULL, 0x2edae66363fdd7daULL, 0x8c29f9cff052049bULL, 0x435ef84b65707e7cULL,
0x171ba2f1bbd1a595ULL, 0x719951770b5f639eULL, 0x4aaf9396616874dfULL, 0x2f43d2bb1429e250ULL,
0x87002d2f22d32fd9ULL, 0xd007a89ca523b532ULL, 0x2d56bc093177e1f3ULL, 0xe48bba84a6965bd4ULL,
0xb848652afcf782edULL, 0xd8dfb342fc152656ULL, 0x25c2b63cf2fe6cd7ULL, 0xd07094f4554fbfa8ULL,
0x78b4e478a87cea51ULL, 0x4def9f0b89ed3a6aULL, 0xab3eb2781641672bULL, 0x6273b0f38b5fe10cULL,
0x36305b99e1c10825ULL, 0x90ae0a1f314ec62eULL, 0xdd910d1928380cafULL, 0xc2254c3ddaf97a20ULL,
0x19e1a6b1e9a2c7a9ULL, 0xef1c6144cb1317c2ULL, 0x4c6b74b157674483ULL, 0x03a0732ccc85be64ULL,
0xd75d1dd322e6e57dULL, 0x6bc12cc5c2e4be26ULL, 0x44d76ee518edcf67ULL, 0x63520e771c1f5778ULL,
0x7b3cee2cd96ce261ULL, 0xc444699a5bbd67baULL, 0x21937d06e811947bULL, 0xd8c87b825d300e5cULL,
}},
{"harvest-gathering", "2983ac00f777101dd7d71bd7379764ac32aa2330608fed9a4bf4dc1f2ee01426",
"53544843484b505402000000b600000069020000000000009102030405064708890a0b0c0d0e0f1007000000000000000200"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000002000000000000000200000000000000"
"0f00000000000000000000000000000000000000000000000002000000000000000100000000000000020000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000300000000"
"0000000002000000020000000300000003000000030000000200000000000000020000000100000000000000010000000000"
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000"
"0400000003000000050000000300000006000000030000000700000003000000080000000300000009000000030000000a00"
"0000030000000b000000030000000c000000030000000d000000030000000e00000003000000000000000000000000000000"
"0000000000000100000001000000000000000300000003000000010100000001000000010000000100000000000000000001"
"00000001000000000000000e0000000300000014000000010000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000006719c2fed4abf63ffe4456b03d95b13c12ef3078097d13e1a1b74a"
"bb30b5cf17"
, {
0x4034a5761e22ecabULL, 0xf78178bf59b905d9ULL, 0x5fd5644d1fa59357ULL, 0xaa768617a1b90374ULL,
0x6ceeba0f2fe9089dULL, 0xee339afe091ed342ULL, 0xaeb06ae4ea87af53ULL, 0x7b6079611fd6a880ULL,
0xbbc9c0a6facb2499ULL, 0xe75c76afc2037eceULL, 0xec829e3d4f72762fULL, 0x07bfb4a042a471ecULL,
0x55e6cc33aa390f75ULL, 0x3e52625e8b2045b6ULL, 0x4f7d9d5bcf978d4dULL, 0x303f84c95c235208ULL,
0xb2896b1b8df536cfULL, 0xc0fc67ce76a32cbaULL, 0x421810bd51ac0c71ULL, 0x32d353a79afcd8dcULL,
0x9dd13f2ee856f313ULL, 0xac443be1d104e8feULL, 0x61a1fa6a365c4a35ULL, 0xd6d4e506f73bbaf0ULL,
0x51cc2c0b015adcd7ULL, 0x603f28bdea08d2c2ULL, 0x543c6dcbb870c959ULL, 0xfdbfa374e6fab424ULL,
0x44669f6c836f5bfbULL, 0x52d99c1f6c1d51e6ULL, 0x6404d71cb094997dULL, 0x44c6be8a3d205e38ULL,
0x06f612cf620661bfULL, 0x15690f824ab457aaULL, 0x9684b87125bd3761ULL, 0x873ffb5b6f0e03ccULL,
0xb25878efc953ff43ULL, 0xc0cb75a2b201f52eULL, 0x7629342b17595665ULL, 0x2b418cbacb4ce5e0ULL,
0x665365cbe257e907ULL, 0x74c6627ecb05def2ULL, 0xa8a9157f8c81f449ULL, 0x522c4b28bb0bdf14ULL,
0x98d34720578086ebULL, 0xa74643d3402e7cd6ULL, 0xb8717ed084a5c46dULL, 0x9933663e11318928ULL,
0x1b7d4c9043036defULL, 0x29f049432bb163daULL, 0xab0bf23206ba4391ULL, 0x9bc7351c500b0ffcULL,
0x06c520a39d652a33ULL, 0x15381d568613201eULL, 0xca95dbdeeb6a8155ULL, 0x3fc8c67bac49f210ULL,
0xbac00d7fb66913f7ULL, 0xc9330a329f1709e2ULL, 0xbd304f406d7f0079ULL, 0x66b384e99c08eb44ULL,
0xad5a80e1387d931bULL, 0xbbcd7d94212b8906ULL, 0x292932be9169f41dULL, 0x09eb1a2c1df5b8d8ULL,
0xcc1a6e7142dbbc5fULL, 0xda8d6b242b89b24aULL, 0x5ba9141306929201ULL, 0x4c6456fd4fe35e6cULL,
0x777cd491aa2959e3ULL, 0x85efd14492d74fceULL, 0x3b4d8fccf82eb105ULL, 0xf065e85cac224080ULL,
0x2b77c16dc32d43a7ULL, 0x39eabe20abdb3992ULL, 0x6dcd71216d574ee9ULL, 0x1750a6ca9be139b4ULL,
0x5df7a2c23855e18bULL, 0x6c6a9f752103d776ULL, 0x7d95da72657b1f0dULL, 0x5e57c1dff206e3c8ULL,
}},
{"harvest-hauled", "038b7ae299004c672e20cefb6c50ab9bacd6f83606ceca83d9d5edd20ff8cfad",
"53544843484b505402000000b600000059020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000200000000000000"
"0f00000000000000000000000000000000000000000000000002000000000000000100000000000000020000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000400000000"
"000000000b000000040000000300000005000000030000000600000003000000070000000300000008000000030000000900"
"0000030000000a000000030000000b000000030000000c000000030000000d000000030000000e0000000300000000000000"
"0000000000000000000000000000000001000000000000000100000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000001000000010000000000"
"0000030000000300000001000000000100000000000000010000000000000000000100000001000000000000000e00000003"
"0000001400000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000df9205984b13c7ea46ccd323ab458977e4ea273b047760dbebb30e7fd311d16f"
, {
0x5fd5644d1fa59357ULL, 0xaa768617a1b90374ULL, 0x6ceeba0f2fe9089dULL, 0xee339afe091ed342ULL,
0xaeb06ae4ea87af53ULL, 0x7b6079611fd6a880ULL, 0xbbc9c0a6facb2499ULL, 0xe75c76afc2037eceULL,
0xec829e3d4f72762fULL, 0x07bfb4a042a471ecULL, 0x55e6cc33aa390f75ULL, 0x3e52625e8b2045b6ULL,
0x4f7d9d5bcf978d4dULL, 0x303f84c95c235208ULL, 0xb2896b1b8df536cfULL, 0xc0fc67ce76a32cbaULL,
0x421810bd51ac0c71ULL, 0x32d353a79afcd8dcULL, 0x9dd13f2ee856f313ULL, 0xac443be1d104e8feULL,
0x61a1fa6a365c4a35ULL, 0xd6d4e506f73bbaf0ULL, 0x51cc2c0b015adcd7ULL, 0x603f28bdea08d2c2ULL,
0x543c6dcbb870c959ULL, 0xfdbfa374e6fab424ULL, 0x44669f6c836f5bfbULL, 0x52d99c1f6c1d51e6ULL,
0x6404d71cb094997dULL, 0x44c6be8a3d205e38ULL, 0x06f612cf620661bfULL, 0x15690f824ab457aaULL,
0x9684b87125bd3761ULL, 0x873ffb5b6f0e03ccULL, 0xb25878efc953ff43ULL, 0xc0cb75a2b201f52eULL,
0x7629342b17595665ULL, 0x2b418cbacb4ce5e0ULL, 0x665365cbe257e907ULL, 0x74c6627ecb05def2ULL,
0xa8a9157f8c81f449ULL, 0x522c4b28bb0bdf14ULL, 0x98d34720578086ebULL, 0xa74643d3402e7cd6ULL,
0xb8717ed084a5c46dULL, 0x9933663e11318928ULL, 0x1b7d4c9043036defULL, 0x29f049432bb163daULL,
0xab0bf23206ba4391ULL, 0x9bc7351c500b0ffcULL, 0x06c520a39d652a33ULL, 0x15381d568613201eULL,
0xca95dbdeeb6a8155ULL, 0x3fc8c67bac49f210ULL, 0xbac00d7fb66913f7ULL, 0xc9330a329f1709e2ULL,
0xbd304f406d7f0079ULL, 0x66b384e99c08eb44ULL, 0xad5a80e1387d931bULL, 0xbbcd7d94212b8906ULL,
0x292932be9169f41dULL, 0x09eb1a2c1df5b8d8ULL, 0xcc1a6e7142dbbc5fULL, 0xda8d6b242b89b24aULL,
0x5ba9141306929201ULL, 0x4c6456fd4fe35e6cULL, 0x777cd491aa2959e3ULL, 0x85efd14492d74fceULL,
0x3b4d8fccf82eb105ULL, 0xf065e85cac224080ULL, 0x2b77c16dc32d43a7ULL, 0x39eabe20abdb3992ULL,
0x6dcd71216d574ee9ULL, 0x1750a6ca9be139b4ULL, 0x5df7a2c23855e18bULL, 0x6c6a9f752103d776ULL,
0x7d95da72657b1f0dULL, 0x5e57c1dff206e3c8ULL, 0xe0a1a83223d8c88fULL, 0xef14a4e50c86be7aULL,
}},
{"meal-eating", "6ef841c3978ffb1cc6c622485ae00f612b8df62e728a00998dff39c4cb23dd86",
"53544843484b505402000000b6000000e3010000000000009102030405064708890a0b0c0d0e0f1007000000000000009b00"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b0000000000000014000000080000009b000000000000000100000000000000"
"0e00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000100000001000000000000000e000000030000000700000000"
"0000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000000"
"000001000000000000000000000000000000000000000000000000000000000000000000000000000000c000000000000000"
"0000000000000100000001000000000000000e00000003000000140000000000000001010000000504000000000000000000"
"000000000000000000000000000000000000000000000000000000000000000000000000000000cbca12e9de2b541fa0a67c"
"950419717981e249938bede98f7bc5ac8b21bb41e4"
, {
0x0eae6cbd44a5eb4cULL, 0x666bd2a801c60dc5ULL, 0xaa5ed34a6065dbaaULL, 0x0de79ba8983d3fb3ULL,
0x99ab26421b611ba8ULL, 0xc09e84ec6875f729ULL, 0xec94b6b0b80ab7b5ULL, 0xf98239f36dc2c19dULL,
0xd44d9d9512ae9821ULL, 0xa5f198ebe67c6949ULL, 0x6960ffccf032887dULL, 0x892b7289233b1e85ULL,
0xa0d41230356d6121ULL, 0xccf5a29ed61d7299ULL, 0x38d1425618c651e5ULL, 0x47a8b158ccfd867dULL,
0x227414fa71e95d01ULL, 0x997c1739f8dc3b99ULL, 0xb78777324f6d4d5dULL, 0x7cb5f0d7359af0d5ULL,
0x07c728f9efefcf21ULL, 0xce1cfa5e52220209ULL, 0x84c0a7e6fb14fc35ULL, 0x91ae2b29b0cd061dULL,
0x6c798ecb55b8dca1ULL, 0xb3700e5dd0287429ULL, 0x018cf103333cccfdULL, 0x96a9e7fb0ce72965ULL,
0x390003667877a5a1ULL, 0x652193d51927b719ULL, 0x464fb7c802725cc5ULL, 0xdfd4a28f1007cafdULL,
0xbaa00630b4f3a181ULL, 0x31a808703be68019ULL, 0x4fb36868927791ddULL, 0x14e1e20d78a53555ULL,
0x9ff31a3032fa13a1ULL, 0x44f1d52f88f4cf69ULL, 0x70e806f3d8898ff5ULL, 0x7dd58a368e4199ddULL,
0x6dfbe560e5e9e3a1ULL, 0x3f9fe0b7b9b7b4c9ULL, 0x030f4798c36dd3fdULL, 0x0d7ec2cc43b9f6c5ULL,
0x3a8259fc08a8aca1ULL, 0x5148f2e1f69c4ad9ULL, 0xd27f8a21ec019d65ULL, 0xe156f924a038d1fdULL,
0xa6c7653d92683541ULL, 0x1dcf677d195b13d9ULL, 0x3bdac7756fec259dULL, 0x166438a308d63c55ULL,
0xa17570c5c32b1aa1ULL, 0x67cb422a255d4d89ULL, 0x0913f82a1b93d475ULL, 0x16017b6cd14bde5dULL,
0x0627d69728f42821ULL, 0x37c35ea0f0a74c69ULL, 0x9b3b38cf0678187dULL, 0x30582fc6e02274e5ULL,
0xd2ae4b324bb2f121ULL, 0xe974e41839a68f59ULL, 0xcaa3080b22f13505ULL, 0x7982ea5ae343167dULL,
0x3ef35673d57279c1ULL, 0xb5fb58b35c655859ULL, 0xd406b8abb2f66a1dULL, 0xae9029d94be080d5ULL,
0x39a161fc06355f21ULL, 0x8aa4af24c1c5cba9ULL, 0xb69ae0e9115a8c35ULL, 0x98d2751a6199af9dULL,
0x739dd8bc06858621ULL, 0x6ff7c3243fcc3dc9ULL, 0x33672a0549825cfdULL, 0x287badb017120c85ULL,
0x40244d5729444f21ULL, 0x96fbccd72f6d4719ULL, 0x02d76c8e72162665ULL, 0x11aedb91264d5afdULL,
}},
{"meal-going", "2bf42eb752cdbb6d06a69cfe3f7eb68cbf0686d5ec855b986599b2f4b589390d",
"53544843484b505402000000b60000004b020000000000009102030405064708890a0b0c0d0e0f1007000000000000008f00"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b0000000000000014000000080000008f000000000000000100000000000000"
"0e00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000002000000030000000600000000"
"000000000d000000020000000300000003000000030000000400000003000000050000000300000006000000030000000700"
"000003000000080000000300000009000000030000000a000000030000000b000000030000000c000000030000000d000000"
"030000000e000000030000000100000000000000000000000000000000000000010000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b4000000"
"000000000000000000000100000001000000000000000e000000030000001400000000000000010100000005050000000100"
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000919d8854127c30"
"0dbea118a7d16c7f0c3044dd54f2148b20800d6204105412e3"
, {
0xfd9dfc2a0c96299dULL, 0x055fa24bd46f74c7ULL, 0xc3a99a4764c3bac9ULL, 0x788d6816d3b41547ULL,
0xabaedc2e42067cddULL, 0xad632a0f1d2c4b17ULL, 0xc9b73d3b4e831031ULL, 0x7d5bc37e22cdc2f7ULL,
0xcc366163e21db0fdULL, 0xe24026ad5ef92427ULL, 0xa4867348eeb2b129ULL, 0x165dc919e3326217ULL,
0x0eae6cbd44a5eb4cULL, 0x666bd2a801c60dc5ULL, 0xaa5ed34a6065dbaaULL, 0x0de79ba8983d3fb3ULL,
0x99ab26421b611ba8ULL, 0xc09e84ec6875f729ULL, 0xec94b6b0b80ab7b5ULL, 0xf98239f36dc2c19dULL,
0xd44d9d9512ae9821ULL, 0xa5f198ebe67c6949ULL, 0x6960ffccf032887dULL, 0x892b7289233b1e85ULL,
0xa0d41230356d6121ULL, 0xccf5a29ed61d7299ULL, 0x38d1425618c651e5ULL, 0x47a8b158ccfd867dULL,
0x227414fa71e95d01ULL, 0x997c1739f8dc3b99ULL, 0xb78777324f6d4d5dULL, 0x7cb5f0d7359af0d5ULL,
0x07c728f9efefcf21ULL, 0xce1cfa5e52220209ULL, 0x84c0a7e6fb14fc35ULL, 0x91ae2b29b0cd061dULL,
0x6c798ecb55b8dca1ULL, 0xb3700e5dd0287429ULL, 0x018cf103333cccfdULL, 0x96a9e7fb0ce72965ULL,
0x390003667877a5a1ULL, 0x652193d51927b719ULL, 0x464fb7c802725cc5ULL, 0xdfd4a28f1007cafdULL,
0xbaa00630b4f3a181ULL, 0x31a808703be68019ULL, 0x4fb36868927791ddULL, 0x14e1e20d78a53555ULL,
0x9ff31a3032fa13a1ULL, 0x44f1d52f88f4cf69ULL, 0x70e806f3d8898ff5ULL, 0x7dd58a368e4199ddULL,
0x6dfbe560e5e9e3a1ULL, 0x3f9fe0b7b9b7b4c9ULL, 0x030f4798c36dd3fdULL, 0x0d7ec2cc43b9f6c5ULL,
0x3a8259fc08a8aca1ULL, 0x5148f2e1f69c4ad9ULL, 0xd27f8a21ec019d65ULL, 0xe156f924a038d1fdULL,
0xa6c7653d92683541ULL, 0x1dcf677d195b13d9ULL, 0x3bdac7756fec259dULL, 0x166438a308d63c55ULL,
0xa17570c5c32b1aa1ULL, 0x67cb422a255d4d89ULL, 0x0913f82a1b93d475ULL, 0x16017b6cd14bde5dULL,
0x0627d69728f42821ULL, 0x37c35ea0f0a74c69ULL, 0x9b3b38cf0678187dULL, 0x30582fc6e02274e5ULL,
0xd2ae4b324bb2f121ULL, 0xe974e41839a68f59ULL, 0xcaa3080b22f13505ULL, 0x7982ea5ae343167dULL,
0x3ef35673d57279c1ULL, 0xb5fb58b35c655859ULL, 0xd406b8abb2f66a1dULL, 0xae9029d94be080d5ULL,
}},
{"tending", "3827f807449b4eef713945b5e196e082e48e10d7971587e8281f3f858f76c475",
"53544843484b505402000000b600000004020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000"
"0500000000000000000000000000000000000000000000000102000000000000000100000000000000020000000000000001"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000005000000030000000300000000"
"0000000004000000020000000300000003000000030000000400000003000000050000000300000004000000000000000500"
"0000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000002900040000000000000001000000010000000000000005000000"
"0300000001000000000600000001000000010200000000000000000000000000000000010000000200000002000000010000"
"00000000000000000000000000010000000000000001b4030ca9d1f16481a8e535b4d15d5386c3373d95462d4d421acb8c39"
"bffd838c"
, {
0x40e38438faf94b0bULL, 0x14761863e62e2a4dULL, 0xe6cd2e9002d72edbULL, 0x05e511dfedbab179ULL,
0xa31d1be8a64993d3ULL, 0x2689b1c58ae359daULL, 0x0a35fc84aa4f48c7ULL, 0xfcb493ac0b7a9ca0ULL,
0xa5b6852baae0b5d5ULL, 0x475c01f9c9b77106ULL, 0x8f687924c6abc753ULL, 0xda1797bdf654a5fcULL,
0x06e3f4bcdb5865e1ULL, 0xcfc208819fd468a2ULL, 0x8f5cf81cd325dcefULL, 0xab87d8ad5efdc448ULL,
0x9596d5a2eab7763dULL, 0xc5aea624fbd7c04eULL, 0xd450e36c43ad31dbULL, 0xa28d719e4a7f7b04ULL,
0x9397942622050189ULL, 0xed40d75b33713baaULL, 0x8b456815cce24137ULL, 0x914e242111a8c7d0ULL,
0x2ccbce0483ab8405ULL, 0xbbfc27d8b7020bb6ULL, 0x332345807b3a2dc3ULL, 0x9762664544b614ecULL,
0x80116ad6bde724d1ULL, 0x68fb7be5021b5cf2ULL, 0xfc7eb3a74944f05fULL, 0x67bda54ab54433f8ULL,
0x58e78171ef50baedULL, 0x88ff51f4007104feULL, 0x59ed9f385b844e8bULL, 0x3d906a7dcfbe2e34ULL,
0x1aacdcfefacfcfb9ULL, 0x7d5eec1f9d8fca7aULL, 0x4d8111fad96086a7ULL, 0x55025b12df1abec0ULL,
0xc29ec7a141fddb35ULL, 0x8c1fa47cb9bc6066ULL, 0xd42c1ba7b6b0b6b3ULL, 0x0a89ff17710cfe1cULL,
0x3d5c395e0c4893c1ULL, 0x130d1df7cee5a682ULL, 0xb9c9822e97a65f4fULL, 0xc26a3ddb3fe313e8ULL,
0xcc0f1a441ba7a41dULL, 0xfc26eac62cc7ee2eULL, 0xefc098d519d6a5bbULL, 0xdfd2a9ccc358e324ULL,
0xb07fd69bb92226e9ULL, 0x519a59517381094aULL, 0xa6b51d7ea30bb517ULL, 0xb43c43de5efdc2f0ULL,
0x7016e37ab2bcc1e5ULL, 0xff473d4ee6134996ULL, 0x766e5af6aa4b6ba3ULL, 0xaccc3e6664a7b30cULL,
0xc302fb492ed47b31ULL, 0x1fc6fc206a2749d2ULL, 0xb34a33e2b150dd3fULL, 0x6f49b0cbe9ae8d98ULL,
0x8e54ca4832dab44dULL, 0x0caacdd834d6e0deULL, 0x810f8a2cdff9866bULL, 0xab721e2bcde3c154ULL,
0x9d91429d9d844719ULL, 0xe0ad724af039639aULL, 0x74a2fcef5dd5be87ULL, 0xc2e40ec0dd4051e0ULL,
0x5e61b8a44f430e15ULL, 0xb3418f713e319846ULL, 0x3c07f20dfe9e7413ULL, 0xa04712d2c81a5b3cULL,
0x72c982344fd28d21ULL, 0x2caac15025f78162ULL, 0x558c7331a4eb922fULL, 0xfc64d6ec78b13188ULL,
}},
}};
} // namespace custody_v14
+258
View File
@@ -0,0 +1,258 @@
#include "settlement/core/checkpoint.hpp"
#include "settlement/core/world.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <array>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, const char* message = "identity invariant failed") {
if (!condition) throw std::runtime_error(message);
}
constexpr auto last_counter = std::numeric_limits<std::uint64_t>::max();
// Format 13 header, five tick/stat counters, hunger and four next-ID counters.
constexpr std::size_t next_node_offset = 85;
constexpr std::size_t next_storage_offset = 93;
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
void put_u64(std::string& data, std::size_t at, std::uint64_t value) {
require(at + 8 <= data.size(), "fixture offset outside save");
for (unsigned i = 0; i < 8; ++i) data[at + i] = static_cast<char>((value >> (i * 8)) & 255);
}
std::unique_ptr<World> restore(const std::string& data, std::size_t workers = 1) {
std::istringstream input(data, std::ios::binary);
return World::read_save(input, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
}
CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
return world.apply_command({1, world.next_command_sequence(1), kind, cell, value}).status;
}
void compare_continuation(World& original, int ticks) {
const auto initial = bytes(original);
std::array copies{restore(initial, 1), restore(initial, 2), restore(initial, 6), restore(initial, 12)};
const auto catalog = builtin_rule_packages();
const auto rules = default_rules_manifest();
require(catalog.has_value() && rules.has_value(), "built-in rule fixture failed");
const auto id = Void::Uuid::try_v4();
require(id.has_value(), "UUID fixture failed");
const auto checkpoint = encode_checkpoint(original, *id, 1, *rules);
require(checkpoint.has_value(), "checkpoint encode failed");
auto candidate = decode_checkpoint(*checkpoint, *catalog, 1, ExecutionMode::SerialReference);
require(candidate.has_value(), "checkpoint decode failed");
const auto held = original.capture();
for (int tick = 0; tick < ticks; ++tick) {
original.step();
const auto expected = bytes(original);
for (auto& copy : copies) {
copy->step();
require(bytes(*copy) == expected, "ID-linked continuation differs across execution modes");
}
candidate->world->step();
require(bytes(*candidate->world) == expected, "checkpoint continuation changed ID links");
require(bytes(*held) == initial, "held snapshot changed after ID-linked world advanced");
}
}
template<class Work>
void require_exhausted(World& world, Work work) {
const auto before = bytes(world);
bool overflow = false;
try { work(); } catch (const std::overflow_error&) { overflow = true; }
require(overflow && bytes(world) == before, "exhausted factory mutated state or failed to report overflow");
}
struct [[= Void::Testing::name("IdentityTests")]] IdentityTests : Void::Testing::Suite<IdentityTests> {
[[= Void::Testing::tag("identity")]] Test test_active_haul_survives_earlier_storage_and_node_deletion();
[[= Void::Testing::tag("identity")]] Test test_construction_stops_retain_ids_after_earlier_storage_deletion();
[[= Void::Testing::tag("identity")]] Test test_pantry_and_unstored_tending_restore_stable_ids();
[[= Void::Testing::tag("identity")]] Test test_carpenter_output_retains_its_storage_id();
[[= Void::Testing::tag("identity")]] Test test_factory_counters_stop_before_max_without_mutation();
[[= Void::Testing::tag("identity")]] Test test_command_counters_stop_before_max_without_terrain_changes();
[[= Void::Testing::tag("identity")]] Test test_invalid_legacy_positions_fail_before_candidate_publication();
};
Test IdentityTests::test_active_haul_survives_earlier_storage_and_node_deletion() {
World world(42, 32, 32, 1, ExecutionMode::SerialReference);
const auto unused_store = world.add_storage({1, 1}, 10, StorageKind::Pantry);
const auto destination = world.add_storage({28, 4}, 30);
const auto unused_node = world.add_resource_node({30, 25}, ItemType::Stone, 3);
const auto source = world.add_resource_node({6, 4}, ItemType::Wood, 5);
const auto resident = world.spawn_agent({4, 4});
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Woodcutter), {}, resident}).status == CommandStatus::Accepted);
world.step();
require(world.agents().front().resource_node_id == source &&
world.agents().front().storage_id == destination, "fixture did not reserve the later node and store");
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted &&
command(world, CommandKind::DemolishObject, {30, 25}) == CommandStatus::Accepted);
require(world.find_storage(unused_store) == nullptr && world.find_resource_node(unused_node) == nullptr);
require(world.agents().front().resource_node_id == source &&
world.agents().front().storage_id == destination, "deleting earlier records changed durable links");
require(world.find_storage(0) == nullptr && world.find_resource_node(last_counter) == nullptr);
for (int tick = 0; tick < 40 && world.agents().front().state != AgentState::Hauling; ++tick) world.step();
require(world.agents().front().state == AgentState::Hauling &&
world.agents().front().inventory.item_count(ItemType::Wood) == 1);
compare_continuation(world, 80);
require(world.find_storage(destination)->item_count(ItemType::Wood) > 0, "cargo missed its stable destination");
}
Test IdentityTests::test_construction_stops_retain_ids_after_earlier_storage_deletion() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(world.add_storage({1, 1}, 10, StorageKind::Pantry));
const auto planks = world.add_storage({3, 3}, 20);
const auto blocks = world.add_storage({8, 3}, 20);
world.stock_storage(planks, ItemType::Plank, 3);
world.stock_storage(blocks, ItemType::StoneBlock, 2);
static_cast<void>(world.spawn_agent({2, 3}));
world.queue_production({14, 3}, RecipeId::BuildCabin);
world.step();
const auto& order = world.production_orders().front();
require(order.delivery_stops.size() == 2 && order.delivery_stops[0].storage_id == planks &&
order.delivery_stops[1].storage_id == blocks, "construction did not retain both actual store IDs");
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
require(order.materials[0].storage_id == planks && order.materials[1].storage_id == blocks);
for (int tick = 0; tick < 20 && order.collected_stops == 0; ++tick) world.step();
require(order.collected_stops == 1 && !world.agents().front().inventory.empty());
compare_continuation(world, 65);
require(order.state == JobState::Completed, "multi-store construction did not finish");
}
Test IdentityTests::test_pantry_and_unstored_tending_restore_stable_ids() {
World meal(44, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(meal.add_storage({1, 1}, 5));
const auto pantry = meal.add_storage({28, 4}, 50, StorageKind::Pantry);
meal.stock_storage(pantry, ItemType::Berries, 40);
static_cast<void>(meal.spawn_agent({4, 4}));
meal.enable_hunger();
for (int tick = 0; tick < 500 && meal.agents().front().state != AgentState::GoingToEat; ++tick) meal.step();
require(meal.agents().front().storage_id == pantry);
require(command(meal, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
compare_continuation(meal, 50);
require(meal.meals_eaten() > 0);
World tending(45, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(tending.spawn_agent({2, 3}));
static_cast<void>(tending.add_resource_node({30, 30}, ItemType::Stone, 1));
require(command(tending, CommandKind::PlaceBerryField, {9, 3}) == CommandStatus::Accepted);
tending.step();
require(tending.agents().front().resource_node_id == tending.resource_nodes().back().id &&
tending.agents().front().storage_id == 0, "tending acquired an unrelated storage");
require(command(tending, CommandKind::DemolishObject, {30, 30}) == CommandStatus::Accepted);
compare_continuation(tending, 100);
require(tending.resource_nodes().front().quantity > 0);
}
Test IdentityTests::test_carpenter_output_retains_its_storage_id() {
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(world.add_storage({1, 1}, 10, StorageKind::Pantry));
const auto materials = world.add_storage({2, 3}, 10);
world.stock_storage(materials, ItemType::Wood, 2);
const auto carpenter = world.spawn_agent({2, 2});
world.start_scenario({8, 3});
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
world.queue_production({8, 3}, RecipeId::CraftWoodenDoor);
world.step();
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
for (int tick = 0; tick < 100 &&
world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 0; ++tick) world.step();
require(world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 1 &&
world.agents().front().storage_id == materials && world.find_storage(materials)->reserved_slots == 1,
"carpenter output lost its persistent reserved destination");
compare_continuation(world, 30);
require(world.find_storage(materials)->item_count(ItemType::WoodenDoor) == 1 &&
world.find_storage(materials)->reserved_slots == 0, "carpenter delivered into the wrong storage");
}
Test IdentityTests::test_factory_counters_stop_before_max_without_mutation() {
World empty(46, 8, 8, 1, ExecutionMode::SerialReference);
for (const auto offset : {next_node_offset, next_storage_offset}) {
auto data = bytes(empty);
put_u64(data, offset, last_counter - 1);
auto world = restore(data);
if (offset == next_node_offset) {
require(world->add_resource_node({2, 2}, ItemType::Wood, 1) == last_counter - 1);
world = restore(bytes(*world));
require_exhausted(*world, [&] { static_cast<void>(world->add_resource_node({3, 3}, ItemType::Stone, 1)); });
} else {
require(world->add_storage({2, 2}, 10) == last_counter - 1);
world = restore(bytes(*world));
require_exhausted(*world, [&] { static_cast<void>(world->add_storage({3, 3}, 10)); });
}
put_u64(data, offset, last_counter);
world = restore(data);
if (offset == next_node_offset) {
require_exhausted(*world, [&] { static_cast<void>(world->add_resource_node({2, 2}, ItemType::Wood, 1)); });
} else {
require_exhausted(*world, [&] { static_cast<void>(world->add_storage({2, 2}, 10)); });
}
}
}
Test IdentityTests::test_command_counters_stop_before_max_without_terrain_changes() {
constexpr std::array kinds{CommandKind::PlaceBerryField, CommandKind::PlaceTreePlot,
CommandKind::PlaceFlaxField, CommandKind::PlaceMine, CommandKind::PlaceStorage};
for (const auto kind : kinds) {
World initial(47, 8, 8, 1, ExecutionMode::SerialReference);
static_cast<void>(initial.spawn_agent({2, 2}));
const bool mine = kind == CommandKind::PlaceMine;
if (mine) {
initial.set_blocked({4, 4});
initial.set_blocked({5, 4});
}
const auto offset = kind == CommandKind::PlaceStorage ? next_storage_offset : next_node_offset;
auto data = bytes(initial);
put_u64(data, offset, last_counter);
auto world = restore(data);
const auto before = bytes(*world);
require(command(*world, kind, {4, 4}) == CommandStatus::Busy && bytes(*world) == before &&
world->next_command_sequence(1) == 1, "exhausted command changed world or consumed sequence");
if (mine) require(!world->is_walkable({4, 4}));
put_u64(data, offset, last_counter - 1);
world = restore(data);
require(command(*world, kind, {4, 4}) == CommandStatus::Accepted);
require(kind == CommandKind::PlaceStorage ? world->storages().back().id == last_counter - 1 :
world->resource_nodes().back().id == last_counter - 1);
world = restore(bytes(*world));
const auto exhausted = bytes(*world);
require(command(*world, kind, {5, 4}) == CommandStatus::Busy && bytes(*world) == exhausted &&
world->next_command_sequence(1) == 2, "second exhausted command changed state");
if (mine) require(!world->is_walkable({5, 4}));
}
}
Test IdentityTests::test_invalid_legacy_positions_fail_before_candidate_publication() {
World world(48, 8, 8, 1, ExecutionMode::SerialReference);
static_cast<void>(world.spawn_agent({2, 2}));
static_cast<void>(world.add_resource_node({3, 3}, ItemType::Wood, 2));
static_cast<void>(world.add_storage({4, 4}, 10));
const auto original = bytes(world);
// The first resident has an empty route. Its two legacy links follow the
// 101-byte prefix, cell mask, resident count and 41 bytes of resident fields.
constexpr std::size_t node_link = 101 + 8 * 8 + 4 + 41;
for (const auto at : {node_link, node_link + 8}) {
auto invalid = original;
put_u64(invalid, at, 2); // One-based position two, with a single record.
bool rejected = false;
try { static_cast<void>(restore(invalid)); } catch (const std::runtime_error&) { rejected = true; }
require(rejected && bytes(world) == original, "dangling legacy link escaped candidate validation");
}
}
} // namespace
+322
View File
@@ -1,14 +1,26 @@
#define NOMINMAX
#include <winsock2.h>
#include <ws2tcpip.h>
#include "lan_session.hpp"
#include "lan_wire.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <chrono>
#include <condition_variable>
#include <future>
#include <mutex>
#include <spanstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace {
@@ -29,11 +41,128 @@ constexpr auto command_bytes = "\x23\x00\x00\x00\x03"
constexpr auto receipt_bytes = "\x0a\x00\x00\x00\x04\x04\x10\x32\x54\x76\x98\xba\xdc\xfe"sv;
constexpr auto ping_bytes = "\x01\x00\x00\x00\x06"sv;
WorldCheckpoint colony_checkpoint() {
auto identity = Void::Uuid::try_v4();
auto rules = default_rules_manifest();
require(identity.has_value() && rules.has_value());
return {make_first_colony(2), *identity, 1, std::move(*rules)};
}
template<class Pump, class Condition>
void pump_until(Pump pump, Condition condition, const char* message) {
const auto deadline = std::chrono::steady_clock::now() + 3s;
do {
pump();
if (condition()) return;
std::this_thread::sleep_for(1ms);
} while (std::chrono::steady_clock::now() < deadline);
throw std::runtime_error(message);
}
struct CaptureGate {
std::mutex mutex;
std::condition_variable changed;
bool armed = false;
bool entered = false;
bool released = false;
void capture(RuntimePhase phase) {
if (phase != RuntimePhase::BeforeCapture) return;
std::unique_lock lock(mutex);
if (!armed) return;
entered = true;
changed.notify_all();
if (!changed.wait_for(lock, 5s, [&] { return released; })) {
throw std::runtime_error("LAN test capture gate timed out.");
}
}
void arm() { std::lock_guard lock(mutex); armed = true; }
bool waiting() { std::lock_guard lock(mutex); return entered; }
void release() {
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
};
struct RawGuest {
SOCKET socket = INVALID_SOCKET;
std::string input;
std::string output;
bool closed = false;
std::vector<lan_wire::Receipt> receipts;
std::unique_ptr<World> snapshot;
RawGuest(std::uint16_t port, std::uint64_t key) {
socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socket == INVALID_SOCKET) throw std::runtime_error("Raw guest socket failed.");
auto close_on_error = Void::Scope::on_exit([&] { closesocket(socket); });
sockaddr_in remote{};
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
remote.sin_port = htons(port);
if (connect(socket, reinterpret_cast<const sockaddr*>(&remote), sizeof(remote)) != 0) {
throw std::runtime_error("Raw guest connect failed.");
}
u_long enabled = 1;
require(ioctlsocket(socket, static_cast<long>(FIONBIO), &enabled) == 0);
const auto hello = lan_wire::encode_hello({lan_wire::protocol_version, key});
lan_wire::append_frame(output, lan_wire::Message::Hello, std::string_view(hello));
close_on_error.release();
}
~RawGuest() { closesocket(socket); }
RawGuest(const RawGuest&) = delete;
RawGuest& operator=(const RawGuest&) = delete;
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value});
lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes));
}
void poll() {
if (closed) return;
if (!output.empty()) {
const auto sent = send(socket, output.data(), static_cast<int>(output.size()), 0);
if (sent > 0) output.erase(0, static_cast<std::size_t>(sent));
else if (sent == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
}
std::array<char, 8192> bytes{};
for (int attempt = 0; attempt < 16 && !closed; ++attempt) {
const auto count = recv(socket, bytes.data(), static_cast<int>(bytes.size()), 0);
if (count == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
break;
}
if (count == 0) { closed = true; break; }
input.append(bytes.data(), static_cast<std::size_t>(count));
std::size_t consumed = 0;
while (const auto frame = lan_wire::next_frame(std::string_view(input).substr(consumed))) {
if (frame->message == lan_wire::Message::Receipt) {
auto receipt = lan_wire::decode_receipt(frame->payload);
require(receipt.has_value());
receipts.push_back(*receipt);
} else if (frame->message == lan_wire::Message::Snapshot) {
std::ispanstream stream(frame->payload);
snapshot = World::read_save(stream);
}
consumed += frame->size;
}
input.erase(0, consumed);
}
}
};
struct LanTests : Void::Testing::Suite<LanTests> {
[[= Void::Testing::tag("wire")]] Test test_protocol_11_fixed_messages();
[[= Void::Testing::tag("wire")]] Test test_fragmented_and_coalesced_frames();
[[= Void::Testing::tag("wire")]] Test test_frame_size_limits();
[[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_receipts_and_corrected_legacy_sequence();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_wrong_sequence_busy_and_pipelining();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_retains_slot_work_across_reconnect();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_reauthenticates_after_pending_rollback();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults();
};
Test LanTests::test_protocol_11_fixed_messages() {
@@ -295,4 +424,197 @@ Test LanTests::test_shared_colony_over_loopback() {
require(authoritative->production_orders().size() == previous_size + 10);
}
Test LanTests::test_runtime_host_receipts_and_corrected_legacy_sequence() {
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
LanSession host, guest;
host.host(0, true);
guest.join("127.0.0.1", host.join_code(), host.port());
std::unique_ptr<World> view;
const auto pump = [&] {
host.poll_host(runtime);
if (auto latest = guest.poll_guest()) view = std::move(latest);
};
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Runtime guest did not join.");
require(view && view->tick() == 0);
const auto resident = view->agents().back().id;
require(guest.submit(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), {}, resident));
std::optional<LanCommandResult> result;
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Profession receipt missing.");
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::AssignProfession &&
result->resident == resident && result->value == static_cast<std::uint8_t>(Profession::Miner));
require(runtime.latest()->world->agents().back().profession == Profession::Miner);
require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast<std::uint8_t>(BedBase::Stone)));
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Bed receipt missing.");
require(result->status == CommandStatus::Accepted && result->cell == GridPosition{16, 18});
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0));
require(guest.submit(CommandKind::SetForaging, {14, 12}, 1));
pump_until(pump, [&] { return guest.take_rejection().has_value(); }, "Bed rejection missing.");
// The failed result remains undrained. The queued correction cannot execute.
for (int attempt = 0; attempt < 20; ++attempt) pump();
require(runtime.latest()->next_requests[1] == 4);
result = guest.take_result();
require(result && result->status == CommandStatus::InvalidTarget && result->kind == CommandKind::PlaceBed &&
result->cell == GridPosition{16, 18} && result->destination == GridPosition{} && result->value == 0);
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Corrected command receipt missing.");
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
require(runtime.latest()->next_requests[1] == 5 && runtime.latest()->world->next_command_sequence(2) == 4);
require(runtime.latest()->world->production_orders().size() == 1);
pump_until(pump, [&] { return view->next_command_sequence(2) == 4; }, "Same-tick snapshot missing.");
require(view->tick() == 0);
guest.leave();
require(!guest.take_result());
}
Test LanTests::test_runtime_host_wrong_sequence_busy_and_pipelining() {
CaptureGate gate;
RuntimeOptions options{.capacity = 1, .ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
SimulationRuntime runtime(colony_checkpoint(), options);
auto release = Void::Scope::on_exit([&] { gate.release(); });
LanSession host;
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Raw runtime guest did not join.");
guest.command(99, CommandKind::SetForaging, {14, 12}, 1);
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Wrong-sequence receipt missing.");
require(guest.receipts[0].status == CommandStatus::WrongSequence && guest.receipts[0].next_sequence == 1);
const auto snapshot = runtime.latest();
gate.arm();
const auto& id = snapshot->identity;
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, 1,
CommandPayload{CommandKind::SetForaging, {13, 14}, 1}});
require(local.admission == RuntimeAdmission::Accepted);
pump_until(pump, [&] { return gate.waiting(); }, "Owner did not reach blocked capture.");
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Busy receipt missing.");
require(guest.receipts[1].status == CommandStatus::Busy && guest.receipts[1].next_sequence == 1);
require(runtime.latest()->next_requests[1] == 1);
gate.release();
require(local.completion.wait_for(3s) == std::future_status::ready);
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
// Two coalesced commands cannot turn one guest slot into multiple in-flight operations.
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
guest.command(2, CommandKind::SetForaging, {18, 12}, 1);
pump_until(pump, [&] { return guest.closed; }, "Pipelined guest was not bounded.");
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
pump_until(pump, [&] {
fence = runtime.synchronize();
return fence.admission == RuntimeAdmission::Accepted;
}, "Owner did not release its admission slot.");
require(fence.completion.wait_for(3s) == std::future_status::ready);
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->next_command_sequence(2) == 2);
}
Test LanTests::test_runtime_host_retains_slot_work_across_reconnect() {
CaptureGate gate;
RuntimeOptions options{.ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
SimulationRuntime runtime(colony_checkpoint(), options);
auto release = Void::Scope::on_exit([&] { gate.release(); });
LanSession host, first, next;
host.host(0, true);
const auto code = host.join_code();
const auto pump = [&] {
host.poll_host(runtime);
static_cast<void>(first.poll_guest());
static_cast<void>(next.poll_guest());
};
first.join("127.0.0.1", code, host.port());
pump_until(pump, [&] { return first.state() == LanState::GuestConnected; }, "First guest did not join.");
gate.arm();
require(first.submit(CommandKind::PlaceBed, {16, 18}, 1));
pump_until(pump, [&] { return gate.waiting(); }, "Guest command did not reach blocked owner.");
require(runtime.latest()->world->production_orders().empty());
first.leave();
pump_until(pump, [&] { return host.state() == LanState::Hosting; }, "Old socket did not close.");
next.join("127.0.0.1", code, host.port());
for (int attempt = 0; attempt < 20; ++attempt) pump();
require(next.state() == LanState::Connecting && !next.take_result());
gate.release();
pump_until(pump, [&] { return next.state() == LanState::GuestConnected; }, "Reconnected guest did not join.");
require(!next.take_result());
require(runtime.latest()->world->production_orders().size() == 1);
require(runtime.latest()->next_requests[1] == 2);
require(next.submit(CommandKind::SetForaging, {14, 12}, 1));
std::optional<LanCommandResult> result;
pump_until(pump, [&] { result = next.take_result(); return result.has_value(); }, "New guest receipt missing.");
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
require(runtime.latest()->next_requests[1] == 3 && runtime.latest()->world->next_command_sequence(2) == 3);
}
Test LanTests::test_runtime_host_reauthenticates_after_pending_rollback() {
CaptureGate gate;
RuntimeOptions options{.ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
auto initial = colony_checkpoint();
const auto world_id = initial.world_id;
SimulationRuntime runtime(std::move(initial), options);
auto release = Void::Scope::on_exit([&] { gate.release(); });
LanSession host, guest;
host.host(0, true);
guest.join("127.0.0.1", host.join_code(), host.port());
const auto pump = [&] { host.poll_host(runtime); static_cast<void>(guest.poll_guest()); };
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Rollback guest did not join.");
const auto old_session = runtime.latest()->identity.session;
gate.arm();
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
pump_until(pump, [&] { return gate.waiting(); }, "Rollback guest command did not block.");
auto ticket = runtime.begin_load();
require(ticket.has_value());
auto rollback = colony_checkpoint();
rollback.world_id = world_id;
auto installed = runtime.try_install(*ticket, rollback);
require(installed.admission == RuntimeAdmission::Accepted);
gate.release();
require(installed.completion.wait_for(3s) == std::future_status::ready);
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Old epoch peer stayed connected.");
require(runtime.latest()->identity.session != old_session && runtime.latest()->identity.world == world_id);
require(runtime.latest()->world->production_orders().empty() && !guest.take_result());
guest.reconnect();
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Guest could not reauthenticate.");
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
std::optional<LanCommandResult> result;
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "New epoch receipt missing.");
require(result->status == CommandStatus::Accepted && runtime.latest()->next_requests[1] == 2);
}
Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() {
auto initial = colony_checkpoint();
auto packages = builtin_rule_packages();
require(packages.has_value());
const std::array selected{std::string{"settlement.core"}};
auto rules = resolve_rules(*packages, selected);
require(rules.has_value());
initial.rules = std::move(*rules);
SimulationRuntime incompatible(std::move(initial), {.ticking = false});
LanSession host, guest;
host.host(0, true);
guest.join("127.0.0.1", host.join_code(), host.port());
host.poll_host(incompatible);
require(host.state() == LanState::Hosting && host.detail().find("default rules") != std::string::npos);
for (int attempt = 0; attempt < 20; ++attempt) {
host.poll_host(incompatible);
require(!guest.poll_guest());
}
require(guest.state() != LanState::GuestConnected);
guest.leave();
RuntimeOptions options{.ticking = false};
options.observer = [](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected capture failure.");
};
SimulationRuntime faulting(colony_checkpoint(), options);
guest.join("127.0.0.1", host.join_code(), host.port());
const auto pump = [&] { host.poll_host(faulting); static_cast<void>(guest.poll_guest()); };
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Fault guest did not join.");
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Faulted peer stayed connected.");
require(faulting.view().state == RuntimeState::Faulted && faulting.latest()->world->production_orders().empty());
require(!guest.take_result());
}
} // namespace
+352
View File
@@ -0,0 +1,352 @@
#include "settlement/core/checkpoint.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
constexpr auto terminal = std::numeric_limits<ProductionId>::max();
constexpr std::size_t next_production_offset = 101;
constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}};
void require(bool condition, const char* message = "production identity invariant failed") {
if (!condition) throw std::runtime_error(message);
}
std::string bytes(const World& world, WorldSaveFormat format = WorldSaveFormat::Current14) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, format);
return stream.str();
}
std::unique_ptr<World> restore(const std::string& data, std::size_t workers = 1) {
std::istringstream input(data, std::ios::binary);
return World::read_save(input, workers, workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
}
template<class T>
void put(std::string& data, std::size_t offset, T value) {
Void::Binary::Writer writer(std::as_writable_bytes(std::span{data.data(), data.size()}).subspan(offset));
require(writer.writeLittle(value).has_value(), "fixture write failed");
}
std::unique_ptr<World> with_next(const World& world, ProductionId next) {
auto data = bytes(world);
put(data, next_production_offset, next);
return restore(data);
}
std::unique_ptr<World> checkpoint(const World& world, std::size_t workers = 1) {
const auto rules = default_rules_manifest();
const auto catalog = builtin_rule_packages();
require(rules.has_value() && catalog.has_value());
const auto encoded = encode_checkpoint(world, world_id, 7, *rules);
require(encoded.has_value());
auto decoded = decode_checkpoint(*encoded, *catalog, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
require(decoded.has_value() && decoded->world_id == world_id && bytes(*decoded->world) == bytes(world),
"modern checkpoint changed stable identity or high-water state");
return std::move(decoded->world);
}
CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
GridPosition destination = {}) {
return world.apply_command({1, world.next_command_sequence(1), kind, cell, value, destination}).status;
}
std::unique_ptr<World> scenario(bool legacy_beds = false) {
auto world = std::make_unique<World>(43, 24, 24, 1, ExecutionMode::SerialReference);
world->start_scenario({2, 2});
if (legacy_beds) {
auto data = bytes(*world);
data.back() = 0; // Historical scenario without staged beds.
world = restore(data);
}
return world;
}
// Parse only field boundaries, using the public version-14 wire layout. This
// avoids relying on C++ object layout when attacking references/counters.
struct Locations { std::vector<std::size_t> orders; std::vector<std::size_t> links; };
Locations locations(const std::string& data) {
Void::Binary::Reader reader(std::as_bytes(std::span{data.data(), data.size()}));
const auto skip = [&](std::size_t n) { require(reader.skip(n).has_value()); };
const auto count = [&] { return reader.readLittle<std::uint32_t>().value(); };
const auto route = [&] { const auto n = count(); skip(static_cast<std::size_t>(n) * 8); };
skip(20);
const auto width = count(), height = count();
skip(81 + static_cast<std::size_t>(width) * height);
Locations found;
const auto agents = count();
for (std::uint32_t i = 0; i < agents; ++i) {
skip(25); route(); skip(28 + item_type_count * 4); route();
found.links.push_back(reader.position()); skip(14);
}
const auto jobs = count(); skip(static_cast<std::size_t>(jobs) * 25);
const auto nodes = count(); skip(static_cast<std::size_t>(nodes) * 39);
const auto stores = count();
for (std::uint32_t i = 0; i < stores; ++i) { skip(25); const auto stacks = count(); skip(stacks * 9U); }
const auto orders = count();
for (std::uint32_t i = 0; i < orders; ++i) {
found.orders.push_back(reader.position()); skip(18);
const auto materials = count(); skip(materials * 13U);
const auto stops = count();
for (std::uint32_t j = 0; j < stops; ++j) { skip(8); route(); }
skip(18);
}
return found;
}
void rejected(const std::string& data) {
bool failed = false;
try { static_cast<void>(restore(data)); } catch (const std::runtime_error&) { failed = true; }
require(failed, "corrupt stable production state was accepted");
}
struct [[= Void::Testing::name("ProductionIdentityTests")]] ProductionIdentityTests
: Void::Testing::Suite<ProductionIdentityTests> {
[[= Void::Testing::tag("production-id")]] Test active_delivery_survives_lower_deletion_and_modern_replay();
[[= Void::Testing::tag("production-id")]] Test highest_and_all_deletions_preserve_high_water();
[[= Void::Testing::tag("production-id")]] Test last_single_id_and_complete_command_batches();
[[= Void::Testing::tag("production-id")]] Test demolition_preflights_every_product_before_losing_stock();
[[= Void::Testing::tag("production-id")]] Test demolition_counts_existing_supply_and_pending_crafts_exactly();
[[= Void::Testing::tag("production-id")]] Test legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result();
[[= Void::Testing::tag("production-id")]] Test malformed_ids_and_references_fail_before_dereference();
[[= Void::Testing::tag("production-id")]] Test legacy_projection_imports_deterministic_dense_ids();
};
Test ProductionIdentityTests::active_delivery_survives_lower_deletion_and_modern_replay() {
World world(42, 32, 32, 1, ExecutionMode::SerialReference);
const auto store = world.add_storage({3, 3}, 20);
world.stock_storage(store, ItemType::Plank, 3);
world.stock_storage(store, ItemType::StoneBlock, 2);
static_cast<void>(world.spawn_agent({2, 3}));
world.queue_production({20, 20}, RecipeId::BuildMedicineCabinet); // No wood: remains available.
world.queue_production({14, 3}, RecipeId::BuildCabin);
const auto lower = world.production_orders().front().id;
const auto active = world.production_orders().back().id;
for (int tick = 0; tick < 30 && world.agents().front().inventory.empty(); ++tick) world.step();
require(world.agents().front().production_id == active && !world.agents().front().inventory.empty(),
"fixture must exercise actual mid-delivery cargo");
require(command(world, CommandKind::DemolishObject, {20, 20}) == CommandStatus::Accepted);
require(world.find_production(lower) == nullptr && world.find_production(0) == nullptr &&
world.find_production(terminal) == nullptr && world.agents().front().production_id == active);
const auto legacy_bytes = bytes(world, WorldSaveFormat::Legacy13);
const auto legacy = restore(legacy_bytes);
require(legacy->agents().front().production_id == legacy->production_orders().front().id &&
bytes(*legacy, WorldSaveFormat::Legacy13) == legacy_bytes,
"legacy positional projection changed a live delivery after lower deletion");
const auto held = world.capture();
const auto frozen = bytes(*held);
std::vector<std::unique_ptr<World>> copies;
for (auto workers : {1U, 2U, 6U, 12U}) copies.push_back(checkpoint(world, workers));
for (int tick = 0; tick < 70; ++tick) {
world.step();
for (auto& copy : copies) {
copy->step();
require(bytes(*copy) == bytes(world), "modern canonical tick replay diverged across worker counts");
}
require(bytes(*held) == frozen, "capture did not retain production state independently");
}
require(world.find_production(active)->state == JobState::Completed);
require(command(world, CommandKind::DemolishObject, {14, 3}) == CommandStatus::Accepted);
auto empty = checkpoint(world);
empty->queue_production({15, 3}, RecipeId::BuildCabin);
require(empty->production_orders().front().id > active, "deleting all orders reissued an identity");
}
Test ProductionIdentityTests::highest_and_all_deletions_preserve_high_water() {
auto world = scenario();
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
const auto highest = world->production_orders().back().id;
require(command(*world, CommandKind::DemolishObject, {7, 6}) == CommandStatus::Accepted);
world = checkpoint(*world);
world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet);
require(world->production_orders().back().id == highest + 1);
require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted);
require(command(*world, CommandKind::DemolishObject, {8, 6}) == CommandStatus::Accepted);
world = checkpoint(*world);
world->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
require(world->production_orders().front().id == highest + 2);
}
Test ProductionIdentityTests::last_single_id_and_complete_command_batches() {
World basic(42, 24, 24, 1, ExecutionMode::SerialReference);
auto single = with_next(basic, terminal - 1);
single->queue_production({6, 6}, RecipeId::BuildCabin);
require(single->production_orders().back().id == terminal - 1);
single = checkpoint(*single);
const auto before = bytes(*single);
bool exhausted = false;
try { single->queue_production({7, 6}, RecipeId::BuildCabin); }
catch (const ProductionCapacityError&) { exhausted = true; }
require(exhausted && bytes(*single) == before);
struct Batch { CommandKind kind; std::uint8_t value; std::size_t count; bool legacy; GridPosition last; };
const RoomPlan furnished{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Doctor};
const RoomPlan empty{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Empty};
const std::array batches{
Batch{CommandKind::PlaceBed, 0, 1, false, {}},
Batch{CommandKind::PlaceBed, 0, 2, true, {}},
Batch{CommandKind::PlaceLoom, 0, 2, false, {}},
Batch{CommandKind::CraftDoor, 0, 1, false, {}},
Batch{CommandKind::CraftFurniture, static_cast<std::uint8_t>(ItemType::MiningRack), 1, false, {}},
Batch{CommandKind::PlaceRoom, furnished.placement_value(), 20, false, furnished.last},
Batch{CommandKind::PlaceRoom, furnished.placement_value(), 21, true, furnished.last},
Batch{CommandKind::PlaceRoom, empty.placement_value(), 17, false, empty.last}};
for (const auto& batch : batches) {
const auto initial = scenario(batch.legacy);
auto refused = with_next(*initial, terminal - batch.count + 1);
const auto original = bytes(*refused);
require(command(*refused, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Busy,
"insufficient complete command batch was not Busy");
require(bytes(*refused) == original && refused->next_command_sequence(1) == 1,
"batch refusal changed orders, counter, stock, terrain or command sequence");
auto accepted = with_next(*initial, terminal - batch.count);
require(command(*accepted, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Accepted);
require(accepted->production_orders().size() == batch.count &&
accepted->production_orders().back().id == terminal - 1, "batch allocation count or last ID differs");
accepted = checkpoint(*accepted);
const auto full = bytes(*accepted);
require(command(*accepted, CommandKind::CraftDoor) == CommandStatus::Busy && bytes(*accepted) == full);
}
static_cast<void>(basic.spawn_agent({2, 2}));
auto loom = with_next(basic, terminal - 1);
require(command(*loom, CommandKind::PlaceLoom, {6, 6}) == CommandStatus::Accepted &&
loom->production_orders().size() == 1 && loom->production_orders().front().id == terminal - 1);
for (auto count : {5U, 6U}) {
auto cabin = with_next(basic, terminal - count);
const auto original = bytes(*cabin);
bool failed = false;
try { cabin->queue_cabin({10, 10}, {3, 3}, {4, 3}); }
catch (const ProductionCapacityError&) { failed = true; }
require(count == 5 ? failed && bytes(*cabin) == original :
!failed && cabin->production_orders().size() == 6 && cabin->production_orders().back().id == terminal - 1);
}
}
Test ProductionIdentityTests::demolition_preflights_every_product_before_losing_stock() {
auto initial = scenario();
const auto store = initial->add_storage({3, 3}, 20);
initial->stock_storage(store, ItemType::WoodenDoor, 1);
initial->stock_storage(store, ItemType::Loom, 1);
initial->stock_storage(store, ItemType::MedicineCabinet, 1);
initial->queue_production({6, 6}, RecipeId::InstallDoorAlongX);
initial->queue_production({7, 6}, RecipeId::InstallLoom);
initial->queue_production({8, 6}, RecipeId::InstallMedicineCabinet);
for (auto available : {0U, 1U, 2U}) {
auto world = with_next(*initial, terminal - available);
const auto before = bytes(*world);
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Busy && bytes(*world) == before,
"multi-product demolition lost stock or allocated a partial replacement batch");
require(world->find_storage(store) != nullptr && world->next_command_sequence(1) == 1);
}
auto world = with_next(*initial, terminal - 3);
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted);
require(world->find_storage(store) == nullptr && world->production_orders().size() == 6);
for (auto recipe : {RecipeId::CraftWoodenDoor, RecipeId::CraftLoom, RecipeId::CraftMedicineCabinet}) {
require(std::count_if(world->production_orders().begin(), world->production_orders().end(),
[&](const auto& order) { return order.recipe == recipe; }) == 1);
}
static_cast<void>(checkpoint(*world));
}
Test ProductionIdentityTests::demolition_counts_existing_supply_and_pending_crafts_exactly() {
auto world = scenario();
const auto lost = world->add_storage({3, 3}, 20);
const auto retained = world->add_storage({4, 3}, 20);
world->stock_storage(lost, ItemType::WoodenDoor, 1);
world->stock_storage(lost, ItemType::Loom, 1);
world->stock_storage(lost, ItemType::MedicineCabinet, 1);
world->stock_storage(retained, ItemType::WoodenDoor, 1);
world->queue_production({6, 6}, RecipeId::InstallDoorAlongX);
world->queue_production({7, 6}, RecipeId::InstallLoom);
world->queue_production({8, 6}, RecipeId::InstallMedicineCabinet);
world->queue_production({2, 2}, RecipeId::CraftLoom);
world = with_next(*world, terminal - 1);
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted,
"demolition overcounted replacement orders already covered by stock or pending craft");
require(world->production_orders().size() == 5 && world->production_orders().back().recipe == RecipeId::CraftMedicineCabinet &&
world->production_orders().back().id == terminal - 1 && world->find_storage(retained)->item_count(ItemType::WoodenDoor) == 1);
}
Test ProductionIdentityTests::legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result() {
World initial(42, 24, 24, 1, ExecutionMode::SerialReference);
static_cast<void>(initial.spawn_agent({2, 2}));
auto world = with_next(initial, terminal - 5);
const auto before = bytes(*world);
auto rules = default_rules_manifest(); require(rules.has_value());
SimulationRuntime runtime(WorldCheckpoint{std::move(world), world_id, 7, *rules}, {.ticking = false});
const auto identity = runtime.latest()->identity;
const CommandEnvelope cabin{command_envelope_version, identity.world, identity.session, identity.city, 1,
LegacyCabinPayload{{10, 10}, {3, 3}, {4, 3}}};
auto result = runtime.try_submit({1}, cabin);
require(result.admission == RuntimeAdmission::Accepted);
auto completed = result.completion.get();
require(completed.outcome == RuntimeOutcome::Completed && completed.receipt ==
DispatchReceipt{DispatchStatus::Completed, CommandStatus::Busy, 0, 0});
auto repeat = runtime.try_submit({1}, cabin);
require(repeat.admission == RuntimeAdmission::Accepted && repeat.completion.get().receipt == completed.receipt);
require(runtime.lookup({1}, cabin) == completed.receipt && runtime.latest()->next_requests[0] == 2 &&
runtime.view().state == RuntimeState::Running && bytes(*runtime.latest()->world) == before,
"pre-mutation cabin refusal faulted the session, changed state or lost its retained receipt");
const CommandEnvelope storage{command_envelope_version, identity.world, identity.session, identity.city, 2,
CommandPayload{CommandKind::PlaceStorage, {6, 6}}};
auto continued = runtime.try_submit({1}, storage);
require(continued.admission == RuntimeAdmission::Accepted);
const auto next = continued.completion.get();
require(next.outcome == RuntimeOutcome::Completed && next.receipt->command_status == CommandStatus::Accepted &&
runtime.view().state == RuntimeState::Running && runtime.latest()->world->storages().size() == 1);
}
Test ProductionIdentityTests::malformed_ids_and_references_fail_before_dereference() {
auto world = scenario();
static_cast<void>(world->spawn_agent({4, 4}));
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
const auto valid = bytes(*world);
const auto offsets = locations(valid);
require(offsets.orders.size() == 2 && offsets.links.size() == 1);
for (const auto value : {ProductionId{0}, ProductionId{2}, terminal}) {
auto data = valid; put(data, offsets.orders.front(), value); rejected(data);
}
auto duplicate = valid; put(duplicate, offsets.orders.back(), ProductionId{1}); rejected(duplicate);
auto unsorted = valid; put(unsorted, offsets.orders.front(), ProductionId{2});
put(unsorted, offsets.orders.back(), ProductionId{1}); rejected(unsorted);
for (const auto value : {ProductionId{0}, ProductionId{2}}) {
auto data = valid; put(data, next_production_offset, value); rejected(data);
}
for (const auto value : {ProductionId{1}, ProductionId{3}, terminal}) {
auto data = valid; put(data, offsets.links.front(), value); rejected(data);
}
const auto store = world->add_storage({3, 3}, 20);
world->stock_storage(store, ItemType::Wood, 4);
world->step();
require(world->agents().front().production_id != 0);
const auto active = bytes(*world);
auto none = active; put(none, locations(active).links.front(), ProductionId{0}); rejected(none);
auto wrong = active; put(wrong, locations(active).links.front(), world->production_orders().back().id); rejected(wrong);
}
Test ProductionIdentityTests::legacy_projection_imports_deterministic_dense_ids() {
auto world = scenario();
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted);
world = with_next(*world, 123);
world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet);
const auto old_bytes = bytes(*world, WorldSaveFormat::Legacy13);
auto legacy = restore(old_bytes);
require(legacy->production_orders()[0].id == 1 && legacy->production_orders()[1].id == 2 &&
bytes(*legacy, WorldSaveFormat::Legacy13) == old_bytes, "legacy positional projection or deterministic import changed");
legacy->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
require(legacy->production_orders().back().id == 3);
auto modern = checkpoint(*world);
modern->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
require(modern->production_orders().back().id == 124);
}
} // namespace
+285
View File
@@ -0,0 +1,285 @@
#include "settlement/core/colony_profile.hpp"
#include <Void/Core/Hash.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
template<class T, class E>
T checked(std::expected<T, E> result) {
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string saved(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return std::move(stream).str();
}
std::string checkpoint(const World& world, const WorldCheckpoint& identity) {
return checked(encode_checkpoint(world, identity.world_id, identity.city, identity.rules));
}
void command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
GridPosition target = {}, AgentId resident = 0) {
const auto receipt = world.apply_command(
{1, world.next_command_sequence(1), kind, cell, value, target, resident});
require(receipt.status == CommandStatus::Accepted, "profile command was rejected");
}
std::uint64_t stock(const World& world, ItemType item) {
std::uint64_t count = 0;
for (const auto& storage : world.storages()) count += storage.item_count(item);
for (const auto& agent : world.agents()) count += agent.inventory.item_count(item);
return count;
}
void queue_three_beds(World& world) {
command(world, CommandKind::PlaceBed, {16, 18});
command(world, CommandKind::PlaceBed, {17, 18}, 1);
command(world, CommandKind::PlaceBed, {18, 18});
command(world, CommandKind::SetForaging, {14, 12}, 1);
command(world, CommandKind::SetForaging, {13, 14}, 1);
}
std::size_t count_recipe(const World& world, RecipeId recipe) {
return static_cast<std::size_t>(std::count_if(
world.production_orders().begin(), world.production_orders().end(),
[recipe](const auto& order) { return order.recipe == recipe; }));
}
std::string from_hex(std::string_view hex) {
const auto digit = [](char value) {
return value <= '9' ? value - '0' : value - 'a' + 10;
};
std::string bytes;
for (std::size_t i = 0; i < hex.size(); i += 2) {
bytes.push_back(static_cast<char>(digit(hex[i]) * 16 + digit(hex[i + 1])));
}
return bytes;
}
// Produced by the pre-profile core and header at 60154bd, SHA-256
// 8936352f8f8c939f866195bd434fe58c3bcf9ace49202c937c9cb2a026583d48.
// Checkpoint schema 1 holds an active default-manifest world with simple beds.
const std::string legacy_simple_checkpoint = from_hex(
"53544843484b505401000000b6000000b7000000000000000102030405064708890a0b0c0d0e0f10"
"0100000000000000000000000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72d"
"c0984cfc62cd83d1020000001100736574746c656d656e742e636f6c6f6e790500312e302e3008e1"
"8a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c0890f00736574746c656d65"
"6e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530d0000002f010000000000000500000005000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000000010100000000"
"00000001000000000000000100000000000000010000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000100000002000000"
"0200000000000000000000000000000000000000000000000000000000ada3be851474c1ab6aa6bb"
"0efc1a3cc103430f5b1a69fd602ec6bf02b93f98c6");
struct [[= Void::Testing::name("ProfileTests")]] ProfileTests : Void::Testing::Suite<ProfileTests> {
[[= Void::Testing::tag("profile")]] Test test_compiled_profiles_resolve_exact_content();
[[= Void::Testing::tag("profile")]] Test test_both_first_colonies_complete_with_the_selected_material_chain();
[[= Void::Testing::tag("profile")]] Test test_furnished_rooms_use_the_selected_bed_recipe();
[[= Void::Testing::tag("profile")]] Test test_profiles_replay_and_resume_mid_delivery();
[[= Void::Testing::tag("profile")]] Test test_historical_default_simple_and_inactive_worlds_keep_their_mode();
[[= Void::Testing::tag("profile")]] Test test_supported_profile_gate_rejects_mismatches_without_mutation();
[[= Void::Testing::tag("profile")]] Test test_scenario_profile_cannot_change_after_start();
};
Test ProfileTests::test_compiled_profiles_resolve_exact_content() {
const auto original = checked(colony_rules(ColonyProfile::Default));
const auto planks = checked(colony_rules(ColonyProfile::PlankBeds));
require(original.manifest() == checked(default_rules_manifest()) &&
original.bed_mode() == BedConstructionMode::Staged, "default compilation changed");
require(planks.manifest().packages().size() == 3 && planks.bed_mode() == BedConstructionMode::Plank,
"optional package did not select plank construction");
auto catalog = checked(builtin_rule_packages());
std::reverse(catalog.begin(), catalog.end());
const std::array selected{std::string{"settlement.plankbeds"}};
const auto shuffled = checked(resolve_rules(catalog, selected));
require(shuffled == planks.manifest() &&
checked(compile_colony_rules(shuffled)).profile() == ColonyProfile::PlankBeds,
"catalog order changed the compiled profile");
require(!colony_rules(static_cast<ColonyProfile>(255)), "unknown profile compiled");
require(!make_colony_checkpoint(ColonyProfile::Default, 1),
"parallel one-worker colony was created");
}
Test ProfileTests::test_both_first_colonies_complete_with_the_selected_material_chain() {
for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) {
auto candidate = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference));
require(!candidate.world_id.is_nil() && candidate.city == 1, "colony identity is missing");
require(validate_colony_checkpoint(candidate).has_value(), "new colony profile failed validation");
auto& world = *candidate.world;
queue_three_beds(world);
const bool staged = profile == ColonyProfile::Default;
require(world.staged_beds() == staged &&
count_recipe(world, RecipeId::SawPlank) == (staged ? 0U : 3U),
"bed command ignored its selected recipe");
for (const auto& order : world.production_orders()) {
if (order.recipe != RecipeId::BuildBed) continue;
require(order.bed_material() == (staged ?
(order.bed_base == BedBase::Stone ? ItemType::Stone : ItemType::Wood) : ItemType::Plank),
"material preview does not match the enacted profile");
}
for (int tick = 0; tick < 1200 && !world.scenario_progress().completed; ++tick) world.step();
require(world.scenario_progress().completed && world.scenario_progress().assigned_beds == 3,
"selected first-colony profile did not complete the three-bed food objective");
require(stock(world, ItemType::Cloth) == (staged ? 6U : 12U) &&
stock(world, ItemType::Stone) == (staged ? 5U : 6U),
"bed profile consumed the wrong cloth or foundation material");
require(std::all_of(world.production_orders().begin(), world.production_orders().end(),
[](const auto& order) { return order.state == JobState::Completed; }),
"selected profile left an unfinished prerequisite");
}
}
Test ProfileTests::test_furnished_rooms_use_the_selected_bed_recipe() {
for (auto mode : {BedConstructionMode::Staged, BedConstructionMode::Plank}) {
World world(64, 20, 18, 1, ExecutionMode::SerialReference);
const auto builder = world.spawn_agent({5, 3});
const auto carpenter = world.spawn_agent({3, 3});
const auto materials = world.add_storage({3, 4}, 128);
world.stock_storage(materials, ItemType::Wood, 80);
world.stock_storage(materials, ItemType::Stone, 6);
world.stock_storage(materials, ItemType::Cloth, 2);
const auto food = world.add_storage({2, 4}, 200, StorageKind::Pantry);
world.stock_storage(food, ItemType::Berries, 200);
world.start_scenario({4, 3}, mode);
command(world, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Builder), {}, builder);
command(world, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter);
const RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, RoomTemplate::Miner};
command(world, CommandKind::PlaceRoom, plan.first, plan.placement_value(), plan.last);
require(count_recipe(world, RecipeId::SawPlank) == (mode == BedConstructionMode::Plank ? 1U : 0U),
"furnished room ignored the optional plank prerequisite");
for (int tick = 0; tick < 2200 && world.scenario_progress().assigned_beds == 0; ++tick) world.step();
require(world.scenario_progress().assigned_beds == 1, "room bed did not complete");
require(stock(world, ItemType::Cloth) == (mode == BedConstructionMode::Plank ? 2U : 0U),
"furnished room consumed the wrong bedding");
}
}
Test ProfileTests::test_profiles_replay_and_resume_mid_delivery() {
const auto catalog = checked(builtin_rule_packages());
for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) {
auto initial = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference));
queue_three_beds(*initial.world);
const auto initial_bytes = checkpoint(*initial.world, initial);
std::vector<WorldCheckpoint> runs;
for (std::size_t workers : {2U, 6U, 12U}) {
runs.push_back(checked(decode_checkpoint(initial_bytes, catalog, workers)));
}
std::shared_ptr<const World> held;
std::string held_bytes;
bool resumed = false;
for (int tick = 0; tick < 500; ++tick) {
initial.world->step();
for (auto& run : runs) run.world->step();
const auto expected = checkpoint(*initial.world, initial);
for (const auto& run : runs) {
require(checkpoint(*run.world, run) == expected, "profile parallel replay diverged");
}
if (!resumed && std::any_of(initial.world->agents().begin(), initial.world->agents().end(),
[](const auto& agent) {
return agent.state == AgentState::Hauling &&
(agent.inventory.item_count(ItemType::Wood) != 0 ||
agent.inventory.item_count(ItemType::Stone) != 0 ||
agent.inventory.item_count(ItemType::Plank) != 0 ||
agent.inventory.item_count(ItemType::Cloth) != 0);
})) {
held = initial.world->capture();
held_bytes = saved(*held);
runs.push_back(checked(decode_checkpoint(expected, catalog, 1, ExecutionMode::SerialReference)));
resumed = true;
}
}
require(resumed && saved(*held) == held_bytes, "held material snapshot changed or was never captured");
require(initial.world->scenario_progress().assigned_beds == 3, "replay profile failed its bed objective");
}
}
Test ProfileTests::test_historical_default_simple_and_inactive_worlds_keep_their_mode() {
const auto catalog = checked(builtin_rule_packages());
auto legacy = checked(decode_checkpoint(legacy_simple_checkpoint, catalog, 1, ExecutionMode::SerialReference));
require(legacy.world->scenario_active() && !legacy.world->staged_beds(),
"authentic schema-1 fixture lost its historical mode");
const auto before = saved(*legacy.world);
require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == before,
"default profile gate rewrote a historical simple colony");
auto current = checked(decode_checkpoint(checkpoint(*legacy.world, legacy), catalog, 1, ExecutionMode::SerialReference));
require(validate_colony_checkpoint(current).has_value() && saved(*current.world) == before,
"resaving historical defaults changed their enacted rules");
// The corresponding v2 raw format omitted the staged flag and used an FNV footer.
auto raw_v2 = before;
raw_v2[8] = 2;
raw_v2.pop_back();
auto digest = Void::Hash::fnv1a64_offset_basis;
digest = Void::Hash::fnv1a64_update(digest, std::as_bytes(std::span{raw_v2}));
for (unsigned shift = 0; shift < 64; shift += 8) raw_v2.push_back(static_cast<char>(digest >> shift));
std::istringstream input(raw_v2, std::ios::binary);
legacy.world = World::read_save(input, 1, ExecutionMode::SerialReference);
require(legacy.world->scenario_active() && !legacy.world->staged_beds() &&
validate_colony_checkpoint(legacy).has_value(), "active raw-v2 import lost default compatibility");
legacy.world = std::make_unique<World>(17, 5, 5, 1, ExecutionMode::SerialReference);
const auto inactive_before = saved(*legacy.world);
require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == inactive_before,
"inactive historical default was rejected or modified");
}
Test ProfileTests::test_supported_profile_gate_rejects_mismatches_without_mutation() {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 1, ExecutionMode::SerialReference));
const auto before = saved(*candidate.world);
candidate.rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest();
auto invalid = validate_colony_checkpoint(candidate);
require(!invalid && invalid.error().package == "settlement.plankbeds" &&
saved(*candidate.world) == before, "staged world with plank rules was accepted or changed");
auto catalog = checked(builtin_rule_packages());
auto altered = std::string(catalog.back().canonical_json());
const auto work = altered.find("\"work_ticks\":14");
require(work != std::string::npos, "plank fixture has no work duration");
altered.replace(work, std::string_view{"\"work_ticks\":14"}.size(), "\"work_ticks\":15");
catalog.back() = checked(load_rule_package("altered/plankbeds", altered));
const std::array selected{std::string{"settlement.plankbeds"}};
candidate.rules = checked(resolve_rules(catalog, selected));
require(!validate_colony_checkpoint(candidate) && saved(*candidate.world) == before,
"modified recipe content was accepted as an implemented profile");
const std::array core_only{std::string{"settlement.core"}};
require(!compile_colony_rules(checked(resolve_rules(catalog, core_only))), "incomplete profile compiled");
const auto extra = checked(load_rule_package("extra",
R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})"));
catalog.push_back(extra);
const std::array with_extra{std::string{"settlement.colony"}, std::string{"game.extra"}};
require(!compile_colony_rules(checked(resolve_rules(catalog, with_extra))), "unimplemented package compiled");
require(!resolve_rules(catalog, std::array{std::string{"missing.package"}}), "missing package resolved");
}
Test ProfileTests::test_scenario_profile_cannot_change_after_start() {
World world(17, 5, 5, 1, ExecutionMode::SerialReference);
const auto before = saved(world);
Void::Testing::expect_throw<std::invalid_argument>([&] {
world.start_scenario({2, 2}, static_cast<BedConstructionMode>(255));
});
require(saved(world) == before, "invalid mode changed the world");
world.start_scenario({2, 2}, BedConstructionMode::Plank);
const auto started = saved(world);
Void::Testing::expect_throw<std::invalid_argument>([&] { world.start_scenario({2, 2}); });
require(saved(world) == started, "started colony changed its creation profile");
}
} // namespace
+407
View File
@@ -0,0 +1,407 @@
#include "settlement/core/inventory_transaction.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Testing/Suite.hpp>
#include <array>
#include <chrono>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using Void::Testing::Test;
constexpr auto maximum = std::numeric_limits<std::uint32_t>::max();
void require(bool condition, const char* message = "quantity transfer invariant failed") {
if (!condition) throw std::runtime_error(message);
}
Storage source() {
return {7, {3, 3}, 20, 0, {{ItemType::Wood, 4, 3}, {ItemType::Stone, 3, 2}}};
}
void same_inventory(const Inventory& actual, const Inventory& expected) {
for (std::size_t i = 1; i <= item_type_count; ++i) {
require(actual.item_count(static_cast<ItemType>(i)) == expected.item_count(static_cast<ItemType>(i)),
"failed pickup changed destination");
}
}
void same_storage(const Storage& actual, const Storage& expected) {
require(actual.id == expected.id && actual.position == expected.position && actual.capacity == expected.capacity &&
actual.reserved_slots == expected.reserved_slots && actual.kind == expected.kind &&
actual.items.size() == expected.items.size(), "failed pickup changed storage metadata");
for (std::size_t i = 0; i < actual.items.size(); ++i) {
require(actual.items[i].type == expected.items[i].type && actual.items[i].count == expected.items[i].count &&
actual.items[i].reserved == expected.items[i].reserved, "failed pickup changed source quantities/order");
}
}
void rejected(Storage& storage, Inventory& inventory, std::span<const MaterialReservation> materials,
QuantityTransferError error, bool slot = false) {
const auto before = storage;
const auto cargo = inventory;
const auto result = withdraw_reserved_materials(storage, inventory, materials, slot);
require(!result && result.error() == error, "pickup accepted bad input or returned the wrong diagnostic");
same_storage(storage, before);
same_inventory(inventory, cargo);
}
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
}
void same_pickup_actor(const Agent& actual, const Agent& expected) {
same_inventory(actual.inventory, expected.inventory);
require(actual.position == expected.position && actual.route == expected.route &&
actual.route_cursor == expected.route_cursor && actual.haul_route == expected.haul_route &&
actual.state == expected.state && actual.storage_id == expected.storage_id &&
actual.production_id == expected.production_id && actual.work_remaining == expected.work_remaining,
"rejected pickup changed actor/route state");
}
std::unique_ptr<World> cabin() {
auto world = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference);
const auto store = world->add_storage({3, 3}, 20);
world->stock_storage(store, ItemType::Plank, 3);
world->stock_storage(store, ItemType::StoneBlock, 2);
static_cast<void>(world->spawn_agent({1, 3}));
world->queue_production({14, 3}, RecipeId::BuildCabin);
world->step();
require(world->agents().front().state == AgentState::FetchingMaterials, "fixture already picked up materials");
return world;
}
// Test-only corruption uses public read views of a nonconst fixture. Production
// code cannot create these malformed sources through the checked save loader.
void at_pickup(World& world) {
auto& agent = const_cast<Agent&>(world.agents().front());
agent.position = world.storages().front().position;
agent.route.clear();
agent.route_cursor = 0;
}
struct [[= Void::Testing::name("QuantityTransactionTests")]] QuantityTransactionTests
: Void::Testing::Suite<QuantityTransactionTests> {
[[= Void::Testing::tag("quantity-transfer")]] Test late_failure_is_atomic();
[[= Void::Testing::tag("quantity-transfer")]] Test nonadjacent_duplicates_and_foreign_stops();
[[= Void::Testing::tag("quantity-transfer")]] Test invalid_selection_and_item_bounds();
[[= Void::Testing::tag("quantity-transfer")]] Test source_invariants_and_underflow();
[[= Void::Testing::tag("quantity-transfer")]] Test cumulative_and_destination_boundaries();
[[= Void::Testing::tag("quantity-transfer")]] Test stable_multiple_erasure_and_output_capacity();
[[= Void::Testing::tag("quantity-transfer")]] Test invalid_capacity_and_slot_overflow_are_atomic();
[[= Void::Testing::tag("quantity-transfer")]] Test real_construction_rejection_keeps_stop_actor_and_routes();
[[= Void::Testing::tag("quantity-transfer")]] Test real_split_lines_and_invalid_storage_selection();
[[= Void::Testing::tag("quantity-transfer")]] Test real_carpentry_invalid_capacity_keeps_pickup_untouched();
[[= Void::Testing::tag("quantity-transfer")]] Test real_meal_pickup_and_overflow_rejection();
[[= Void::Testing::tag("quantity-transfer")]] Test real_multistop_carpentry_reserves_first_ingredient_store();
[[= Void::Testing::tag("quantity-transfer")]] Test direct_crafting_stays_in_storage();
[[= Void::Testing::tag("quantity-transfer")]] Test owner_fault_preserves_last_healthy_publication();
};
Test QuantityTransactionTests::late_failure_is_atomic() {
auto storage = source();
Inventory inventory;
inventory.add(ItemType::Wood, 9);
const std::array materials{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 3}};
rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock);
inventory.add(ItemType::Stone, maximum);
auto valid = materials;
valid[1].count = 1;
rejected(storage, inventory, valid, QuantityTransferError::Overflow, true);
}
Test QuantityTransactionTests::nonadjacent_duplicates_and_foreign_stops() {
auto storage = source();
Inventory inventory;
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}, MaterialReservation{9, ItemType::Wood, 5},
MaterialReservation{7, ItemType::Stone, 2}, MaterialReservation{7, ItemType::Wood, 2}};
require(withdraw_reserved_materials(storage, inventory, materials).has_value());
require(inventory.item_count(ItemType::Wood) == 3 && inventory.item_count(ItemType::Stone) == 2);
require(storage.items[0].count == 1 && storage.items[0].reserved == 0 && storage.items[1].count == 1 &&
storage.items[1].reserved == 0);
auto insufficient = source();
const std::array duplicates{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 1},
MaterialReservation{7, ItemType::Wood, 2}};
rejected(insufficient, inventory, duplicates, QuantityTransferError::InsufficientStock);
}
Test QuantityTransactionTests::invalid_selection_and_item_bounds() {
auto storage = source();
Inventory inventory;
const std::array valid{MaterialReservation{7, ItemType::Wood, 1}};
rejected(storage, inventory, {}, QuantityTransferError::MissingSelection);
const std::array foreign{MaterialReservation{8, ItemType::Wood, 1}};
rejected(storage, inventory, foreign, QuantityTransferError::MissingSelection);
const std::array zero_id{MaterialReservation{0, ItemType::Wood, 1}};
rejected(storage, inventory, zero_id, QuantityTransferError::MissingSelection);
for (const auto type : {ItemType::None, static_cast<ItemType>(item_type_count + 1), static_cast<ItemType>(255)}) {
const std::array bad{MaterialReservation{7, type, 1}};
rejected(storage, inventory, bad, QuantityTransferError::InvalidMaterial);
}
const std::array zero{MaterialReservation{7, ItemType::Wood, 0}};
rejected(storage, inventory, zero, QuantityTransferError::InvalidMaterial);
storage.id = 0;
rejected(storage, inventory, zero_id, QuantityTransferError::InvalidStorage);
storage = source();
storage.kind = static_cast<StorageKind>(255);
rejected(storage, inventory, valid, QuantityTransferError::InvalidStorage);
}
Test QuantityTransactionTests::source_invariants_and_underflow() {
Inventory inventory;
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}};
const std::array missing{MaterialReservation{7, ItemType::Plank, 1}};
auto storage = source();
rejected(storage, inventory, missing, QuantityTransferError::InsufficientStock);
for (int fault = 0; fault < 8; ++fault) {
storage = source();
switch (fault) {
case 0: storage.items[0].reserved = 5; break;
case 1: storage.items[0].count = 0; break;
case 2: storage.items[0].type = ItemType::None; break;
case 3: storage.items[0].type = static_cast<ItemType>(item_type_count + 1); break;
case 4: storage.items[1].type = ItemType::Wood; break;
case 5: std::swap(storage.items[0], storage.items[1]); break;
case 6: storage.kind = StorageKind::Pantry; break;
case 7: storage.items[1].reserved = 4; break;
}
rejected(storage, inventory, materials, QuantityTransferError::InvalidStock);
}
storage = source();
storage.items[0].reserved = 0;
rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock);
storage.items[0].reserved = storage.items[0].count = 1;
const std::array too_many{MaterialReservation{7, ItemType::Wood, 2}};
rejected(storage, inventory, too_many, QuantityTransferError::InsufficientStock);
}
Test QuantityTransactionTests::cumulative_and_destination_boundaries() {
Storage storage{7, {}, maximum, 0, {{ItemType::Wood, maximum, maximum}}};
Inventory inventory;
const std::array overflow{MaterialReservation{7, ItemType::Wood, maximum},
MaterialReservation{8, ItemType::Stone, 1}, MaterialReservation{7, ItemType::Wood, 1}};
rejected(storage, inventory, overflow, QuantityTransferError::Overflow);
const std::array exact{MaterialReservation{7, ItemType::Wood, maximum - 1}, MaterialReservation{7, ItemType::Wood, 1}};
require(withdraw_reserved_materials(storage, inventory, exact).has_value());
require(storage.items.empty() && inventory.item_count(ItemType::Wood) == maximum);
storage = source();
const std::array one{MaterialReservation{7, ItemType::Wood, 1}};
rejected(storage, inventory, one, QuantityTransferError::Overflow);
Inventory boundary;
boundary.add(ItemType::Wood, maximum - 1);
require(withdraw_reserved_materials(storage, boundary, one).has_value());
require(boundary.item_count(ItemType::Wood) == maximum);
}
Test QuantityTransactionTests::stable_multiple_erasure_and_output_capacity() {
Storage storage{7, {}, 10, 0, {{ItemType::Wood, 2, 2}, {ItemType::Stone, 3, 1},
{ItemType::Plank, 1, 1}, {ItemType::StoneBlock, 4, 0}}};
Inventory inventory;
const std::array materials{MaterialReservation{7, ItemType::Plank, 1}, MaterialReservation{7, ItemType::Wood, 2}};
require(withdraw_reserved_materials(storage, inventory, materials, true).has_value());
require(storage.reserved_slots == 1 && storage.items.size() == 2 &&
storage.items[0].type == ItemType::Stone && storage.items[0].count == 3 && storage.items[0].reserved == 1 &&
storage.items[1].type == ItemType::StoneBlock && storage.items[1].count == 4 && storage.items[1].reserved == 0);
Storage full{7, {}, 1, 0, {{ItemType::Wood, 1, 1}}};
const std::array one{MaterialReservation{7, ItemType::Wood, 1}};
require(withdraw_reserved_materials(full, inventory, one, true).has_value());
require(full.items.empty() && full.reserved_slots == 1 && full.total_items() + full.reserved_slots == full.capacity);
}
Test QuantityTransactionTests::invalid_capacity_and_slot_overflow_are_atomic() {
Inventory inventory;
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}};
for (int fault = 0; fault < 4; ++fault) {
auto storage = source();
switch (fault) {
case 0: storage.capacity = 0; break;
case 1: storage.capacity = 6; break;
case 2: storage.reserved_slots = maximum; break;
case 3: storage.capacity = 7; storage.reserved_slots = 1; break;
}
rejected(storage, inventory, materials, QuantityTransferError::Capacity, true);
}
}
Test QuantityTransactionTests::real_construction_rejection_keeps_stop_actor_and_routes() {
auto world = cabin();
at_pickup(*world);
auto& storage = const_cast<Storage&>(world->storages().front());
storage.items.back().reserved = 1; // The first item is valid; the second fails.
const auto before = storage;
const auto actor = world->agents().front();
const auto order = world->production_orders().front();
bool failed = false;
try { world->step(); } catch (const std::logic_error&) { failed = true; }
require(failed);
same_storage(storage, before);
same_pickup_actor(world->agents().front(), actor);
const auto& after = world->production_orders().front();
require(after.collected_stops == order.collected_stops && after.delivery_stops.size() == order.delivery_stops.size());
require(after.delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next);
}
Test QuantityTransactionTests::real_split_lines_and_invalid_storage_selection() {
auto world = cabin();
at_pickup(*world);
auto& order = const_cast<ProductionOrder&>(world->production_orders().front());
const auto id = world->storages().front().id;
order.materials = {{id, ItemType::Plank, 1}, {id, ItemType::StoneBlock, 2}, {id, ItemType::Plank, 2}};
for (const auto invalid : {StorageId{0}, StorageId{123}, id}) {
order.delivery_stops.front().storage_id = invalid;
if (invalid == id) { // A real storage, but no selected reservation.
for (auto& material : order.materials) material.storage_id = 123;
}
const auto before = world->storages().front();
const auto actor = world->agents().front();
const auto route = order.delivery_stops.front().route_to_next;
bool failed = false;
try { world->step(); } catch (const std::logic_error&) { failed = true; }
require(failed && order.collected_stops == 0 && order.delivery_stops.front().route_to_next == route);
same_pickup_actor(world->agents().front(), actor);
same_storage(world->storages().front(), before);
}
for (auto& material : order.materials) material.storage_id = id;
world->step();
require(order.collected_stops == 1 && world->storages().front().items.empty());
require(world->agents().front().inventory.item_count(ItemType::Plank) == 3 &&
world->agents().front().inventory.item_count(ItemType::StoneBlock) == 2);
for (int i = 0; i < 80 && order.state != JobState::Completed; ++i) world->step();
require(order.state == JobState::Completed && world->agents().front().inventory.empty());
}
Test QuantityTransactionTests::real_carpentry_invalid_capacity_keeps_pickup_untouched() {
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
const auto store = world.add_storage({3, 3}, 1);
world.stock_storage(store, ItemType::Wood, 1);
const auto carpenter = world.spawn_agent({1, 3});
world.start_scenario({8, 3});
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
world.queue_production({8, 3}, RecipeId::CraftMedicineCabinet);
world.step();
require(world.agents().front().state == AgentState::FetchingMaterials);
at_pickup(world);
auto& storage = const_cast<Storage&>(world.storages().front());
storage.reserved_slots = 1; // Already over capacity before this pickup.
const auto before = storage;
const auto actor = world.agents().front();
const auto order = world.production_orders().front();
bool failed = false;
try { world.step(); } catch (const std::logic_error&) { failed = true; }
require(failed && world.production_orders().front().collected_stops == 0);
same_storage(storage, before);
same_pickup_actor(world.agents().front(), actor);
require(world.production_orders().front().delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next);
}
Test QuantityTransactionTests::real_meal_pickup_and_overflow_rejection() {
World world(44, 32, 32, 1, ExecutionMode::SerialReference);
const auto pantry = world.add_storage({28, 4}, 50, StorageKind::Pantry);
world.stock_storage(pantry, ItemType::Berries, 40);
static_cast<void>(world.spawn_agent({4, 4}));
world.enable_hunger();
for (int i = 0; i < 500 && world.agents().front().state != AgentState::GoingToEat; ++i) world.step();
require(world.agents().front().state == AgentState::GoingToEat);
auto& actor = const_cast<Agent&>(world.agents().front());
at_pickup(world);
actor.inventory.add(ItemType::Berries, maximum);
const auto agent_before = actor;
const auto storage_before = world.storages().front();
bool failed = false;
try { world.step(); } catch (const std::logic_error&) { failed = true; }
require(failed);
same_pickup_actor(actor, agent_before);
same_storage(world.storages().front(), storage_before);
actor.inventory.remove(ItemType::Berries, maximum);
world.step();
require(actor.state == AgentState::Eating && actor.inventory.item_count(ItemType::Berries) == 1 && actor.storage_id == 0);
require(world.storages().front().item_count(ItemType::Berries) == 39);
for (int i = 0; i < 5; ++i) world.step();
require(world.meals_eaten() == 1 && actor.inventory.empty() && actor.hunger == 0);
}
Test QuantityTransactionTests::real_multistop_carpentry_reserves_first_ingredient_store() {
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
const auto stone = world.add_storage({3, 3}, 1);
const auto wood = world.add_storage({6, 3}, 1);
world.stock_storage(stone, ItemType::Stone, 1);
world.stock_storage(wood, ItemType::Wood, 1);
const auto carpenter = world.spawn_agent({2, 3});
world.start_scenario({8, 3});
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
world.queue_production({8, 3}, RecipeId::CraftMiningRack);
world.step();
const auto& order = world.production_orders().front();
require(order.materials.front().storage_id == wood && order.delivery_stops.front().storage_id == stone);
for (int i = 0; i < 20 && order.collected_stops == 0; ++i) world.step();
require(order.collected_stops == 1 && world.find_storage(stone)->reserved_slots == 0 &&
world.find_storage(wood)->reserved_slots == 0);
for (int i = 0; i < 20 && order.collected_stops == 1; ++i) world.step();
require(order.collected_stops == 2 && world.find_storage(wood)->items.empty() &&
world.find_storage(wood)->reserved_slots == 1);
for (int i = 0; i < 80 && world.find_storage(wood)->item_count(ItemType::MiningRack) == 0; ++i) world.step();
require(world.find_storage(wood)->item_count(ItemType::MiningRack) == 1 &&
world.find_storage(wood)->reserved_slots == 0 && world.find_storage(stone)->items.empty());
}
Test QuantityTransactionTests::direct_crafting_stays_in_storage() {
World world(51, 24, 24, 1, ExecutionMode::SerialReference);
const auto store = world.add_storage({3, 3}, 2);
world.stock_storage(store, ItemType::Wood, 1);
world.stock_storage(store, ItemType::Stone, 1);
static_cast<void>(world.spawn_agent({2, 3}));
world.queue_production({5, 3}, RecipeId::SawPlank);
world.queue_production({7, 3}, RecipeId::CutStoneBlock);
for (int i = 0; i < 80; ++i) {
world.step();
require(world.agents().front().inventory.empty(), "direct recipe created physical carrier cargo");
}
const auto* storage = world.find_storage(store);
require(storage->item_count(ItemType::Wood) == 0 && storage->item_count(ItemType::Stone) == 0 &&
storage->item_count(ItemType::Plank) == 1 && storage->item_count(ItemType::StoneBlock) == 1 &&
storage->reserved_slots == 0);
}
Test QuantityTransactionTests::owner_fault_preserves_last_healthy_publication() {
using namespace std::chrono_literals;
auto world = cabin();
at_pickup(*world);
auto* fixture = world.get();
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.clock = clock};
options.observer = [fixture](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeTick) {
const_cast<Storage&>(fixture->storages().front()).items.back().reserved = 1;
}
};
auto rules = default_rules_manifest();
require(rules.has_value());
Void::Uuid::Uuid id;
id.bytes.back() = 71;
SimulationRuntime runtime({std::move(world), id, 1, std::move(*rules)}, std::move(options));
const auto previous = runtime.latest();
const auto healthy = bytes(*previous->world);
require(clock->advance(50ms).has_value());
RuntimeSubmission fence;
const auto limit = std::chrono::steady_clock::now() + 5s;
do {
fence = runtime.synchronize();
if (fence.admission != RuntimeAdmission::Busy) break;
require(std::chrono::steady_clock::now() < limit, "runtime fence admission timed out");
std::this_thread::yield();
} while (true);
require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(5s) == std::future_status::ready);
require(fence.completion.get().outcome == RuntimeOutcome::Faulted && runtime.view().state == RuntimeState::Faulted &&
runtime.view().failure && !runtime.snapshot_for_save());
require(runtime.latest() == previous && bytes(*runtime.latest()->world) == healthy,
"owner published the rejected pickup candidate");
}
} // namespace
+1 -1
View File
@@ -38,7 +38,7 @@ void require(bool condition, std::string_view message) {
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
}
+7
View File
@@ -218,6 +218,13 @@ Test RulesTests::test_builtin_default_and_known_digest() {
const auto first = checked(default_rules_manifest());
const auto second = checked(default_rules_manifest());
require(first == second && first.packages().size() == 2, "default rules were not reproducible");
// Recorded by profile-baseline.exe against the compiled pre-profile core.
require(rules_digest_hex(first.fingerprint()) ==
"06d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1",
"default profile fingerprint changed");
require(first.canonical_json() ==
R"({"packages":[{"id":"settlement.colony","sha256":"08e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089","version":"1.0.0"},{"id":"settlement.core","sha256":"61b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab7124188d337f","version":"1.0.0"}],"schema":1})",
"default canonical manifest changed");
const auto empty = load(package("game.core"));
require(rules_digest_hex(empty.identity().content_sha256) == "f6d1f704ccbb3ec707d2e1ba7b0db27dab8494b7787eeee10f1449dabee1477a", "package SHA-256 differs from the canonical-byte known vector");
require(empty.definitions().empty(), "empty package gained a definition");
+2 -2
View File
@@ -28,7 +28,7 @@ static_assert(!std::is_copy_constructible_v<World>);
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
world.write_save(stream, WorldSaveFormat::Current15);
return stream.str();
}
@@ -113,7 +113,7 @@ Test SnapshotTests::test_mid_delivery_and_paused_command_state_survives_owner()
source->step();
carrying = source->assignment_path_cache_hits() > 0 &&
std::any_of(source->agents().begin(), source->agents().end(), [](const Agent& agent) {
return !agent.inventory.empty() && agent.production_index != no_entity_index;
return !agent.inventory.empty() && agent.production_id != 0;
});
}
require(carrying);
+395
View File
@@ -0,0 +1,395 @@
#include "viewer_session.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <atomic>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <fstream>
#include <mutex>
#include <sstream>
#include <thread>
namespace {
using namespace settlement;
using namespace settlement::viewer;
using namespace std::chrono_literals;
using Void::Testing::require;
using Void::Testing::Test;
struct TempFiles {
std::filesystem::path root;
TempFiles() {
const auto id = Void::Uuid::try_v4();
require(id.has_value());
root = std::filesystem::temp_directory_path() /
("settlement-client-" + id->to_string());
require(std::filesystem::create_directory(root));
}
~TempFiles() {
std::error_code error;
std::filesystem::remove_all(root, error);
}
};
struct Gate {
std::mutex mutex;
std::condition_variable changed;
bool entered = false;
bool released = false;
void hold() {
std::unique_lock lock(mutex);
entered = true;
changed.notify_all();
if (!changed.wait_for(lock, 5s, [&] { return released; })) throw std::runtime_error("gate timeout");
}
void wait() {
std::unique_lock lock(mutex);
require(changed.wait_for(lock, 5s, [&] { return entered; }));
}
void release() {
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
};
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
void write(const std::filesystem::path& path, std::string_view contents) {
std::ofstream file(path, std::ios::binary);
file.write(contents.data(), static_cast<std::streamsize>(contents.size()));
file.close();
require(file.good());
}
template<class Predicate>
std::vector<ViewerEvent> pump_until(ViewerSession& session, Predicate done) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
std::vector<ViewerEvent> events;
while (!done(events)) {
auto current = session.poll();
for (auto& event : current) events.push_back(std::move(event));
require(std::chrono::steady_clock::now() < deadline);
std::this_thread::yield();
}
return events;
}
bool has(const std::vector<ViewerEvent>& events, ViewerEventKind kind) {
return std::any_of(events.begin(), events.end(), [kind](const auto& event) { return event.kind == kind; });
}
void flush_owner(ViewerSession& session) {
for (;;) {
auto sync = session.runtime().synchronize();
if (sync.admission == RuntimeAdmission::Busy) {
std::this_thread::yield();
continue;
}
require(sync.admission == RuntimeAdmission::Accepted);
require(sync.completion.wait_for(5s) == std::future_status::ready);
require(sync.completion.get().outcome == RuntimeOutcome::Completed);
return;
}
}
struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void::Testing::Suite<ViewerSessionTests> {
[[= Void::Testing::tag("viewer-session")]] Test test_commands_wait_for_commit_and_keep_rejected_drafts_retryable();
[[= Void::Testing::tag("viewer-session")]] Test test_long_tick_allows_reset_without_joining_and_fences_old_intents();
[[= Void::Testing::tag("viewer-session")]] Test test_title_load_and_later_failed_load_supersede_old_preparation();
[[= Void::Testing::tag("viewer-session")]] Test test_unsupported_profile_and_dimensions_keep_current_world();
[[= Void::Testing::tag("viewer-session")]] Test test_save_keeps_captured_session_across_reset();
[[= Void::Testing::tag("viewer-session")]] Test test_guest_view_is_read_only_and_leave_installs_received_world();
[[= Void::Testing::tag("viewer-session")]] Test test_runtime_busy_keeps_the_same_intent_until_commit();
[[= Void::Testing::tag("viewer-session")]] Test test_initial_candidate_requires_supported_rules_and_dimensions();
[[= Void::Testing::tag("viewer-session")]] Test test_fault_retains_view_and_explicit_load_recovers();
[[= Void::Testing::tag("viewer-session")]] Test test_failed_guest_transitions_retain_received_replica();
};
Test ViewerSessionTests::test_commands_wait_for_commit_and_keep_rejected_drafts_retryable() {
ViewerSession session(2, {.command_capacity = 1});
const auto before = session.world();
const SessionPayload payload = CommandPayload{CommandKind::SetPriority, {}, 1};
const auto first = session.submit(payload);
require(first.has_value());
require(session.submit(payload) == first);
require(!session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}));
require(session.world()->work_priority() == before->work_priority());
const auto changed = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
require(changed.front().command == *first);
require(changed.front().status == CommandStatus::Accepted);
require(!session.pending(*first));
require(session.world()->work_priority() == WorkPriority::FoodFirst);
require(session.world()->tick() == before->tick());
require(before->work_priority() == WorkPriority::Balanced);
require(session.submit(CommandPayload{CommandKind::PlaceBed, {15, 16}, 0}).has_value());
const auto rejected = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
require(rejected.front().status == CommandStatus::InvalidTarget);
require(session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}).has_value());
const auto paused = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
require(paused.front().status == CommandStatus::Accepted);
require(session.world()->paused());
}
Test ViewerSessionTests::test_long_tick_allows_reset_without_joining_and_fences_old_intents() {
const auto clock = std::make_shared<Void::Time::ManualClock>();
auto gate = std::make_shared<Gate>();
std::atomic<bool> block{true};
ViewerSessionOptions options;
options.runtime.clock = clock;
options.runtime.observer = [gate, &block](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeTick && block.exchange(false)) gate->hold();
};
ViewerSession session(2, std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
session.set_ticking(true);
static_cast<void>(session.poll());
flush_owner(session);
require(clock->advance(50ms).has_value());
session.runtime().notify_clock();
gate->wait();
const auto old = session.runtime().latest();
require(session.submit(CommandPayload{CommandKind::SetPriority, {}, 1}).has_value());
static_cast<void>(session.poll());
session.new_colony();
const auto pending = session.poll();
require(pending.empty());
require(session.changing_world());
require(session.world() == old->world);
gate->release();
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Replaced); });
require(!has(events, ViewerEventKind::Command));
require(session.runtime().latest()->identity.session != old->identity.session);
require(session.world()->work_priority() == WorkPriority::Balanced);
}
Test ViewerSessionTests::test_title_load_and_later_failed_load_supersede_old_preparation() {
TempFiles files;
const auto original = make_first_colony(2);
write(files.root / "old.settlement", bytes(*original));
auto gate = std::make_shared<Gate>();
std::atomic<bool> block{true};
ViewerSessionOptions options;
options.files.read_observer = [gate, &block](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && block.exchange(false)) gate->hold();
};
ViewerSession session(2, std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto before = session.runtime().latest();
session.load(files.root / "old.settlement");
gate->wait();
session.load(files.root / "missing.settlement");
require(session.poll().empty());
gate->release();
const auto failed = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
require(!has(failed, ViewerEventKind::Replaced));
require(session.runtime().latest()->identity == before->identity);
require(!session.changing_world());
session.load(files.root / "old.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(session.runtime().latest()->identity.world != before->identity.world);
require(session.world()->tick() == 0);
require(bytes(*session.world()) == bytes(*original));
}
Test ViewerSessionTests::test_unsupported_profile_and_dimensions_keep_current_world() {
TempFiles files;
ViewerSession session(2);
const auto initial = session.runtime().latest();
auto catalog = builtin_rule_packages();
require(catalog.has_value());
const std::array selected{std::string{"settlement.core"}};
const auto rules = resolve_rules(*catalog, selected);
require(rules.has_value());
const auto custom = encode_checkpoint(*initial->world, initial->identity.world, 1, *rules);
require(custom.has_value());
write(files.root / "custom.settlement", *custom);
session.load(files.root / "custom.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
require(session.runtime().latest() == initial);
World small(1, 16, 16);
write(files.root / "small.settlement", bytes(small));
session.load(files.root / "small.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
require(session.runtime().latest() == initial);
write(files.root / "broken.settlement", "STHCHKPTmalformed");
session.load(files.root / "broken.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
require(session.runtime().latest() == initial);
}
Test ViewerSessionTests::test_save_keeps_captured_session_across_reset() {
TempFiles files;
ViewerSession session(2);
const auto before = session.runtime().latest();
session.save(files.root / "captured.settlement");
session.new_colony();
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Replaced); });
require(!has(events, ViewerEventKind::Saved));
require(session.runtime().latest()->identity.world != before->identity.world);
CheckpointFiles reader;
CheckpointLoadResult loaded = std::unexpected{CheckpointFileDiagnostic{CheckpointFileError::Io, "waiting"}};
const auto limit = std::chrono::steady_clock::now() + 5s;
while (!loaded) {
auto operation = reader.try_load(files.root / "captured.settlement");
require(operation.admission == CheckpointLoadAdmission::Accepted);
require(operation.completion.wait_for(5s) == std::future_status::ready);
loaded = operation.completion.get();
require(std::chrono::steady_clock::now() < limit);
}
require(loaded->world_id == before->identity.world);
require(bytes(*loaded->world) == bytes(*before->world));
}
Test ViewerSessionTests::test_guest_view_is_read_only_and_leave_installs_received_world() {
ViewerSession session(2);
auto* owner = &session.runtime();
const auto before = session.runtime().latest();
session.enter_guest();
require(!session.world());
require(!session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}));
auto incoming = make_first_colony(2);
const auto receipt = incoming->apply_command({1, 1, CommandKind::SetPriority, {}, 2});
require(receipt.status == CommandStatus::Accepted);
const auto expected = bytes(*incoming);
session.receive_guest(std::move(incoming));
const auto held = session.world();
require(bytes(*held) == expected);
session.leave_guest();
require(session.world() == held);
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(&session.runtime() == owner);
require(session.runtime().latest()->identity.session != before->identity.session);
require(bytes(*session.world()) == expected);
require(bytes(*held) == expected);
require(!session.guest());
}
Test ViewerSessionTests::test_runtime_busy_keeps_the_same_intent_until_commit() {
const auto clock = std::make_shared<Void::Time::ManualClock>();
auto gate = std::make_shared<Gate>();
std::atomic<bool> block{true};
ViewerSessionOptions options;
options.runtime.capacity = 1;
options.runtime.clock = clock;
options.runtime.observer = [gate, &block](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeTick && block.exchange(false)) gate->hold();
};
ViewerSession session(2, std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
session.set_ticking(true);
static_cast<void>(session.poll());
flush_owner(session);
require(clock->advance(50ms).has_value());
session.runtime().notify_clock();
gate->wait();
auto occupying = session.runtime().synchronize();
require(occupying.admission == RuntimeAdmission::Accepted);
require(session.runtime().synchronize().admission == RuntimeAdmission::Busy);
const auto command = session.submit(CommandPayload{CommandKind::SetPriority, {}, 1});
require(command.has_value());
require(session.poll().empty());
require(session.pending(*command));
require(session.world()->work_priority() == WorkPriority::Balanced);
gate->release();
const auto result = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
require(result.front().command == *command && result.front().status == CommandStatus::Accepted);
require(session.world()->next_command_sequence(colony_host) == 2);
}
Test ViewerSessionTests::test_initial_candidate_requires_supported_rules_and_dimensions() {
const auto id = Void::Uuid::try_v4();
require(id.has_value());
const auto catalog = builtin_rule_packages();
require(catalog.has_value());
const std::array selected{std::string{"settlement.core"}};
const auto custom = resolve_rules(*catalog, selected);
require(custom.has_value());
bool rejected = false;
try { ViewerSession session({make_first_colony(2), *id, 1, *custom}, 2); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected);
const auto defaults = default_rules_manifest();
require(defaults.has_value());
rejected = false;
try { ViewerSession session({std::make_unique<World>(1, 16, 16), *id, 1, *defaults}, 2); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected);
}
Test ViewerSessionTests::test_fault_retains_view_and_explicit_load_recovers() {
TempFiles files;
const auto clock = std::make_shared<Void::Time::ManualClock>();
std::atomic<bool> fail{true};
ViewerSessionOptions options;
options.runtime.clock = clock;
options.runtime.observer = [&fail](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeTick && fail.exchange(false)) throw std::runtime_error("injected tick fault");
};
ViewerSession session(2, std::move(options));
const auto before = session.world();
write(files.root / "recover.settlement", bytes(*before));
session.set_ticking(true);
static_cast<void>(session.poll());
flush_owner(session);
require(clock->advance(50ms).has_value());
session.runtime().notify_clock();
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Fault); });
require(session.world() == before);
require(!session.can_submit());
require(!has(session.poll(), ViewerEventKind::Fault));
bool rejected_save = false;
try { session.save(files.root / "fault.settlement"); }
catch (const std::runtime_error&) { rejected_save = true; }
require(rejected_save);
session.set_ticking(false);
static_cast<void>(session.poll());
auto suspended = session.runtime().synchronize();
require(suspended.admission == RuntimeAdmission::Accepted);
require(suspended.completion.wait_for(5s) == std::future_status::ready);
require(suspended.completion.get().outcome == RuntimeOutcome::Faulted);
static_cast<void>(session.poll());
session.load(files.root / "recover.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(session.can_submit());
require(bytes(*session.world()) == bytes(*before));
require(clock->advance(50ms).has_value());
session.runtime().notify_clock();
flush_owner(session);
require(session.world()->tick() == before->tick());
session.set_ticking(true);
static_cast<void>(session.poll());
flush_owner(session);
require(clock->advance(50ms).has_value());
session.runtime().notify_clock();
pump_until(session, [&](const auto&) { return session.world()->tick() > before->tick(); });
}
Test ViewerSessionTests::test_failed_guest_transitions_retain_received_replica() {
ViewerSession session(2);
session.enter_guest();
session.receive_guest(make_first_colony(2));
const auto received = session.world();
session.runtime().shutdown();
bool rejected_join = false;
try { session.enter_guest(); }
catch (const std::runtime_error&) { rejected_join = true; }
require(rejected_join && session.guest() && session.world() == received);
bool rejected_leave = false;
try { session.leave_guest(); }
catch (const std::runtime_error&) { rejected_leave = true; }
require(rejected_leave && session.guest() && session.world() == received);
}
} // namespace