Compare commits

..
Author SHA1 Message Date
faumaray 77781a5f1f Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray aaa0f82527 Verify conditioned peer admission with restored custody states 2026-12-02 23:39:19 +03:00
faumaray 447a1cfd2b Admit legacy guest commands against the exact checked publication 2026-12-02 23:39:19 +03:00
faumaray e5464784f5 Record verified migration of thirteen historical colony states 2026-12-02 23:37:52 +03:00
faumaray 596b491acf Wait for owner fence admission when verifying viewer fault recovery 2026-12-02 23:26:10 +03:00
faumaray c183de1952 Connect legacy admission to the validated custody state 2026-12-02 23:23:51 +03:00
faumaray f34dcc5053 Check live peer admission alongside verified order controls 2026-12-02 23:23:51 +03:00
faumaray 13b4665ed2 Verify order selection through real window controls and modal replacement 2026-12-02 23:23:51 +03:00
faumaray 6cc59b4ef5 Verify peer cutoff while real owner commands and snapshots are pending 2026-12-02 23:19:32 +03:00
faumaray 5c309b2a9f Exercise a protocol 11 host through real order cancellation 2026-12-02 23:14:05 +03:00
faumaray a1c65119a2 Exercise order controls with persisted physical cargo 2026-12-02 23:13:59 +03:00
faumaray 83a57cbe46 Fence legacy peers from an unrepresentable custody publication 2026-12-02 23:13:59 +03:00
faumaray b5f75d3c13 Cancel and resume durable production orders from the Works menu 2026-12-02 23:13:59 +03:00
faumaray 1b57183939 Prepare LAN compatibility checks for durable cargo 2026-12-02 23:01:50 +03:00
faumaray e5d01a4ecd Prepare S04 commands against the durable custody contract 2026-12-02 23:01:50 +03:00
faumaray 5a64a27d17 Record rule selection and quantity transfer checks in the combined game 2026-12-02 22:57:52 +03:00
faumaray 180506d414 Choose colony rules on New and preserve saved rules on load 2026-12-02 22:53:10 +03:00
faumaray 37fb6a897d Integrate actual colony rule selection in the Windows client 2026-12-02 22:53:10 +03:00
25 changed files with 1770 additions and 64 deletions

No files matched your search

+8
View File
@@ -128,6 +128,7 @@ if(BUILD_TESTING)
tests/executor_tests.cpp
tests/identity_tests.cpp
tests/production_identity_tests.cpp
tests/production_commands_tests.cpp
tests/profile_tests.cpp
tests/quantity_transaction_tests.cpp
tests/replay_tests.cpp
@@ -148,4 +149,11 @@ if(BUILD_TESTING)
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)
add_executable(settlement_production_controls_tests
tests/production_controls_tests.cpp tests/test_main.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
target_link_libraries(settlement_production_controls_tests PRIVATE settlement_client settlement_lan
Void::Testing user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
add_test(NAME settlement_production_controls_tests COMMAND settlement_production_controls_tests)
set_tests_properties(settlement_production_controls_tests PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
endif()
+11 -1
View File
@@ -3,6 +3,7 @@
#include "settlement/core/world.hpp"
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
@@ -31,9 +32,16 @@ struct LanCommandResult {
AgentId resident;
};
struct LanSessionOptions {
// Runs on the polling thread after a guest command's snapshot checks and
// before owner admission. May block or throw for diagnostics/tests.
std::function<void()> before_command_admission;
};
class LanSession {
public:
LanSession();
explicit LanSession(LanSessionOptions options);
~LanSession();
LanSession(const LanSession&) = delete;
LanSession& operator=(const LanSession&) = delete;
@@ -53,7 +61,9 @@ public:
// 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.
// Protocol 11 accepts the compiled default rules and a representable 32x32
// active colony. Incompatible state drops the peer, including queued bytes,
// while the listener and authoritative owner remain available.
// 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);
+70 -22
View File
@@ -151,6 +151,16 @@ struct Action {
AgentId resident;
};
void require_legacy_world(const World& world) {
if (!world.scenario_active() || world.width() != first_colony_map_size ||
world.height() != first_colony_map_size) {
throw std::runtime_error("Protocol 11 requires a supported 32x32 colony.");
}
if (!world.legacy_representable()) {
throw UnsupportedLegacyState{};
}
}
} // namespace
struct LanSession::Impl {
@@ -186,8 +196,9 @@ struct LanSession::Impl {
std::optional<Void::Uuid::Uuid> runtime_session;
std::optional<RulesManifest> compatibility_rules;
std::optional<PendingCommand> pending_command;
LanSessionOptions options;
Impl() {
explicit Impl(LanSessionOptions settings) : options(std::move(settings)) {
WSADATA data{};
winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0;
}
@@ -270,8 +281,9 @@ struct LanSession::Impl {
peer.queue(Message::Receipt, std::string_view(bytes));
}
void handle_runtime_host(SimulationRuntime& runtime, const PublishedSnapshot& snapshot,
void handle_runtime_host(SimulationRuntime& runtime, const std::shared_ptr<const PublishedSnapshot>& checked,
Message message, std::string_view payload) {
const auto& snapshot = *checked;
if (!authenticated) {
authenticate(message, payload);
return;
@@ -290,23 +302,34 @@ struct LanSession::Impl {
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 (options.before_command_admission) options.before_command_admission();
auto submitted = runtime.try_submit_if_current({guest_player}, envelope, checked);
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 if (submitted.admission == RuntimeAdmission::Busy ||
submitted.admission == RuntimeAdmission::StaleSnapshot) {
// Contention/capacity does not certify the old publication either.
// Fail closed on incompatible/faulted/replaced state; an ordinary
// compatible revision leaves the legacy sequence available to retry.
const auto current = current_runtime_snapshot(runtime);
reply(CommandStatus::Busy, *current->world);
} else {
throw std::runtime_error("The authoritative owner cannot accept guest commands.");
}
}
void complete_runtime_command() {
void complete_runtime_command(SimulationRuntime& runtime) {
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;
// A ready receipt can predate a load or an incompatible local change.
// Settle its future, but never queue old bytes for the current peer.
const auto current = runtime.view();
validate_runtime(current);
if (current.snapshot->identity.session != pending.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.");
@@ -321,27 +344,38 @@ struct LanSession::Impl {
}
}
void bind_runtime(const RuntimeView& view) {
void validate_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) {
if (view.state != RuntimeState::Running || !view.snapshot || !view.snapshot->world) {
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.");
}
require_legacy_world(*snapshot.world);
}
void bind_runtime(const RuntimeView& view) {
validate_runtime(view);
const auto& snapshot = *view.snapshot;
if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer();
runtime_session = snapshot.identity.session;
}
std::shared_ptr<const PublishedSnapshot> current_runtime_snapshot(SimulationRuntime& runtime) {
const auto view = runtime.view();
validate_runtime(view);
if (!runtime_session || *runtime_session != view.snapshot->identity.session) {
throw std::runtime_error("The authoritative session changed. Reconnect to the host.");
}
return view.snapshot;
}
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) {
@@ -373,6 +407,7 @@ struct LanSession::Impl {
}
void send_snapshot(const World& world, Clock::time_point now) {
require_legacy_world(world);
if (peer.pending()) return;
const auto host_seq = world.next_command_sequence(1);
const auto guest_seq = world.next_command_sequence(guest_player);
@@ -400,8 +435,9 @@ struct LanSession::Impl {
awaiting_receipt = action;
}
template<class Receive, class SendHost>
void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) {
template<class Receive, class SendHost, class Validate>
void poll_network(Receive receive, SendHost send_host, Validate validate, bool accept_allowed = true) {
validate();
if (listener && accept_allowed) accept_guest();
if (!peer.socket) return;
const auto now = Clock::now();
@@ -411,7 +447,12 @@ struct LanSession::Impl {
}
if (connecting) finish_connection();
if (connecting) return;
peer.receive(receive);
peer.receive([&](Message message, std::string_view payload) {
// The owner can publish while one receive drains several frames.
validate();
receive(message, payload);
});
validate();
if (authenticated && guest) {
send_action();
if (!peer.pending() && now - last_ping >= 2s) {
@@ -421,12 +462,15 @@ struct LanSession::Impl {
} else if (authenticated) {
send_host(now);
}
// This includes old snapshots/receipts already waiting in output.
validate();
peer.flush();
if (reject_pending && !peer.pending()) drop_peer();
}
};
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
LanSession::LanSession() : LanSession(LanSessionOptions{}) {}
LanSession::LanSession(LanSessionOptions options) : impl_(std::make_unique<Impl>(std::move(options))) {}
LanSession::~LanSession() = default;
void LanSession::host(std::uint16_t port, bool loopback_only) {
@@ -536,7 +580,9 @@ std::unique_ptr<World> LanSession::poll(World& world) {
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);
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); });
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); }, [&] {
if (connection.listener && !connection.guest) require_legacy_world(world);
});
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
@@ -549,16 +595,18 @@ void LanSession::poll_host(SimulationRuntime& runtime) {
auto& connection = *impl_;
if (!connection.listener || connection.guest) return;
try {
connection.complete_runtime_command();
connection.complete_runtime_command(runtime);
// 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);
const auto snapshot = connection.current_runtime_snapshot(runtime);
connection.handle_runtime_host(runtime, snapshot, message, payload);
}, [&](Clock::time_point now) {
if (!connection.pending_command) connection.send_snapshot(*view.snapshot->world, now);
}, !connection.pending_command);
const auto snapshot = connection.current_runtime_snapshot(runtime);
if (!connection.pending_command) connection.send_snapshot(*snapshot->world, now);
}, [&] { static_cast<void>(connection.current_runtime_snapshot(runtime)); }, !connection.pending_command);
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
@@ -573,7 +621,7 @@ std::unique_ptr<World> LanSession::poll_guest() {
try {
connection.poll_network([&](Message message, std::string_view payload) {
connection.handle_guest(latest, message, payload);
}, [](Clock::time_point) {});
}, [](Clock::time_point) {}, [] {});
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
+25 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include <windows.h>
#include "settlement/core/colony_profile.hpp"
#include <algorithm>
#include <array>
@@ -19,6 +20,7 @@ constexpr int title_coop_id = 1103;
constexpr int title_exit_id = 1104;
constexpr int title_saves_id = 1105;
constexpr int title_open_id = 1106;
constexpr int title_rules_id = 1107;
inline std::filesystem::path saves_directory() {
const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0);
@@ -51,6 +53,14 @@ public:
0, 0, 0, 0, owner, id(title_saves_id), instance, nullptr);
open_ = CreateWindowExW(0, L"BUTTON", L"Загрузить выбранное", WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
0, 0, 0, 0, owner, id(title_open_id), instance, nullptr);
rules_label_ = CreateWindowExW(0, L"STATIC", L"Правила только новой колонии:", WS_CHILD,
0, 0, 0, 0, owner, nullptr, instance, nullptr);
rules_ = CreateWindowExW(0, L"COMBOBOX", L"Правила новой колонии",
WS_CHILD | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST,
0, 0, 0, 0, owner, id(title_rules_id), instance, nullptr);
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Поэтапная кровать: опора и 2 ткани"));
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Простая кровать: 1 доска"));
SendMessageW(rules_, CB_SETCURSEL, 0, 0);
list_background_ = CreateSolidBrush(RGB(44, 63, 53));
font_ = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
@@ -58,6 +68,8 @@ public:
for (const auto button : buttons_) SendMessageW(button, WM_SETFONT, font, FALSE);
SendMessageW(saves_, WM_SETFONT, font, FALSE);
SendMessageW(open_, WM_SETFONT, font, FALSE);
SendMessageW(rules_label_, WM_SETFONT, font, FALSE);
SendMessageW(rules_, WM_SETFONT, font, FALSE);
}
void reload_saves() {
@@ -90,6 +102,8 @@ public:
for (const auto button : buttons_) ShowWindow(button, flags);
ShowWindow(saves_, flags);
ShowWindow(open_, flags);
ShowWindow(rules_label_, flags);
ShowWindow(rules_, flags);
}
void update(bool can_resume, bool offline) const {
@@ -98,6 +112,7 @@ public:
EnableWindow(buttons_[title_browse_id - title_continue_id], offline);
EnableWindow(open_, offline && selected_index() < saves.size());
EnableWindow(saves_, offline);
EnableWindow(rules_, offline);
}
HBRUSH paint_list_background(HWND control, HDC dc) const {
@@ -116,6 +131,10 @@ public:
return saves.empty() ? std::nullopt : std::optional{saves.front().path};
}
[[nodiscard]] ColonyProfile new_colony_profile() const {
return SendMessageW(rules_, CB_GETCURSEL, 0, 0) == 1 ? ColonyProfile::PlankBeds : ColonyProfile::Default;
}
void layout(int width, int height) const {
const RECT panel = bounds(width, height);
for (std::size_t i = 0; i < buttons_.size(); ++i) {
@@ -123,6 +142,8 @@ public:
}
position(saves_, panel.left + 318, panel.top + 146, panel.right - panel.left - 346, 118);
position(open_, panel.left + 318, panel.top + 274, panel.right - panel.left - 346, 33);
position(rules_label_, panel.left + 28, panel.top + 358, panel.right - panel.left - 56, 23);
position(rules_, panel.left + 28, panel.top + 383, panel.right - panel.left - 56, 100);
}
void draw(HDC dc, int width, int height, const std::wstring& notice) const {
@@ -160,7 +181,7 @@ public:
DrawTextW(dc, saves.empty() ? L"Сохранения · список пуст" : L"Сохранения", -1,
&saves_label, DT_SINGLELINE | DT_VCENTER);
if (!notice.empty()) {
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.bottom - 11};
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.top + 355};
DrawTextW(dc, notice.c_str(), -1, &information, DT_WORDBREAK | DT_NOPREFIX);
}
SetTextColor(dc, ink);
@@ -209,7 +230,7 @@ private:
static RECT bounds(int width, int height) {
constexpr int panel_width = 704;
constexpr int panel_height = 365;
constexpr int panel_height = 430;
const int left = (width - panel_width) / 2;
const int top = (height - panel_height) / 2;
return {left, top, left + panel_width, top + panel_height};
@@ -233,6 +254,8 @@ private:
std::array<HWND, 5> buttons_{};
HWND saves_ = nullptr;
HWND open_ = nullptr;
HWND rules_label_ = nullptr;
HWND rules_ = nullptr;
HBRUSH list_background_ = nullptr;
HFONT font_ = nullptr;
std::vector<SaveFile> saves;
+23 -14
View File
@@ -19,25 +19,24 @@ RulesManifest supported_rules() {
return std::move(*manifest);
}
void validate_supported(const WorldCheckpoint& candidate, const RulesManifest& rules) {
void validate_supported(const WorldCheckpoint& candidate) {
const auto valid = validate_colony_checkpoint(candidate);
if (!valid) throw std::runtime_error(valid.error().message);
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);
WorldCheckpoint validated_initial(WorldCheckpoint candidate) {
validate_supported(candidate);
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()};
WorldCheckpoint initial_colony(std::size_t workers, ColonyProfile profile = ColonyProfile::Default) {
auto candidate = make_colony_checkpoint(profile, workers);
if (!candidate) throw std::runtime_error(candidate.error().message);
return std::move(*candidate);
}
RuntimeOptions suspended(RuntimeOptions options) {
@@ -59,7 +58,7 @@ ViewerSession::ViewerSession(std::size_t workers, ViewerSessionOptions 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))),
runtime_(validated_initial(std::move(initial)), suspended(std::move(options.runtime))),
files_(std::move(options.files)) {
if (command_capacity_ == 0) throw std::invalid_argument("The command queue must have capacity.");
}
@@ -74,6 +73,16 @@ bool ViewerSession::can_submit() const {
return !guest_ && !changing_world_ && runtime_.view().state == RuntimeState::Running;
}
bool ViewerSession::can_host_legacy() const {
const auto current = runtime_.view();
return !guest_ && !changing_world_ && current.state == RuntimeState::Running &&
current.snapshot && current.snapshot->rules && *current.snapshot->rules == supported_rules_ &&
current.snapshot->world && current.snapshot->world->scenario_active() &&
current.snapshot->world->width() == first_colony_map_size &&
current.snapshot->world->height() == first_colony_map_size &&
current.snapshot->world->legacy_representable();
}
std::optional<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
if (!can_submit()) return std::nullopt;
for (const auto& intent : intents_) {
@@ -111,7 +120,7 @@ LoadTicket ViewerSession::begin_change() {
}
void ViewerSession::validate_candidate(const WorldCheckpoint& candidate) const {
validate_supported(candidate, supported_rules_);
validate_supported(candidate);
}
void ViewerSession::replace(WorldCheckpoint candidate) {
@@ -120,8 +129,8 @@ void ViewerSession::replace(WorldCheckpoint candidate) {
installing_.emplace(Installing{ticket, std::move(candidate)});
}
void ViewerSession::new_colony() {
replace(initial_colony(workers_));
void ViewerSession::new_colony(ColonyProfile profile) {
replace(initial_colony(workers_, profile));
}
void ViewerSession::load(const std::filesystem::path& path) {
+3 -1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "settlement/core/checkpoint_files.hpp"
#include "settlement/core/colony_profile.hpp"
#include <deque>
#include <filesystem>
@@ -39,13 +40,14 @@ public:
[[nodiscard]] bool guest() const noexcept { return guest_; }
[[nodiscard]] bool changing_world() const noexcept { return changing_world_; }
[[nodiscard]] bool can_submit() const;
[[nodiscard]] bool can_host_legacy() 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 new_colony(ColonyProfile profile = ColonyProfile::Default);
void load(const std::filesystem::path& path);
void save(const std::filesystem::path& path);
void enter_guest();
+180 -6
View File
@@ -72,6 +72,7 @@ constexpr int furnished_room_tool_id = 1045;
constexpr int house_list_back_id = 1046;
constexpr int carpenter_menu_id = 1047;
constexpr int craft_door_id = 1048;
constexpr int manage_orders_id = 1049;
constexpr int first_furniture_craft_id = 1143;
constexpr int first_work_choice_id = 1050;
constexpr int resident_list_id = 1060;
@@ -140,7 +141,7 @@ 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 };
enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room, ManageOrders };
PlacementMode placement_mode = PlacementMode::None;
enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, Houses, Carpenter, None };
WorkPanel work_panel = WorkPanel::None;
@@ -204,6 +205,11 @@ constexpr const wchar_t* house_contents[] = {
L"Каменная кровать и стойка с инструментами",
L"Деревянная кровать и ткацкий станок",
};
constexpr const wchar_t* simple_house_contents[] = {
L"Кровать: 1 доска; аптечный шкаф",
L"Кровать: 1 доска; стойка с инструментами",
L"Кровать: 1 доска; ткацкий станок",
};
std::array<HICON, 3> house_artwork{};
struct DockSection {
WorkPanel panel;
@@ -827,6 +833,15 @@ bool can_give_orders() {
return world && session && (lan->is_guest() ? lan->state() == LanState::GuestConnected : session->can_submit());
}
bool can_manage_orders() {
return !showing_title && can_give_orders() && !lan->is_guest() && !session->guest() &&
!session->changing_world();
}
bool manageable_order(const settlement::ProductionOrder& order) {
return order.suspended || order.state != settlement::JobState::Completed;
}
void update_roster_details() {
const auto* resident = selected_agent();
const auto role = resident ? profession_name(resident->profession) : L"";
@@ -1054,7 +1069,7 @@ void show_title_screen(HWND window, bool visible) {
}
void reset_world(HWND window) {
session->new_colony();
session->new_colony(title_screen.new_colony_profile());
host_after_replacement = false;
clear_blueprints();
placement_message = L"Создаём поселение…";
@@ -1254,7 +1269,13 @@ void handle_lan_menu(HWND window, int command) {
if (!showing_title) return;
try {
if (command == lan_host_id && lan->state() == LanState::Offline) {
if (!has_session || !world || !world->scenario_active()) {
// Modal menus pump loads, so inspect the authoritative publication
// here, immediately before any listener or replacement is started.
if (!session->can_host_legacy()) {
throw std::runtime_error("LAN requires a ready colony with the default rules. Wait for loading to finish.");
}
const auto current = session->runtime().latest();
if (!has_session || !current->world->scenario_active()) {
session->new_colony();
host_after_replacement = true;
clear_blueprints();
@@ -1411,6 +1432,9 @@ bool valid_edit_cell(settlement::GridPosition cell) {
case PlacementMode::Move:
return move_source ? world->can_place_storage(cell) : world->object_status(cell, true) == CommandStatus::Accepted;
case PlacementMode::Demolish: return world->object_status(cell, false) == CommandStatus::Accepted;
case PlacementMode::ManageOrders:
return can_manage_orders() && std::any_of(world->production_orders().begin(), world->production_orders().end(),
[cell](const auto& order) { return order.position == cell && manageable_order(order); });
case PlacementMode::Building:
return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell);
case PlacementMode::Room:
@@ -1665,6 +1689,11 @@ void complete_command(std::uint64_t id, const settlement::SessionPayload& payloa
}
if (accepted) {
placement_message = L"Команда выполнена.";
if (std::holds_alternative<settlement::CancelProductionPayload>(payload)) {
placement_message = L"Заказ отменён. Установленные части сохранены; груз вернут жители.";
} else if (std::holds_alternative<settlement::ResumeProductionPayload>(payload)) {
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();
@@ -1676,6 +1705,13 @@ void complete_command(std::uint64_t id, const settlement::SessionPayload& payloa
}
}
} else {
if (std::holds_alternative<settlement::CancelProductionPayload>(payload) ||
std::holds_alternative<settlement::ResumeProductionPayload>(payload)) {
placement_message = status == settlement::CommandStatus::Busy
? L"Заказ пока нельзя изменить. Дождитесь возврата материалов или повторите позже."
: L"Заказ отклонён: работа уже завершена, удалена или изменилась.";
return;
}
placement_message = status == settlement::CommandStatus::Busy
? L"Объект занят. Дождитесь окончания работы или сна."
: L"Команда отклонена. Проверьте клетку и доступ к ней. Чертёж сохранён.";
@@ -1715,8 +1751,12 @@ void pump_session(HWND window) {
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"Сетевая колония открыта. Адрес и код доступны в меню кооператива.";
if (lan->state() == LanState::Offline && session->can_host_legacy()) {
lan->host();
placement_message = L"Сетевая колония открыта. Адрес и код доступны в меню кооператива.";
} else {
placement_message = L"Кооператив требует готовую колонию со стандартными правилами.";
}
} else {
show_title_screen(window, false);
}
@@ -1764,8 +1804,115 @@ void pump_session(HWND window) {
invalidate_scene(window);
}
const wchar_t* production_name(settlement::RecipeId recipe) {
using settlement::RecipeId;
switch (recipe) {
case RecipeId::SawPlank: return L"Распилить доску";
case RecipeId::CutStoneBlock: return L"Вытесать каменный блок";
case RecipeId::BuildCabin: return L"Построить домик";
case RecipeId::BuildBed: return L"Спальное место";
case RecipeId::WeaveCloth: return L"Ткать ткань";
case RecipeId::BuildFloor: return L"Пол";
case RecipeId::BuildWall: return L"Стена";
case RecipeId::BuildDoorAlongX:
case RecipeId::BuildDoorAlongY: return L"Построить дверь";
case RecipeId::BuildMedicineCabinet: return L"Построить аптечный шкаф";
case RecipeId::BuildMiningRack: return L"Построить стойку шахтёра";
case RecipeId::BuildLoom: return L"Построить ткацкий станок";
case RecipeId::InstallDoorAlongX:
case RecipeId::InstallDoorAlongY: return L"Установить дверь";
case RecipeId::CraftWoodenDoor: return L"Изготовить дверь";
case RecipeId::InstallMedicineCabinet: return L"Установить аптечный шкаф";
case RecipeId::InstallMiningRack: return L"Установить стойку шахтёра";
case RecipeId::InstallLoom: return L"Установить ткацкий станок";
case RecipeId::CraftMedicineCabinet: return L"Изготовить аптечный шкаф";
case RecipeId::CraftMiningRack: return L"Изготовить стойку шахтёра";
case RecipeId::CraftLoom: return L"Изготовить ткацкий станок";
}
return L"Производственный заказ";
}
void manage_orders_at_cell(HWND window, settlement::GridPosition cell) {
if (!can_manage_orders()) return;
// Popup menus pump nested messages. Keep every displayed order alive and
// fence both replacement admission and completed world/session replacement.
const auto opening = session->runtime().latest();
const auto generation = session->generation();
const auto* opening_session = session.get();
const auto network_generation = lan_generation;
const auto* connection = lan.get();
const auto current_context = [&] {
return can_manage_orders() && session.get() == opening_session && session->generation() == generation &&
session->runtime().latest()->identity == opening->identity && network_generation == lan_generation &&
connection == lan.get() && placement_mode == PlacementMode::ManageOrders;
};
constexpr std::size_t page_size = 16;
constexpr UINT previous_page = 100;
constexpr UINT next_page = 101;
std::size_t offset = 0;
POINT cursor{};
GetCursorPos(&cursor);
for (;;) {
std::array<const settlement::ProductionOrder*, page_size> choices{};
std::size_t count = 0, skipped = 0;
bool more = false;
for (const auto& order : opening->world->production_orders()) {
if (order.position != cell || !manageable_order(order)) continue;
if (skipped++ < offset) continue;
if (count == page_size) { more = true; break; }
choices[count++] = &order;
}
if (count == 0) {
placement_message = L"На этой клетке нет незавершённых или приостановленных заказов.";
return;
}
const auto menu = CreatePopupMenu();
if (!menu) return;
for (std::size_t index = 0; index < count; ++index) {
const auto& order = *choices[index];
const auto title = std::wstring(order.suspended ? L"Возобновить: " : L"Отменить: ") +
production_name(order.recipe) + L" №" + std::to_wstring(order.id) + L" [" +
std::to_wstring(cell.x + 1) + L", " + std::to_wstring(cell.y + 1) + L"]";
AppendMenuW(menu, MF_STRING, index + 1, title.c_str());
}
if (offset != 0 || more) AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
if (offset != 0) AppendMenuW(menu, MF_STRING, previous_page, L"← Предыдущие заказы");
if (more) AppendMenuW(menu, MF_STRING, next_page, L"Следующие заказы →");
const auto selected = static_cast<UINT>(TrackPopupMenu(menu, TPM_RETURNCMD |
TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, window, nullptr));
DestroyMenu(menu);
if (!current_context()) {
placement_message = L"Поселение или режим изменились. Выберите заказ заново.";
return;
}
if (selected == previous_page) { offset -= page_size; continue; }
if (selected == next_page) { offset += page_size; continue; }
if (selected == 0 || selected > count) return;
const auto& chosen = *choices[selected - 1];
const auto current = session->runtime().latest();
const auto* order = current->world->find_production(chosen.id);
if (!order || order->position != chosen.position || order->recipe != chosen.recipe ||
order->suspended != chosen.suspended || !manageable_order(*order)) {
placement_message = L"Заказ изменился. Выберите его заново.";
return;
}
const settlement::SessionPayload payload = chosen.suspended
? settlement::SessionPayload{settlement::ResumeProductionPayload{chosen.id}}
: settlement::SessionPayload{settlement::CancelProductionPayload{chosen.id}};
placement_message = enqueue_command(payload) ? L"Изменение заказа ожидает подтверждения…"
: L"Очередь занята. Попробуйте ещё раз.";
return;
}
}
void edit_at_cell(HWND window, settlement::GridPosition cell) {
if (!can_give_orders()) return;
if (placement_mode == PlacementMode::ManageOrders) {
manage_orders_at_cell(window, cell);
update_status();
invalidate_scene(window);
return;
}
const auto held_world = world;
const auto generation = session->generation();
const auto installed_session = session->runtime().latest()->identity.session;
@@ -1835,6 +1982,7 @@ HMENU create_work_menu() {
role_choices[static_cast<std::size_t>(id - farmer_menu_id + 1)].title);
}
AppendMenuW(menu, MF_STRING, carpenter_menu_id, L"Плотник");
if (can_manage_orders()) AppendMenuW(menu, MF_STRING, manage_orders_id, L"Управление заказами…");
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC");
return menu;
@@ -2054,6 +2202,24 @@ 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->state == settlement::AgentState::Returning) {
text += L" Возвращает материалы";
if (resident->execution) {
switch (resident->execution->blocked) {
case settlement::CustodyStatus::NoDestination:
text += L": нет доступного склада с местом"; break;
case settlement::CustodyStatus::Capacity:
text += L": на складе недостаточно места"; break;
case settlement::CustodyStatus::Busy:
text += L": ожидает освобождения склада"; break;
case settlement::CustodyStatus::Exhausted:
case settlement::CustodyStatus::Overflow:
text += L": достигнут предел учёта запасов"; break;
case settlement::CustodyStatus::Accepted: break;
default: text += L": ожидает возможности сдать груз"; break;
}
}
}
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" Работает за верстаком" :
@@ -2177,6 +2343,8 @@ void draw_world(HDC dc, int width, int height) {
L"Выберите кровать, склад, станок или посаженный участок.";
} else if (placement_mode == PlacementMode::Demolish) {
hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена.";
} else if (placement_mode == PlacementMode::ManageOrders) {
hint = L"Щёлкните по площадке или станку. Выберите заказ, чтобы отменить или возобновить работу.";
} else if (placement_mode == PlacementMode::Room) {
if (room_draft_move) {
hint = L"Щёлкните по новой площадке. R поворачивает дом, правый щелчок отменяет перенос.";
@@ -2201,7 +2369,8 @@ void draw_world(HDC dc, int width, int height) {
DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
auto details = has_blueprint() ? blueprint_details() :
selected_room_template != settlement::RoomTemplate::Empty
? std::wstring(house_contents[static_cast<std::size_t>(selected_room_template) - 1])
? std::wstring((world->staged_beds() ? house_contents : simple_house_contents)
[static_cast<std::size_t>(selected_room_template) - 1])
: resident_details();
if (work_panel == WorkPanel::Carpenter) {
const auto orders = std::count_if(world->production_orders().begin(), world->production_orders().end(),
@@ -2606,6 +2775,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
if (world) show_resident_roster(window);
return 0;
}
if (LOWORD(wparam) == manage_orders_id && HIWORD(wparam) == BN_CLICKED) {
if (can_manage_orders()) set_placement_mode(window, PlacementMode::ManageOrders);
SetFocus(window);
return 0;
}
if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == build_blueprint_id) {
submit_blueprint(window);
SetFocus(window);
+2
View File
@@ -93,3 +93,5 @@ wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag
В `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)
В `37fb6a8` объединены проверяемая передача всего груза одной остановки и выбор правил на титульном экране. Игрок может создать поселение с поэтапной сборкой кровати либо с рецептом из одной доски. При открытии сохранения восстанавливается его собственный набор правил. Испытание настоящего окна проверило оба выбора мышью и клавиатурой, файл и продолжение из нового процесса. В общей сборке под Wine прошли 136 тестов ядра, 9 LAN и 14 клиента. [Загрузка и инвентарь S06](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11) · [Клиент S18](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/13) · [Совместная проверка](tasks/M01-V12.md)
+4
View File
@@ -48,3 +48,7 @@ User authorizes roadmap/push/MRs/upstream issues; root owns all external actions
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.
The integrated S06 check passed. S18-02 now has finished production changes against `e6a01be` in the s18 checkout. Inspect both real title/handler sources in the temporary evidence directory and `client-profile-*` logs, including a real two-process title choice/save/open, normal GUI regressions, held-load Host refusal and 14 viewer cases. Validate the actual six edited files, costs and initial/async gate along with the compiled profile and LAN boundaries.
The S18 component passed and is committed as `180506d`. Integrated `37fb6a8` has parents `f6493e2` and `180506d`. Inspect the combined selector/quantity source against those parents, CMake and `m01-selection-{build,ctest,ui}.log`. The real application smoke used the executable in the integrated build directory.
+50
View File
@@ -0,0 +1,50 @@
# Cancel and resume production work by durable order ID
Task ID: S04-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated s04 e5d01a4 contains 5a64a27 user-facing viewer + private S06 header 4f42488. World::cancel_production/resume_production(ProductionId)->CommandStatus, AgentState::Returning, Agent.execution and ProductionOrder.suspended are frozen declarations; peer S06 implements actual effects. Legacy LAN11 supports only PlayerCommand and local LegacyCabinPayload has existing runtime path. Existing Работы menu is a real entry and current UI correlates exact SessionPayload after receipt.
## 2. Objective and deliverables
Connect modern cancellation and resumption to the authenticated command dispatcher and an actual localized host/offline Win32 control aimed at durable ProductionId. Make receipt/status/return reason visible and verify retry, rejection, stale selection and real returned cargo with S06.
## 3. Scope and non-goals
Only S04 modern session variants and minimal Win32 normal orders action for present job lifecycle. Keep historical PlayerCommand, CommandKind, LAN11, ordinary demolition/move and S19 profiles unchanged. S06 owns World and all ledger/cargo transitions; S15 owns codecs. S17 owns presentation in a sibling branch.
## 4. Files to inspect
Read command_dispatcher.hpp/.cpp, simulation_runtime.hpp and exact receipt semantics, app/viewer_win32.cpp enqueue_command/complete_command/edit_at_cell/Работы menu & agent status, app/viewer_session and existing modal epoch guards, tests/session/runtime and viewer. Inspect frozen custody.hpp/world.hpp and docs/plan/custody.md. Study exposed work order/actual stages and S04 docs.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/command_dispatcher.hpp; engine/src/command_dispatcher.cpp; app/viewer_win32.cpp narrow order-action menu/handler and returned cargo display only; tests/session_tests.cpp and NEW tests/production_commands_tests.cpp if needed; NEW tests/production_controls_tests.cpp for the real Win32 controls; CMakeLists.txt only owned test entries; docs/plan/systems/S04.md
Isolated s04 only; other workers have independent worktrees. Never revert changes, edit S06/S16/S17 or switch shared Serena. No Git/remote ops/children.
## 6. Implementation or investigation approach
Add distinct typed CancelProductionPayload{ProductionId production} and ResumeProductionPayload; equality/payload conflict checks go through existing SessionPayload variant/ledger. Admit/validate trusted client/world/session/city/request before World methods and pass domain status through existing DispatchReceipt; successful mutations advance revision once, refused result retained. No legacy sequence side effect for these new modern payloads or untyped std::get fallthrough. Existing cabin branch remains exact.
## 7. Interfaces and data contracts
User must be able to cancel/resume through normal game UI. Prefer a single order-management action in existing Работы menu with a map target using current user-visible names/coordinates and explicit Отменить/Возобновить choices; if multiple eligible orders share a cell, bind each displayed choice to its actual durable ProductionId. Don't use vector index as command. Host/offline only: hide/disable for legacy guest before enqueue. Pin opening snapshot, recheck world+session incarnation and presentation generation after any modal interaction and validate target still appropriate; never send an old selection into a loaded different colony. Bound menu/list size while retaining access to all choices. Use existing asynchronous queue and return receipt so UI only reports completion after commit. Returning resident with no eligible space shows why it waits; avoid reporting unearned cancel/return, preserve existing move/demolish behaviors.
## 8. Dependencies and integration
Depends on S06 core, not yet linked initially; root provides actual local commits before final build. S17 in another branch may touch drawing; keep changes narrow and alert parent about status text fields so final packet integration preserves them. Separate S16 tests for incompatible legacy guests, no new wire variant.
## 9. Edge cases security and performance
Resource/capacity refusal returns repeatable domain status with stable world and actual request identities. Prior receipt still valid after target removed. Wrong-world/city/session and same request differing ProductionId/variant are fenced/Conflict. Early command/UI must not synthesize arbitrary orders or try to resolve IDs from stale sessions.
## 10. Acceptance criteria
1. Tests use actual dispatcher/runtime with live order/cargo; same request accepted/refused twice, different payload same key Conflict, wrong world/session/city rejected, accepted cancellation/return and resume retained site progress once. 2. UI test actual action/receipt, bound durable ID and cancel on stale dialog without enqueuing new-world action, legacy guest cannot submit. 3. Default legacy command numbering/cabin/old raw & LAN tests unchanged. 4. Native Windows x64 cross-build + loops, full integrated CTest when dependencies provided.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s04-cancel-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. Compile independent translation units/tests as feasible before S06 implementation lands. Use actual focused session/order tests and CTest -V, isolated Windows/Wine UI smoke under /tmp, logs s04-cancel-*. git diff --check. Native hardware not assumed.
## 12. Constraints and stop conditions
Never implement duplicate inventory mutation/ID logic or mock final acceptance. If cyclic API, incorrect capacity/epoch or unavailable real core, report exact required seam and continue independent adapter/tests. Two failed same-cause attempts escalate. No Git/remote/children.
## 13. Authorization and decisions
User authorizes all milestones. F8/root approve explicit modern cancel/resume of retained partially built bed or existing loom, stable identities and old Busy constraints. Root integrates/publishes once end-to-end safe.
## 14. Return format
Return S04-02 READY or PARTIAL, actual normal command/UI entry, test outcomes/real dependency status, logs and native limitations.
The Win32 executable may include the viewer implementation in its test translation unit using its real window and menu handlers. Drive modal selection via an actual window timer, including a world replacement while a choice is open. Cover the correct durable selection, receipt, stale selection and guest action fence. Reuse existing test/build conventions and keep this target independent of the S17 frame smoke. Register it with CTest and report actual Wine results after S06/S15 link.
+48
View File
@@ -0,0 +1,48 @@
# Gate legacy guests on exact representability of authoritative cargo
Task ID: S16-03
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated s16 1b57183, local base modern selector 5a64a27 + S06 header 4f42488. World::legacy_representable() const noexcept and typed UnsupportedLegacyState declared. S06 and S15 owners implement actual new states and raw13 preflight. Existing session supports LAN11 32×32/default rules and historical old binary interop. A common send path sends pending output before a new snapshot, so handling only encode exceptions is too late.
## 2. Objective and deliverables
Reject admission and disconnect incompatible existing LAN11 guests early when the actual authoritative snapshot cannot project into the old format, while preserving the host and all already-admitted receipts. Keep both direct/deferred UI Host refusal before creating a listener.
## 3. Scope and non-goals
LAN11 adapter, host-readiness predicate used by Win32, and focused compatibility tests. No protocol change, modern authoritative-rules restriction, dispatcher command variant or alteration of actual inventory ownership. Normal valid old/new binary interop remains.
## 4. Files to inspect
Read app/lan_session_win32.cpp all poll_network, handshake/receive/send_snapshot/pending output/complete_runtime_command paths incl older standalone poll(World&), app/lan_session.hpp, viewer_session.cpp::can_host_legacy and member/header/actual normal callers from S18; engine/core/world.hpp public frozen readiness + exception, S04/S06 plans and M01-F8. Read tests/lan_tests.cpp and viewer_session_tests.cpp, historic two-binary interop harness in /tmp.
## 5. Write ownership and coordination
Write scope: app/lan_session_win32.cpp; app/lan_session.hpp only if meaningful API docs or narrow shared predicate; app/viewer_session.cpp only can_host_legacy and local support predicate; tests/lan_tests.cpp and tests/viewer_session_tests.cpp narrowly for legacy compatibility; docs/plan/systems/S16.md
No S06 World/codec/cancel implementation, dispatcher edits or S04/S17 viewer_win32 file changes. Others own these in siblings; do not revert/switch Serena or write outside worktree except your temp verification source. Root owns Git/remote.
## 6. Implementation or investigation approach
Gate exact supported rules/active dimensions and actual World::legacy_representable result before accepting/authenticating, receiving/dispatching guest commands, sending/continuing queued legacy output. Do not send partially legacy-encoded bytes. A newly unrepresentable state disconnects old peer and safely clears outgoing/peer-specific pending/request metadata; preserve settlement of already-admitted owner work and compatibility of later reconnection. Incoming cmd must check current published view/epoch before admission; allow valid previously accepted owner work to settle after disconnect. Old poll(World&) normal host path must guard projection and keep owning standalone world unchanged on refusal.
## 7. Interfaces and data contracts
Use typed compatibility failures/explicit reason or existing guarded notice. Healthy hosts continue stepping, saving modern checkpoint and receiving modern commands; ViewerSession::can_host_legacy must check published exact default and freeze during replacement, direct/deferred actual callers gate on that. Do not silently downgrade, fabricate a matching old state, or disconnect a guest for representable ordinary historical default/simple worlds. Preserve user-selected local colony and port/peer while refusing a newly requested Host.
## 8. Dependencies and integration
Depends on S06-03 implementation+S15-04 current15 for actual integrated tests. Local branch currently contains header only, parent will merge coherent core for real normal entry and old binary. Design fixture with a real canceled mixed-cargo/no-storage or withheld suspended site and positive representable counterpart; coordinate with S06/S04 if needed. No mocks for final acceptance.
## 9. Edge cases security and performance
Beware connected guest with old snapshot bytes pending, re-auth/wrong connection incarnation, UDP not involved, S16 ledger boundaries vs published current epoch. Keep game thread and UI polling nonblocking. Avoid full serialization solely to test readiness on each poll when dedicated bounded pure check exists; use immutable snapshot identity/revision when caches needed.
## 10. Acceptance criteria
1. At least one real unrepresentable default colony (mixed canceled carrier/single unlinked plank/suspended residual as applicable) refuses listener/handshake and drops already-connected guest before a further wire command mutates it. 2. Already-admitted command still settles. 3. Host remains healthy, new modern save/reload works and local progress continues. 4. Normal old protocol fixture and old binary both directions pass, valid default simple historical colony still allowed; optional rules still denied. 5. All CTest/GUI at final integrate.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s16-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. Compile independent translation units as feasible now; verify actual core when root supplies it. CTest -V/targeted wire/owner, external interop harness /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-interop.{cpp,py}; keep s16-custody-* logs. Scoped tests use localhost only and temp saves.
## 12. Constraints and stop conditions
Never weaken wire11 bounds or gate whole modern owner/dispatcher. Do not add general authentication flow or expose an external service. If checked interface missing/incorrect, inform root and work independently pending real dependencies. No Git/remote writes/children. Two same-cause failed repairs escalate.
## 13. Authorization and decisions
User authorizes full project. F8/root approve truthful unsupported legacy projection and disconnect preserving host; original normal interop retained. Root owns public actions.
## 14. Return format
Return S16-03 progress/READY or PARTIAL, actual admission/queued frame/receipt behavior, tests/logs and native limits. Identify exact dependency commit needed for final integration.
+47
View File
@@ -0,0 +1,47 @@
# Linearize legacy guest command admission with authoritative publication
Task ID: S16-04
Role: sol_implementer
Status: READY
## 1. Context and baseline
Independent review M01-V15 found a real race in S16-03 at c183de1 in s16 worktree. app/lan_session_win32.cpp current_runtime_snapshot takes a healthy compatible immutable snapshot, then handle_runtime_host later calls unconditional SimulationRuntime::try_submit. Runtime::enqueue under its mutex only checks closing/capacity; a host cancellation can publish an unrepresentable world in the same epoch between those operations. Work already queued before cutoff must still settle. Earlier old/current compatibility and partial buffered data tests unrelated to this gap passed.
## 2. Objective and deliverables
Enforce atomic conditional admission against the exact compatible publication already inspected by protocol11; verify a deterministically forced check→concurrent publish→enqueue race using the real owner/host/socket. Keep old clients functional on compatible newer snapshots, and no secret fallback to the legacy path.
## 3. Scope and non-goals
Limited change to S16 adapter, smallest general runtime admission seam and targeted regression/doc. No protocol layout change, global gameplay trust/authority changes, or duplicate compatibility logic under network ownership.
## 4. Files to inspect
Inspect engine/include/settlement/core/simulation_runtime.hpp, engine/src/simulation_runtime.cpp enqueue/publish/fault/try_submit, app/lan_session_win32.cpp + lan_session.hpp poll/handle_runtime_host/reply/drop, tests/lan_tests.cpp plus tests/runtime_tests.cpp existing gates, docs/plan/systems/{S01,S16}.md. Read M01-V15 and S16-03 and actual earlier logs in temp.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/simulation_runtime.hpp; engine/src/simulation_runtime.cpp; app/lan_session_win32.cpp; app/lan_session.hpp if essential for a small test seam; tests/lan_tests.cpp; docs/plan/systems/S16.md. S21 owns runtime_tests.cpp in a sibling; keep your specific regression in lan_tests. No shared changes/remote, Git writes, children or shared Serena switching.
## 6. Implementation or investigation approach
Add narrowly named conditional admission to normal runtime queue (suggest try_submit_if_current, explicit checked snapshot). Under exactly the mutex serializing published/state and queue insertion, before effects, require RuntimeState::Running and match non-null expected retained shared publication (identity pointer or version+incarnation with equal semantics). Leave existing unconditional local API unchanged. Ensure lock contention/capacity Busy is distinct in outcome/handling from a changed publication, e.g. explicit mismatch result or documented guard outcome; no read outside mutex can certify admission. Do not recompute/copy the whole World in the lock. Never revalidate/revoke work already admitted before publication.
## 7. Interfaces and data contracts
LAN adapter passes checked published snapshot capability with outgoing command. On mismatch re-evaluate latest state: incompatible/faulted/session replacement clears peer/buffers and never enqueues stale envelope; healthy same-session changed revision must retain old protocol sequence/ack, e.g. legitimate Busy and old-client retry or bounded retry with current snapshot, not disconnect all guests every tick. Invalid/fault/capacity must not emit receipt for an unadmitted command as Accepted. Distinguish handshakes/queue flush; prior external bytes already sent cannot be recalled.
## 8. Dependencies and integration
Real S04 cancel from host and custody S06/S15 already in s16. Root also integrating S21/S18 tests. Use test hook at narrow point after checking snapshot and before runtime enqueue, or equivalent genuine scheduling barrier. Avoid new permanent per-frame overhead unrelated to this path. If testing hook is needed, prefer existing configured seams or narrow optional sterile observer rather than global test-only code in normal library that changes semantics.
## 9. Edge cases security and performance
Protect repeated remote sessions/idempotency and stale same-epoch publication across canonical cancellation. Guards must not coerce nullptr into unconditional admission, ABA impossible with retained shared_ptr and immutable identity. Publication faults and shutdown must obey existing semantics. Do not busy-loop when current world is advancing. Old/queued command with exact accepted availability must complete on healthy owner even if the state changes afterwards.
## 10. Acceptance criteria
1. Deterministic two-thread/real-loopback test holds remote operation after capturing representable S, publishes same-epoch unrepresentable S+1 via real typed cancellation, releases, proves zero new guest ledger entry/sequence/stock/command effect and correct peer drop (works on old code as counterexample). 2. Positive same-session compatible revision interleaving maintains coherent old-client progress/sequence and earlier admitted request still settles. 3. Existing 13 LAN and target viewer, actual compiled original/new host+guest both ways pass. 4. No change to PC11 bytes/ordinary local auth or installed snapshots.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s16-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. Run new focused LAN tests and full CTest -V, old/new interop harnesses from your S16-03 context, use logs s16-published-admission-*.log and git diff --check. Native Windows unavailable. Before fixed build, show exact reproducer outcome if feasible.
## 12. Constraints and stop conditions
If inability to atomically compare protected publication and enqueue, report actual contract and fail closed within scope. After two failed same-cause attempts root escalates; no other agents, external writes, retrying commands outside the appropriate session or full scans under runtime lock.
## 13. Authorization and decisions
User requested end-to-end software and protocol compatibility. Fresh V15 correction belongs to S16; bounded change to existing owner seam is authorized. Root exclusively owns commits/remote operations and post-fix re-review.
## 14. Return format
Return S16-04 READY or PARTIAL, frozen paths, observed pre-fix failure/post-fix controlled interleaving and old/new compatibility, actual logs and residual limits.
+48
View File
@@ -0,0 +1,48 @@
# Select supported rules when starting a colony in the Win32 client
Task ID: S18-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated s18 worktree after root fast-forwards to db0a872 or a descendant containing the reviewed b7f18c0 client and 2759563 compiled profiles. S18-01 uses a long-lived runtime, exact default-only constructor/load, healthy views, transactional guest admission and fresh session identity. S19 core factory and validator already run the two real cost chains. M01-F6/F7 require validating initial, asynchronous and legacy hosts.
## 2. Objective and deliverables
Make the actual Russian title screen offer staged beds (default) or one-plank beds for a new colony, apply the selected compiled rules to the new world, reload either supported profile exactly, and restrict LAN protocol 11 to default rules before any network side effect.
## 3. Scope and non-goals
Only S18 profile selection/validation and accurate colony presentation. Preserve general S19 resolver, format1–14, LAN bridge/wire, legacy guest leave and unrelated keyboard/settings. Initial factory default stays staged, UI title selection is local to this process and only affects New.
## 4. Files to inspect
Read root/s18 actual app/title_screen_win32.hpp, viewer_win32.cpp, viewer_session.hpp/.cpp, tests/viewer_session_tests.cpp, colony_profile.hpp/.cpp (colony_rules, compile_colony_rules, make_colony_checkpoint, validate_colony_checkpoint), S19 profile_tests and S18/S19 docs. Inspect LAN direct and deferred host event paths BEFORE making changes, current supported_rules_ also supplies legacy guest import. Actual smoke sources client_{ui,handlers,regression}_smoke.cpp in temp.
## 5. Write ownership and coordination
Write scope: app/title_screen_win32.hpp; app/viewer_win32.cpp (title/new/host/bed labels only); app/viewer_session.hpp and .cpp (factory/validator/host readiness); tests/viewer_session_tests.cpp; docs/plan/systems/S18.md
Isolated s18 only. Other workers edit separate branches. Do not revert others' changes or modify CMake/other components. Root owns all Git/remote operations. Distinct test build directory.
## 6. Implementation or investigation approach
Use one accessible native control for a clearly labeled New-only choice, ensure keyboard (focus/Tab/arrows/Space/Enter as appropriate) and mouse operate at supported dimensions. Preserve title layout/order and new/continue/save list. Factory creates a new UUID and selected actual world; Continue/Open ignore current selector. Run candidate validation for both supplied initial and replacement/latest prepared loads before owner install and preserve current 32×32 restriction. Preserve default simple/inactive historical modes. Display correct cost including Miner house in simple profile; hide staged foundation material controls when simple.
## 7. Interfaces and data contracts
Host immediate path must reject if changing_world or the current authoritative publication does not have exact default rules. Recheck after returning from modal menu before opening a listener; deferred path revalidate the newly installed publication immediately before network start. Error preserves active world/local file operation/peer. Existing default simple legacy world can host if other established gates pass. Legacy guest import still uses exact frozen default. Do not expose optional rules via old wire. Keep S18-01 fresh ticket/epoch gating and bounded queues.
## 8. Dependencies and integration
Root owns fast-forward to integrated base before starting. Backend S19 and first viewer are independently accepted. New choice has real compiled behavior. Future S17 render-timer changes are separately owned; avoid edits to WM_TIMER or D3D unless a real unexpected dependency is reported.
## 9. Edge cases security and performance
Reject unknown/forged/extra manifests, optional+staged, unusable dimensions/identity before any effect. Restore valid default raw simple, active optional simple and authentic old saves. A superseded valid load followed by failing newest must keep current world. Titles with small width/DPI should retain usable label/control. No external files in real saves, never open real network beyond loopback.
## 10. Acceptance criteria
1. Real title New creates both variants (including exact selected manifest in saved checkpoint and visible costs). 2. Continue/Open preserve saved choice despite different selection, exact default old inactive/simple accepted. 3. Bad initial/load gate leaves session/world untouched. 4. Immediate/deferred legacy Host refusal before listener or peer change, including held optional load over old default. 5. Existing ten viewer tests, integration CTest and prior three-process/handler regressions still pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-profiles-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 CTest -V, viewer suite selectors as actually registered and git diff --check. Run an actual GUI smoke with isolated LOCALAPPDATA, exercise both choices with mouse/key, New, save/open with opposite selector, confirm actual stored manifest/bed mode. Extend /tmp smoke only as appropriate and record client-profile-* source/logs. Named current published checks are baselines.
## 12. Constraints and stop conditions
Do not change staged vs simple game costs or default digest, add fake settings, change wire or unrelated app controls. No lowering exact-default admission. If title input cannot be exercised with available Windows/Wine tooling, describe specific gap and continue core meaningful checks. No children/commits/push; two failed same-cause fixes escalate.
## 13. Authorization and decisions
User asked for complete milestones/system branches and actual compatible module selection. M01-F7 recorded corrective host gate and accurate simple Miner description. Root owns external side effects. Existing upstream #4 tracks generic resolution.
## 14. Return format
Return S18-02 READY/PARTIAL, actual chosen title control + normal flow, exception/load/LAN boundaries, paths, commands/logs and any native UI caveats.
+14
View File
@@ -20,6 +20,20 @@
Проверки: [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.
## Реализованный срез S04-02: отмена и возобновление
Современная сессия принимает отдельные `CancelProductionPayload{ProductionId}` и `ResumeProductionPayload{ProductionId}`. Диспетчер проверяет доверенного игрока, мир, инкарнацию, город и номер запроса, затем передаёт действие в `World::cancel_production` / `resume_production`. Их физические эффекты принадлежат [S06](S06.md): адаптер команд не перемещает имущество самостоятельно. Современные действия доступны хозяину; гостю возвращается сохраняемый `Unauthorized`. Они не расширяют `CommandKind`, LAN 11 и прежнюю нумерацию `PlayerCommand`.
Принятый результат и отказ сохраняются в существующем журнале с исходными тактом и ревизией. Точный повтор возвращает прежнюю квитанцию даже после удаления заказа. Другой ID или замена отмены на возобновление под тем же номером возвращает `Conflict`; новый успешный эффект увеличивает ревизию ровно один раз. Используется существующий контракт [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6) для журнала и [#8](https://git.faumaray.com/Void/Library/issues/8) для физического перехода. У закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792` нет готового игрового жизненного цикла заказа; условия замены журнала и передачи имущества сохраняются в этих задачах.
В обычном окне игры команда находится в **Работы → Управление заказами…**. После выбора клетки меню показывает явные «Отменить» / «Возобновить», название работы, постоянный ID и координаты. Несколько заказов одной клетки остаются отдельными действиями; страницы содержат до 16 заказов с переходами вперёд и назад. Отмена предлагается для незавершённых активных работ, возобновление — для приостановленных. Завершённые итоговые объекты сохраняют прежний отказ `Busy` от ядра. Перед отправкой повторно проверяются актуальный заказ, полная идентичность сессии, поколение представления, начавшаяся смена мира, сетевое соединение и выбранный режим. Открытый снимок удерживается до закрытия меню. Диалог из прежней колонии не может отправить действие в новую; гость LAN 11 не видит инструмент и не может вызвать его синтетической командой окна.
До квитанции интерфейс показывает ожидание подтверждения. Подтверждённая отмена сообщает о сохранении установленных частей и последующем возврате груза; возобновление сообщает о продолжении работы. У возвращающего материалы жителя видны действительный состав сумки и причина ожидания: отсутствие доступного склада, недостаток места, занятый склад либо предел учёта. Прежние `DemolishObject` / `MoveObject` сохраняют отказы при занятом источнике, складе и объекте.
Проверки с реальным ядром: [production_commands_tests.cpp](../../../tests/production_commands_tests.cpp) — повтор принятых/отклонённых результатов, конфликты вариантов и ID, границы контекста и прав, отмена до получения/в пути/на площадке, ожидание полного склада и возврат всех материалов, продолжение частичной кровати и установленного станка, публикация runtime. [production_controls_tests.cpp](../../../tests/production_controls_tests.cpp) создаёт настоящее Win32-окно с Direct3D, выбирает клетку обычными сообщениями мыши, проходит меню клавиатурным вводом через `WM_TIMER`, проверяет квитанции обоих действий, выбор точного ID и доступ ко всем 35 заказам на одной клетке, смену мира во время меню, подключённого гостя LAN 11 и причину ожидания возвращающегося жителя. Каждый запуск окна использует отдельный временный каталог пользовательских данных.
На объединённом ядре S06 и кодеке S15 выполнена сборка Windows x64 GCC 16.2; полный `ctest -V` под Wine 11 прошёл 4 исполняемых набора: 160 core, 4 LAN, 14 viewer-session и 6 Win32 controls. В предыдущем полном прогоне один существовавший тест восстановления после сбоя (`viewer_session_tests.cpp:363`) однократно не получил ожидаемый допуск синхронизации; отдельный повтор и итоговый полный прогон прошли. Нативные Windows и MSVC не проверялись.
## Данные и владение
| Новый объект | Ответственность |
+3 -1
View File
@@ -51,7 +51,9 @@ Windows-адаптер чтения связан с [Void/Library #9](https://gi
Экспорт 13 и 14 вызывает чистую проверку представимости до первого байта. `UnsupportedLegacyState` сообщает о возвращаемом несовместимом грузе, приостановленной площадке и нулевом времени ожидающего завершения. Эти состояния полностью сохраняются в современной контрольной точке. Правила собственности и фаз проверяет общий `World::validate_custody`; кодек дополнительно проверяет геометрию, задания, ссылки, размеры и каноничность полей.
[Исторический корпус](../../../tests/fixtures/custody_v14/README.md) содержит 13 подлинных контрольных точек схемы 2, созданных исходной сборкой `f6493e2`, и ожидаемые хеши 80 последующих тактов. Первый объединённый прогон Windows x64 под Wine подтвердил все такты на последовательном исполнителе и 2/6/12 потоках, точный экспорт 14, канонический цикл схемы 3 и продолжение после загрузки. Отдельно проверены отменённая одиночная доска и каменный блок, смешанный груз без места, частичный возврат, приостановленные кровать и станок, нулевой таймер, старые ссылки квитанций и отказ после аутентифицированного повреждения. [Проверки миграции](../../../tests/custody_migration_tests.cpp) · [Снимки с полной версией 15](../../../tests/snapshot_tests.cpp)
[Исторический корпус](../../../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 и сохранность после отключения питания остаются отдельными проверками.
+16
View File
@@ -51,6 +51,22 @@
Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается.
Проверка представимости фактического имущества выполняется до приёма соединения, перед каждым разобранным сообщением и перед отправкой, включая продолжение ранее поставленного снимка или квитанции. `World::legacy_representable()` проверяет игровой контракт без пробной сериализации. Если отменённый груз или приостановленная площадка не имеют точного представления в формате 13, адаптер закрывает гостя и очищает его буферы. Слушатель, современный владелец и принятая им работа сохраняются; готовая квитанция прежнего подключения не отправляется следующему гостю. При работе с фоновым владельцем каждое сообщение и отправка сверяют свежую публикацию и инкарнацию. Прежний `poll(World&)` применяет ту же проверку представимости.
Общий `ViewerSession::can_host_legacy()` разрешает создание слушателя только для опубликованной представимой активной колонии 32×32 с точными встроенными правилами, вне гостевого режима и смены партии. Это ограничение совместимости не блокирует современные команды и контрольные точки. Историческая активная колония с простым рецептом кровати и встроенным манифестом остаётся допустимой. [Контракт S16-03](../../agent-workflow/tasks/S16-03.md)
Проверка представимости снимка сама по себе не разрешает позднейший допуск команды. `SimulationRuntime::try_submit_if_current` сравнивает удержанную проверенную публикацию с текущей и проверяет рабочее состояние под тем же mutex, который защищает публикацию и постановку в очередь. Пустая ссылка получает `InvalidRequest`, нерабочий владелец — `Closed`, сменившаяся публикация — `StaleSnapshot`; конкуренция за mutex и заполненная очередь возвращают `Busy`. Сравнение публикаций предшествует проверке вместимости очереди. Внутри блокировки нет сканирования мира или сериализации. Обычный `try_submit` сохраняет прежний контракт. Уже допущенные операции не отзываются последующей публикацией.
Адаптер передаёт точную проверенную ссылку. При `StaleSnapshot` или `Busy` он заново проверяет текущую публикацию: несовместимое имущество, отказ владельца или другая инкарнация закрывают гостя и очищают буферы. Совместимое новое состояние возвращает честный `Busy` с актуальным прежним номером команды, чтобы гость мог повторить намерение. Цикла повторных допусков в сетевом опросе нет. Необязательный диагностический `LanSessionOptions::before_command_admission` позволяет остановить поток опроса ровно между проверкой и допуском, не удерживая блокировку владельца. [Контракт S16-04](../../agent-workflow/tasks/S16-04.md)
Общий контракт условного допуска отслеживается отдельно от публикации и журнала результатов в [Void/Library #16](https://git.faumaray.com/Void/Library/issues/16). Закреплённый `FuturePool::try_submit` проверяет лимит и остановку исполнителя, но не игровую публикацию. Условие замены локального допуска — сохранить точное сравнение удержанного снимка и постановку в ограниченную очередь одной критической секцией и повторить управляемую гонку: после проверки представимого S реальный владелец публикует несовместимое S+1 в той же инкарнации, затем гость пытается войти в очередь. До исправления регрессия реально продвинула номер запроса гостя с 1 до 2. Она также проверяет совместимую новую публикацию с повтором прежнего сетевого номера, отсутствие эффектов отказа, завершение ранее допущенной работы и отказ после сбоя владельца.
Проверка S16-04 на базе `c183de1`: Windows x64 Release GCC 16.2 под Wine 11, 4/4 новых `lan-admission`; полный CTest — 168/168 core, 17/17 LAN, 15/15 клиента и 6/6 управления заказами. После исправления управляемая гонка сохраняет точную публикацию отмены, прежние сетевой номер и номер запроса гостя, профессию жителя и отсутствие квитанции в журнале. Старый скомпилированный клиент и заново собранный адаптер успешно обменялись приказами в обеих ролях. `git diff --check` прошёл. Нативная Windows, MSVC и физические машины этим прогоном не проверялись.
Для этого адаптера повторно проверены публичный `Void/Net/Socket.hpp`, Windows-ветка `src/Net/Socket.cpp` и `tests/standalone/Net/Socket.cpp` закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792`: UDP не реализован для Windows и не предоставляет игровую проверку представимости. Существующий TCP-транспорт остаётся прежним. Имущество и условие отказа принадлежат игровому адаптеру поверх операций [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8); новое универсальное сетевое средство не вводится.
Проверка S16-03 на интеграционной базе `5c309b2`: Windows x64 Release GCC 16.2 под Wine 11, 13/13 LAN и 15/15 клиента. Четыре новых LAN-сценария проверяют настоящий отменённый смешанный груз при полном складе, отказ входа, сохранение современного мира, завершение ранее допущенного приказа и отсечение следующего приказа в той же инкарнации, а также удаление недосланного снимка размером больше 64 КиБ на обоих путях хоста. Отдельно проходят 3/3 `wire` и 9/9 `lan-owner`. Старый скомпилированный клиент и новый адаптер обменялись приказами в обеих ролях. Оба старых корпуса формата 13 (738 386 и 393 857 байтов) совпали полностью на 1/2/6/12 исполнителях. Полный CTest этой базы выявил два отказа `production-command` и четыре отказа `production-controls` в параллельном срезе S04; их исправление и повторная общая проверка относятся к интеграции. Нативная Windows, MSVC и две физические машины этим прогоном не проверялись.
Пять проверок `--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)
+9 -3
View File
@@ -1,6 +1,6 @@
# S18. Интерфейс, управление и обратная связь
Статус — первый срез S18-W01 реализован: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
Статус — первый срез S18-W01 и выбор двух встроенных правил S18-02 реализованы: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Исходное состояние
@@ -16,7 +16,11 @@
## Последовательность реализации
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное и загружаемое состояние проверяются на карту 32×32 и точное совпадение поддержанного стандартного состава правил. Настоящие альтернативные правила относятся к [S19](S19.md).
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное, непосредственно заменяемое и последнее подготовленное состояние проходят `validate_colony_checkpoint` из [S19](S19.md) до установки и дополнительно ограничены картой 32×32. Допускаются только точные встроенные составы стандартной колонии и `settlement.plankbeds`; неизвестный, лишний или изменённый пакет, пустой мир, нулевой идентификатор либо поэтапная кровать с простыми правилами отклоняются с сохранением текущего мира.
На настоящем главном экране нативный список «Правила только новой колонии» выбирает поэтапную кровать с опорой и тканью (исходный выбор) либо простую кровать из одной доски. Выбор живёт в процессе и применяется только кнопкой «Новая колония»: `make_colony_checkpoint` создаёт соответствующий мир, новый UUID и точный манифест. «Продолжить», список сохранений и выбор файла восстанавливают правила самого сохранения. Исторический стандартный мир с простыми кроватями, поэтапными кроватями или без активного сценария принимается без смены режима. В простом режиме описания всех готовых домов, включая дом шахтёра, показывают одну доску; выбор деревянной/каменной опоры скрыт.
Старый LAN-протокол 11 допускает только точный стандартный манифест из текущей авторитетной публикации. Проверка выполняется при выборе Host после возврата из модального меню, а для отложенного создания — повторно перед запуском сети после установки мира. Пока ожидается любая смена мира, Host отклоняется без замены мира, отмены загрузки или изменения сетевого объекта. Даже если опубликованный старый мир стандартный, ожидающая загрузка простых правил не открывает слушатель. Выход старого гостя по-прежнему присваивает полученному миру замороженные стандартные правила; формат LAN не расширен.
Локальная очередь ограничена 64 намерениями и одной отправленной командой. Номер запроса берётся из подтверждённого снимка; занятая очередь владельца оставляет намерение для повтора. Чертёж комнаты, мебели или старого домика удаляется только после принятого результата. Отказ сохраняет возможность редактирования, повторное нажатие не дублирует ожидающую операцию. Гостевые квитанции сопоставляются с ограниченной очередью отправок и поколением сессии. Таймер обслуживает завершения также на главном экране и внутри модальных меню. Одиночная пауза и выбор файла приостанавливают игровое время; меню хозяина сохраняет существующее сетевое поведение.
@@ -24,6 +28,8 @@
Проверка среза: сборка Windows x64 GCC 16.2; Wine 11, verbose CTest — 99 проверок ядра, 9 LAN и 10 состояния клиента. Отдельный прогон настоящего `settlement_viewer.exe` прошёл создание колонии, движение времени, подтверждённую смену приоритета, модальную паузу, выбор файла сохранения, продолжение партии, загрузку нового формата через главное меню в новом процессе, отказ повреждённого файла, загрузку старого формата из списка и штатное закрытие трёх процессов. Сохранения размещались в отдельном временном `LOCALAPPDATA`. Дополнительный Win32-прогон настоящих обработчиков проверил отказ и повтор чертежа, принятую комнату при переносе другой комнаты, старый домик через общий журнал, отрисовку и сохранение при заблокированном тике, смену мира и гостя без ожидания тика. Регрессионный прогон проверил отказ ошибочного повторного подключения с сохранением полученной колонии, откат при отказе владельца после подготовки соединения и запрет подтверждения сноса во время ожидающей загрузки. Отдельная проверка состояния клиента покрывает остановку после сбоя, успешную загрузку и возобновление тиков. Нативная Windows, доступность и визуальная проверка масштабирования остаются отдельной приёмкой; настройки масштаба, клавиш и звука за пределами этого среза.
Проверка S18-02: повторная Windows x64 GCC 16.2 сборка и verbose CTest под Wine 11 — 122 проверки ядра, 9 LAN и 14 состояния клиента. Четыре новые проверки покрывают оба профиля при создании/сохранении/повторной загрузке, начальные и асинхронные отказы манифестов и идентификаторов, отмену актуальности старой правильной загрузки последующей несовместимой, исторические режимы и стандартный импорт гостя. Отдельный прогон настоящего приложения в изолированном `LOCALAPPDATA` проверяет окно 775×640, Tab/стрелки и мышь в нативном списке, мышь/Space на «Новая колония», точные манифесты и режимы в реальных сохранениях, продолжение, список и диалог открытия при противоположном выборе новых правил. Новый процесс возвращает стандартный выбор новой колонии и открывает последнее сохранение с простыми правилами. Прогон настоящих обработчиков удерживает загрузку простого мира поверх стандартного при прямом Host и Host из модального меню, проверяет сохранение мира/билета/сетевого объекта/кода/порта и отсутствие слушателя; отложенный Host повторно отклоняет несовместимую установленную публикацию. Проверены скрытие опор и описание дома шахтёра. Нативная Windows, экранный диктор и повышенный DPI остаются отдельной приёмкой.
1. **S18-W01, M01–M02.** Отделить чтение снимков и отправку команд от Win32-обработчиков. Определить модель состояния инструмента, выделения и отмены. Добавить настройку масштаба, клавиш и звука с проверкой конфликтов назначений.
2. **S18-W02, M02–M03.** Собрать путь демо. Игрок размечает склон, ставит склад, выбирает этаж, редактирует дом, видит материалы и подтверждает строительство. Затем назначает мебель, проверяет потребности жителей и сохраняет незавершённую работу.
3. **S18-W03, M04–M06.** Добавить панели рабочих очередей, профессий, запасов и торговых сделок. Фильтры и сортировки устойчиво сохраняют выбранный объект при обновлении снимка. Список населения ведёт к жителю или объясняет его нахождение в другом регионе.
@@ -50,7 +56,7 @@
## VoidLibrary
Сверить доступные возможности конфигурации, строк, 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)
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Выбор S18-02 использует готовые фабрику и проверку профилей S19; общий пробел разрешения пакетов связан с [Void/Library #4](https://git.faumaray.com/Void/Library/issues/4). Схема игровых правил и нативные контролы остаются у игры. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
## Приёмка
@@ -44,7 +44,18 @@ struct LegacyCabinPayload {
bool operator==(const LegacyCabinPayload&) const = default;
};
using SessionPayload = std::variant<CommandPayload, LegacyCabinPayload>;
struct CancelProductionPayload {
ProductionId production = 0;
bool operator==(const CancelProductionPayload&) const = default;
};
struct ResumeProductionPayload {
ProductionId production = 0;
bool operator==(const ResumeProductionPayload&) const = default;
};
using SessionPayload = std::variant<CommandPayload, LegacyCabinPayload,
CancelProductionPayload, ResumeProductionPayload>;
struct CommandEnvelope {
std::uint32_t version = command_envelope_version;
@@ -15,7 +15,7 @@
namespace settlement {
enum class RuntimeState { Running, Faulted, Closed };
enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted, StaleSnapshot };
enum class RuntimeOutcome { Completed, Faulted, Closed, Superseded, InvalidCandidate };
enum class RuntimePhase { BeforeTick, BeforeCapture, BeforeInstallCapture };
@@ -77,6 +77,14 @@ public:
[[nodiscard]] std::optional<DispatchReceipt> lookup(
TrustedClient client, const CommandEnvelope& command) const;
[[nodiscard]] RuntimeSubmission try_submit(TrustedClient client, const CommandEnvelope& command);
// Atomically admit against the exact retained publication inspected by the
// caller. Null returns InvalidRequest; a nonrunning owner returns Closed;
// a different publication returns StaleSnapshot, before checking capacity.
// Mutex contention or full capacity returns Busy. Refusals have no future.
// Later publications never revoke work that was already admitted.
[[nodiscard]] RuntimeSubmission try_submit_if_current(
TrustedClient client, const CommandEnvelope& command,
const std::shared_ptr<const PublishedSnapshot>& expected);
[[nodiscard]] RuntimeSubmission set_ticking(bool enabled);
// Fences earlier queued operations and all eligible clock debt through the
// admission time. Advancing a ManualClock should be followed by this or notify_clock().
+6
View File
@@ -74,6 +74,12 @@ CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const
}
if (client.player != colony_host) return CommandStatus::Unauthorized;
if (const auto* payload = std::get_if<CancelProductionPayload>(&command.payload)) {
return world.cancel_production(payload->production);
}
if (const auto* payload = std::get_if<ResumeProductionPayload>(&command.payload)) {
return world.resume_production(payload->production);
}
if (world.scenario_active()) return CommandStatus::Unavailable;
const auto& payload = std::get<LegacyCabinPayload>(command.payload);
try {
+17 -1
View File
@@ -107,11 +107,17 @@ struct SimulationRuntime::Impl {
return published->revision + 1;
}
RuntimeSubmission enqueue(std::unique_ptr<Work> work, WorldCheckpoint* candidate = nullptr) {
RuntimeSubmission enqueue(std::unique_ptr<Work> work, WorldCheckpoint* candidate = nullptr,
const std::shared_ptr<const PublishedSnapshot>* expected = nullptr) {
auto completion = work->promise.get_future();
std::unique_lock lock(mutex, std::try_to_lock);
if (!lock.owns_lock()) return {RuntimeAdmission::Busy, {}};
if (stopping.load()) return {RuntimeAdmission::Closed, {}};
if (expected) {
if (!*expected) return {RuntimeAdmission::InvalidRequest, {}};
if (state != RuntimeState::Running) return {RuntimeAdmission::Closed, {}};
if (published != *expected) return {RuntimeAdmission::StaleSnapshot, {}};
}
if (outstanding == options.capacity) return {RuntimeAdmission::Busy, {}};
queue.push_back(std::move(work));
if (candidate) {
@@ -333,6 +339,16 @@ RuntimeSubmission SimulationRuntime::try_submit(TrustedClient client, const Comm
return impl_->enqueue(std::move(work));
}
RuntimeSubmission SimulationRuntime::try_submit_if_current(
TrustedClient client, const CommandEnvelope& command,
const std::shared_ptr<const PublishedSnapshot>& expected) {
if (!expected) return {RuntimeAdmission::InvalidRequest, {}};
auto work = std::make_unique<Impl::Work>(Impl::Kind::Command);
work->client = client;
work->command = command;
return impl_->enqueue(std::move(work), nullptr, &expected);
}
RuntimeSubmission SimulationRuntime::set_ticking(bool enabled) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Ticking);
work->enabled = enabled;
+368 -4
View File
@@ -48,6 +48,29 @@ WorldCheckpoint colony_checkpoint() {
return {make_first_colony(2), *identity, 1, std::move(*rules)};
}
std::unique_ptr<World> mixed_delivery() {
auto world = std::make_unique<World>(43, 32, 32, 2);
const auto store = world->add_storage({3, 3}, 5);
world->stock_storage(store, ItemType::Plank, 3);
world->stock_storage(store, ItemType::StoneBlock, 2);
static_cast<void>(world->spawn_agent({1, 3}));
world->start_scenario({6, 6});
world->queue_production({14, 3}, RecipeId::BuildCabin);
for (int tick = 0; tick < 100 && world->agents().front().inventory.empty(); ++tick) world->step();
const auto& cargo = world->agents().front().inventory;
require(cargo.item_count(ItemType::Plank) == 3 && cargo.item_count(ItemType::StoneBlock) == 2);
// Keep canceled cargo blocked at its real owner through later steps.
world->stock_storage(store, ItemType::Wood, 5);
require(world->legacy_representable());
return world;
}
void cancel_mixed_delivery(World& world) {
require(world.cancel_production(world.production_orders().front().id) == CommandStatus::Accepted);
require(!world.legacy_representable());
world.validate_custody();
}
template<class Pump, class Condition>
void pump_until(Pump pump, Condition condition, const char* message) {
const auto deadline = std::chrono::steady_clock::now() + 3s;
@@ -66,8 +89,7 @@ struct CaptureGate {
bool entered = false;
bool released = false;
void capture(RuntimePhase phase) {
if (phase != RuntimePhase::BeforeCapture) return;
void block() {
std::unique_lock lock(mutex);
if (!armed) return;
entered = true;
@@ -77,6 +99,10 @@ struct CaptureGate {
}
}
void capture(RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture) block();
}
void arm() { std::lock_guard lock(mutex); armed = true; }
bool waiting() { std::lock_guard lock(mutex); return entered; }
void release() {
@@ -115,8 +141,9 @@ struct RawGuest {
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});
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
AgentId resident = 0) {
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value, {}, resident});
lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes));
}
@@ -163,6 +190,14 @@ struct LanTests : Void::Testing::Suite<LanTests> {
[[= 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();
[[= Void::Testing::tag("lan-owner")]] Test test_legacy_custody_refuses_handshake_and_preserves_modern_owner();
[[= Void::Testing::tag("lan-owner")]] Test test_standalone_custody_discards_queued_snapshot_and_command();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_discards_queued_snapshot_before_admission();
[[= Void::Testing::tag("lan-admission")]] Test test_guest_admission_cannot_cross_incompatible_publication();
[[= Void::Testing::tag("lan-admission")]] Test test_guest_retries_same_sequence_after_compatible_publication();
[[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_preserves_accepted_work_and_reports_refusals();
[[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_rejects_faulted_owner_with_retained_publication();
};
Test LanTests::test_protocol_11_fixed_messages() {
@@ -617,4 +652,333 @@ Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() {
require(!guest.take_result());
}
Test LanTests::test_legacy_custody_refuses_handshake_and_preserves_modern_owner() {
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
cancel_mixed_delivery(*initial.world);
const auto encoded = encode_checkpoint(*initial.world, initial.world_id, initial.city, initial.rules);
require(encoded.has_value());
auto packages = builtin_rule_packages();
require(packages.has_value());
auto restored = decode_checkpoint(*encoded, *packages, 2);
require(restored.has_value() && !restored->world->legacy_representable());
SimulationRuntime runtime(std::move(*restored), {.ticking = false});
LanSession host, guest;
host.host(0, true);
const auto port = host.port();
guest.join("127.0.0.1", host.join_code(), port);
for (int attempt = 0; attempt < 20; ++attempt) {
host.poll_host(runtime);
require(!guest.poll_guest());
}
require(host.state() == LanState::Hosting && host.port() == port && !host.detail().empty());
require(guest.state() != LanState::GuestConnected && !guest.take_result());
const auto before = runtime.latest();
const auto& id = before->identity;
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}});
require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready);
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
require(runtime.view().state == RuntimeState::Running && runtime.latest()->world->paused());
const auto current = runtime.latest();
auto saved = encode_checkpoint(*current->world, id.world, id.city, *current->rules);
require(saved.has_value() && decode_checkpoint(*saved, *packages, 2).has_value());
require(current->next_requests[1] == before->next_requests[1]);
}
Test LanTests::test_standalone_custody_discards_queued_snapshot_and_command() {
auto world = mixed_delivery();
// A real historical snapshot larger than one 64 KiB flush leaves output
// queued; gating only a subsequent send_snapshot call misses this case.
for (int job = 0; job < 4096; ++job) static_cast<void>(world->add_job({20, 20}, 1));
std::ostringstream bytes(std::ios::binary);
world->write_save(bytes);
require(bytes.view().size() > 64 * 1024);
LanSession host;
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
guest.poll();
pump_until([&] { static_cast<void>(host.poll(*world)); },
[&] { return host.state() == LanState::HostConnected; }, "Standalone guest did not authenticate.");
guest.poll();
require(!guest.input.empty() && !guest.snapshot);
const auto partial = guest.input.size();
const auto profession = world->agents().front().profession;
cancel_mixed_delivery(*world);
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner),
world->agents().front().id);
guest.poll();
pump_until([&] { static_cast<void>(host.poll(*world)); guest.poll(); },
[&] { return guest.closed; }, "Unsupported standalone peer stayed connected.");
require(host.state() == LanState::Hosting && !host.detail().empty());
require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty());
require(world->next_command_sequence(2) == 1 && world->agents().front().profession == profession);
const auto tick = world->tick();
world->step();
require(world->tick() == tick + 1);
world->validate_custody();
auto compatible = mixed_delivery();
RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16));
const auto pump = [&] { static_cast<void>(host.poll(*compatible)); next.poll(); };
pump_until(pump, [&] { return next.snapshot != nullptr; }, "Representable counterpart could not join.");
next.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner),
compatible->agents().front().id);
pump_until(pump, [&] { return !next.receipts.empty(); }, "Representable counterpart command did not settle.");
require(next.receipts.front().status == CommandStatus::Accepted);
}
Test LanTests::test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work() {
CaptureGate gate;
RuntimeOptions options{.ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
const auto production = initial.world->production_orders().front().id;
const auto resident = initial.world->agents().front().id;
SimulationRuntime runtime(std::move(initial), 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; }, "Custody guest did not join.");
const auto before = runtime.latest();
const auto id = before->identity;
const CommandPayload accepted{CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Miner), {}, resident};
gate.arm();
guest.command(1, accepted.kind, {}, accepted.value, resident);
pump_until(pump, [&] { return gate.waiting(); }, "Guest work did not reach blocked capture.");
auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[0], CancelProductionPayload{production}});
require(canceled.admission == RuntimeAdmission::Accepted);
// This later wire intent is already in TCP when cancellation publishes.
guest.command(2, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Builder), resident);
guest.poll();
gate.release();
require(canceled.completion.wait_for(3s) == std::future_status::ready);
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable());
pump_until(pump, [&] { return guest.closed; }, "Incompatible runtime guest stayed connected.");
require(host.state() == LanState::Hosting && runtime.view().state == RuntimeState::Running);
require(guest.receipts.empty());
const auto current = runtime.latest();
require(current->next_requests[1] == 2 && current->world->next_command_sequence(2) == 2);
require(current->world->agents().front().profession == Profession::Miner);
const auto retained = runtime.lookup({2}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[1], accepted});
require(retained && retained->status == DispatchStatus::Completed && retained->command_status == CommandStatus::Accepted);
require(encode_checkpoint(*current->world, id.world, id.city, *current->rules).has_value());
// A later compatible incarnation can reconnect; neither the retained work
// nor its old socket's reply leaks into the new connection.
auto ticket = runtime.begin_load();
require(ticket.has_value());
auto replacement = colony_checkpoint();
auto installed = runtime.try_install(*ticket, replacement);
require(installed.admission == RuntimeAdmission::Accepted && installed.completion.wait_for(3s) == std::future_status::ready);
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16));
pump_until([&] { host.poll_host(runtime); next.poll(); },
[&] { return next.snapshot != nullptr; }, "Guest could not reconnect after custody cutoff.");
require(next.receipts.empty() && next.snapshot->next_command_sequence(2) == 1);
}
Test LanTests::test_runtime_custody_discards_queued_snapshot_before_admission() {
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
const auto production = initial.world->production_orders().front().id;
const auto resident = initial.world->agents().front().id;
for (int job = 0; job < 4096; ++job) static_cast<void>(initial.world->add_job({20, 20}, 1));
SimulationRuntime runtime(std::move(initial), {.ticking = false});
LanSession host;
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
guest.poll();
pump_until([&] { host.poll_host(runtime); }, [&] { return host.state() == LanState::HostConnected; },
"Queued-snapshot guest did not authenticate.");
guest.poll();
require(!guest.input.empty() && !guest.snapshot);
const auto partial = guest.input.size();
const auto before = runtime.latest();
const auto id = before->identity;
auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[0], CancelProductionPayload{production}});
require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready);
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
guest.poll();
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; },
"Guest receiving queued snapshot was not dropped.");
require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable());
require(runtime.view().state == RuntimeState::Running && host.state() == LanState::Hosting);
require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty());
require(runtime.latest()->next_requests[1] == 1 && runtime.latest()->world->next_command_sequence(2) == 1);
}
Test LanTests::test_guest_admission_cannot_cross_incompatible_publication() {
CaptureGate admission;
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
const auto production = initial.world->production_orders().front().id;
const auto resident = initial.world->agents().front().id;
SimulationRuntime runtime(std::move(initial), {.ticking = false});
LanSession host({.before_command_admission = [&] { admission.block(); }});
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.snapshot != nullptr; },
"Admission-race guest did not join.");
const auto checked = runtime.latest();
const auto id = checked->identity;
const auto old_profession = checked->world->agents().front().profession;
const CommandPayload intent{CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Miner), {}, resident};
const CommandEnvelope envelope{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[1], intent};
admission.arm();
guest.command(1, intent.kind, {}, intent.value, resident);
guest.poll();
auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); });
auto release = Void::Scope::on_exit([&] { admission.release(); });
pump_until([] {}, [&] { return admission.waiting(); }, "Guest did not reach pre-admission barrier.");
// This is a genuine owner publication between the adapter's compatibility
// check of S and admission of the remote command, without an epoch change.
RuntimeSubmission canceled{RuntimeAdmission::Busy, {}};
pump_until([&] {
canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CancelProductionPayload{production}});
}, [&] { return canceled.admission != RuntimeAdmission::Busy; }, "Cancel could not obtain owner admission.");
require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready);
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
const auto cutoff = runtime.latest();
require(cutoff != checked && cutoff->identity.session == id.session && !cutoff->world->legacy_representable());
admission.release();
require(polling.wait_for(3s) == std::future_status::ready);
polling.get();
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
pump_until([&] { fence = runtime.synchronize(); }, [&] { return fence.admission != RuntimeAdmission::Busy; },
"Owner fence could not be admitted.");
require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(3s) == std::future_status::ready);
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
const auto after = runtime.latest();
const auto evidence = "Guest command crossed incompatible publication: next_request=" +
std::to_string(after->next_requests[1]);
if (after->next_requests[1] != checked->next_requests[1]) throw std::runtime_error(evidence);
require(after->world->next_command_sequence(2) == checked->world->next_command_sequence(2));
require(after->world->agents().front().profession == old_profession && !runtime.lookup({2}, envelope));
require(after == cutoff && runtime.view().state == RuntimeState::Running);
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; },
"Race-cutoff peer was not disconnected.");
require(host.state() == LanState::Hosting && guest.receipts.empty());
require(encode_checkpoint(*after->world, id.world, id.city, *after->rules).has_value());
}
Test LanTests::test_guest_retries_same_sequence_after_compatible_publication() {
CaptureGate admission;
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
LanSession host({.before_command_admission = [&] { admission.block(); }});
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; }, "Compatible-race guest did not join.");
const auto checked = runtime.latest();
const auto id = checked->identity;
const auto resident = checked->world->agents().back().id;
admission.arm();
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
guest.poll();
auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); });
auto release = Void::Scope::on_exit([&] { admission.release(); });
pump_until([] {}, [&] { return admission.waiting(); }, "Compatible command did not reach admission barrier.");
RuntimeSubmission local{RuntimeAdmission::Busy, {}};
pump_until([&] {
local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}});
}, [&] { return local.admission != RuntimeAdmission::Busy; }, "Compatible local change could not be admitted.");
require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready);
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
const auto changed = runtime.latest();
require(changed != checked && changed->identity.session == id.session && changed->world->legacy_representable());
admission.release();
require(polling.wait_for(3s) == std::future_status::ready);
polling.get();
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Compatible revision did not report retryable Busy.");
require(guest.receipts.front().status == CommandStatus::Busy && guest.receipts.front().next_sequence == 1);
require(runtime.latest() == changed && changed->next_requests[1] == 1 && host.state() == LanState::HostConnected);
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Same-sequence guest retry did not settle.");
require(guest.receipts.back().status == CommandStatus::Accepted && guest.receipts.back().next_sequence == 2);
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->agents().back().profession == Profession::Miner);
}
Test LanTests::test_conditional_admission_preserves_accepted_work_and_reports_refusals() {
CaptureGate owner;
RuntimeOptions options{.capacity = 2, .ticking = false};
options.observer = [&](RuntimePhase phase) { owner.capture(phase); };
SimulationRuntime runtime(colony_checkpoint(), options);
auto release = Void::Scope::on_exit([&] { owner.release(); });
const auto checked = runtime.latest();
const auto id = checked->identity;
const CommandEnvelope local_command{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}};
const CommandEnvelope guest_command{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[1], CommandPayload{CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Miner), {}, checked->world->agents().back().id}};
const auto invalid = runtime.try_submit_if_current({2}, guest_command, {});
require(invalid.admission == RuntimeAdmission::InvalidRequest && !invalid.completion.valid());
owner.arm();
RuntimeSubmission local{RuntimeAdmission::Busy, {}};
pump_until([&] { local = runtime.try_submit({1}, local_command); },
[&] { return local.admission != RuntimeAdmission::Busy; }, "Local work did not enter owner queue.");
require(local.admission == RuntimeAdmission::Accepted);
pump_until([] {}, [&] { return owner.waiting(); }, "Owner did not reach capture barrier.");
RuntimeSubmission accepted{RuntimeAdmission::Busy, {}};
pump_until([&] { accepted = runtime.try_submit_if_current({2}, guest_command, checked); },
[&] { return accepted.admission != RuntimeAdmission::Busy; }, "Conditional work did not enter remaining slot.");
require(accepted.admission == RuntimeAdmission::Accepted);
const auto full = runtime.try_submit_if_current({2}, guest_command, checked);
require(full.admission == RuntimeAdmission::Busy && !full.completion.valid());
// Both operations were admitted while S was current. Publishing the local
// result must not revoke the already queued guarded guest operation.
owner.release();
require(local.completion.wait_for(3s) == std::future_status::ready &&
local.completion.get().receipt->command_status == CommandStatus::Accepted);
require(accepted.completion.wait_for(3s) == std::future_status::ready &&
accepted.completion.get().receipt->command_status == CommandStatus::Accepted);
const auto current = runtime.latest();
require(current != checked && current->next_requests[1] == 2);
RuntimeSubmission stale{RuntimeAdmission::Busy, {}};
pump_until([&] { stale = runtime.try_submit_if_current({2}, guest_command, checked); },
[&] { return stale.admission != RuntimeAdmission::Busy; }, "Stale snapshot refusal remained contended.");
require(stale.admission == RuntimeAdmission::StaleSnapshot && !stale.completion.valid());
require(runtime.latest() == current);
runtime.shutdown();
const auto closed = runtime.try_submit_if_current({2}, guest_command, current);
require(closed.admission == RuntimeAdmission::Closed && !closed.completion.valid());
}
Test LanTests::test_conditional_admission_rejects_faulted_owner_with_retained_publication() {
RuntimeOptions options{.ticking = false};
options.observer = [](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected guarded-admission fault.");
};
SimulationRuntime runtime(colony_checkpoint(), options);
const auto checked = runtime.latest();
const auto id = checked->identity;
const CommandEnvelope command{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}};
RuntimeSubmission fault{RuntimeAdmission::Busy, {}};
pump_until([&] { fault = runtime.try_submit({1}, command); },
[&] { return fault.admission != RuntimeAdmission::Busy; }, "Fault trigger remained contended.");
require(fault.admission == RuntimeAdmission::Accepted && fault.completion.wait_for(3s) == std::future_status::ready);
require(fault.completion.get().outcome == RuntimeOutcome::Faulted);
require(runtime.latest() == checked && runtime.view().state == RuntimeState::Faulted);
RuntimeSubmission denied{RuntimeAdmission::Busy, {}};
pump_until([&] { denied = runtime.try_submit_if_current({1}, command, checked); },
[&] { return denied.admission != RuntimeAdmission::Busy; }, "Faulted owner refusal remained contended.");
require(denied.admission == RuntimeAdmission::Closed && !denied.completion.valid());
require(runtime.latest() == checked && !runtime.lookup({1}, command));
}
} // namespace
+275
View File
@@ -0,0 +1,275 @@
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Testing/Suite.hpp>
#include <chrono>
#include <limits>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using Void::Testing::Test;
using namespace std::chrono_literals;
constexpr TrustedClient host{colony_host};
void require(bool condition, const char* message = "production command invariant failed") {
if (!condition) throw std::runtime_error(message);
}
SessionIdentity identity() {
SessionIdentity result;
result.world.bytes.back() = 61;
result.session.bytes.back() = 62;
return result;
}
CommandEnvelope envelope(std::uint64_t request, SessionPayload payload, SessionIdentity context = identity()) {
return {command_envelope_version, context.world, context.session, context.city, request, std::move(payload)};
}
DispatchReceipt send(World& world, CommandDispatcher& dispatcher, SessionPayload payload) {
return dispatcher.dispatch(world, host, envelope(dispatcher.next_request(host), std::move(payload)));
}
void accepted(const DispatchReceipt& receipt) {
require(receipt.status == DispatchStatus::Completed && receipt.command_status == CommandStatus::Accepted,
"production command was not accepted");
}
template<class Predicate>
void step_until(World& world, Predicate done) {
for (int tick = 0; tick < 600 && !done(); ++tick) world.step();
require(done(), "actual work did not reach the required phase");
world.validate_custody();
}
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);
return world;
}
RuntimeResult finish(RuntimeSubmission submission) {
require(submission.admission == RuntimeAdmission::Accepted);
require(submission.completion.wait_for(5s) == std::future_status::ready);
auto result = submission.completion.get();
require(result.outcome == RuntimeOutcome::Completed && result.receipt.has_value());
return result;
}
struct [[= Void::Testing::name("ProductionCommandsTests")]] ProductionCommandsTests
: Void::Testing::Suite<ProductionCommandsTests> {
[[= Void::Testing::tag("production-command")]] Test exact_results_and_conflicts_use_durable_ids();
[[= Void::Testing::tag("production-command")]] Test context_and_guest_denials_leave_orders_untouched();
[[= Void::Testing::tag("production-command")]] Test cancel_at_each_phase_returns_actual_cargo_once();
[[= Void::Testing::tag("production-command")]] Test full_storage_preserves_return_until_space_exists();
[[= Void::Testing::tag("production-command")]] Test resume_keeps_partial_bed_and_installed_loom_identity();
[[= Void::Testing::tag("production-command")]] Test runtime_publishes_and_retains_modern_receipts();
};
Test ProductionCommandsTests::exact_results_and_conflicts_use_durable_ids() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
world.queue_production({8, 8}, RecipeId::SawPlank);
world.queue_production({8, 8}, RecipeId::SawPlank);
const auto first = world.production_orders().front().id;
const auto second = world.production_orders().back().id;
CommandDispatcher dispatcher(identity());
const auto cancel = envelope(1, CancelProductionPayload{first});
const auto result = dispatcher.dispatch(world, host, cancel);
accepted(result);
require(result.revision == 1 && world.find_production(first) == nullptr && world.find_production(second),
"cancel selected by vector position or cell instead of exact durable id");
require(dispatcher.dispatch(world, host, cancel) == result && dispatcher.lookup(host, cancel) == result);
for (const SessionPayload changed : {SessionPayload{CancelProductionPayload{second}},
SessionPayload{ResumeProductionPayload{first}}, SessionPayload{CommandPayload{}},
SessionPayload{LegacyCabinPayload{{8, 8}, {2, 2}, {3, 2}}}}) {
require(dispatcher.dispatch(world, host, envelope(1, changed)).status == DispatchStatus::Conflict,
"same request accepted a different id or payload variant");
}
const auto refused = envelope(2, ResumeProductionPayload{first});
const auto rejection = dispatcher.dispatch(world, host, refused);
require(rejection.status == DispatchStatus::Completed && rejection.command_status == CommandStatus::InvalidTarget &&
rejection.revision == 1 && dispatcher.dispatch(world, host, refused) == rejection);
const auto zero = envelope(3, CancelProductionPayload{0});
const auto zero_result = dispatcher.dispatch(world, host, zero);
require(zero_result.command_status == CommandStatus::InvalidTarget && dispatcher.dispatch(world, host, zero) == zero_result);
accepted(send(world, dispatcher, CancelProductionPayload{second}));
require(world.production_orders().empty() && dispatcher.revision() == 2 &&
world.next_command_sequence(1) == 1 && world.next_command_sequence(2) == 1,
"modern command changed legacy accepted-command numbering");
require(dispatcher.dispatch(world, host, cancel) == result, "removed target lost the original retained receipt");
world.validate_custody();
}
Test ProductionCommandsTests::context_and_guest_denials_leave_orders_untouched() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
world.queue_production({8, 8}, RecipeId::BuildCabin);
const auto id = world.production_orders().front().id;
CommandDispatcher dispatcher(identity());
auto command = envelope(1, CancelProductionPayload{id});
command.world.bytes.back() ^= 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::WrongWorld);
command = envelope(1, CancelProductionPayload{id});
command.session.bytes.back() ^= 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::StaleSession);
command = envelope(1, CancelProductionPayload{id});
require(dispatcher.dispatch(world, {0}, command).status == DispatchStatus::UnauthorizedClient);
require(dispatcher.dispatch(world, {3}, command).status == DispatchStatus::UnauthorizedClient);
require(dispatcher.receipt_count(host) == 0 && dispatcher.revision() == 0 && world.find_production(id));
const auto guest_result = dispatcher.dispatch(world, {2}, command);
require(guest_result.command_status == CommandStatus::Unauthorized &&
dispatcher.dispatch(world, {2}, command) == guest_result);
const auto guest_resume = envelope(2, ResumeProductionPayload{id});
require(dispatcher.dispatch(world, {2}, guest_resume).command_status == CommandStatus::Unauthorized);
command.city = 2;
const auto denied = dispatcher.dispatch(world, host, command);
require(denied.command_status == CommandStatus::Unauthorized && denied.revision == 0 &&
dispatcher.dispatch(world, host, command) == denied && world.find_production(id));
command.city = 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::Conflict);
command.request = 2;
accepted(dispatcher.dispatch(world, host, command));
command.world.bytes.back() ^= 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::WrongWorld,
"cached receipt bypassed world identity check");
require(world.next_command_sequence(1) == 1 && world.next_command_sequence(2) == 1);
}
Test ProductionCommandsTests::cancel_at_each_phase_returns_actual_cargo_once() {
for (int phase = 0; phase < 3; ++phase) {
auto world = cabin();
const auto id = world->production_orders().front().id;
const auto storage = world->storages().front().id;
step_until(*world, [&] {
const auto& agent = world->agents().front();
return phase == 0 ? agent.state == AgentState::FetchingMaterials && agent.inventory.empty() :
phase == 1 ? !agent.inventory.empty() : agent.state == AgentState::Working;
});
CommandDispatcher dispatcher(identity());
const auto sequence = world->next_command_sequence(1);
require(send(*world, dispatcher, CommandPayload{CommandKind::DemolishObject, {3, 3}}).command_status == CommandStatus::Busy);
require(send(*world, dispatcher, CommandPayload{CommandKind::MoveObject, {3, 3}, 0, {4, 3}}).command_status == CommandStatus::Busy);
const auto cancel = envelope(dispatcher.next_request(host), CancelProductionPayload{id});
const auto result = dispatcher.dispatch(*world, host, cancel);
accepted(result);
if (phase != 0) require(world->agents().front().state == AgentState::Returning &&
!world->agents().front().inventory.empty(), "cancellation erased carried or worksite input");
require(dispatcher.dispatch(*world, host, cancel) == result);
step_until(*world, [&] { return world->agents().front().state != AgentState::Returning; });
require(world->find_storage(storage)->item_count(ItemType::Plank) == 3 &&
world->find_storage(storage)->item_count(ItemType::StoneBlock) == 2 &&
world->agents().front().inventory.empty() && world->find_production(id) == nullptr,
"cancelled material was lost, duplicated or left assigned");
for (int tick = 0; tick < 4; ++tick) world->step();
require(dispatcher.dispatch(*world, host, cancel) == result && world->next_command_sequence(1) == sequence &&
world->find_storage(storage)->item_count(ItemType::Plank) == 3 &&
world->find_storage(storage)->item_count(ItemType::StoneBlock) == 2);
world->validate_custody();
}
}
Test ProductionCommandsTests::full_storage_preserves_return_until_space_exists() {
auto world = cabin();
const auto id = world->production_orders().front().id;
const auto original = world->storages().front().id;
step_until(*world, [&] { return !world->agents().front().inventory.empty(); });
world->stock_storage(original, ItemType::Wood, 20);
CommandDispatcher dispatcher(identity());
accepted(send(*world, dispatcher, CancelProductionPayload{id}));
for (int tick = 0; tick < 10; ++tick) world->step();
const auto& waiting = world->agents().front();
require(waiting.state == AgentState::Returning && waiting.execution &&
(waiting.execution->blocked == CustodyStatus::NoDestination || waiting.execution->blocked == CustodyStatus::Capacity) &&
waiting.inventory.item_count(ItemType::Plank) == 3 && waiting.inventory.item_count(ItemType::StoneBlock) == 2,
"full storage did not preserve the cargo and meaningful blocked reason");
const auto destination = world->add_storage({4, 3}, 5);
step_until(*world, [&] { return world->agents().front().state != AgentState::Returning; });
require(world->find_storage(destination)->item_count(ItemType::Plank) == 3 &&
world->find_storage(destination)->item_count(ItemType::StoneBlock) == 2 &&
world->find_storage(original)->item_count(ItemType::Wood) == 20);
}
Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identity() {
for (const bool bed : {true, false}) {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
world.start_scenario({2, 2});
const auto storage = world.add_storage({3, 3}, 20);
world.stock_storage(storage, ItemType::Wood, 2);
static_cast<void>(world.spawn_agent({1, 3}));
CommandDispatcher dispatcher(identity());
if (bed) {
accepted(send(world, dispatcher, CommandPayload{CommandKind::PlaceBed, {9, 3}}));
} else {
world.queue_production({9, 3}, RecipeId::BuildLoom);
}
const auto id = world.production_orders().back().id;
step_until(world, [&] {
const auto* order = world.find_production(id);
return bed ? order->bed_stage == BedStage::Bedding : order->recipe == RecipeId::WeaveCloth;
});
const auto before_cancel = world.capture();
const auto stage = world.find_production(id)->bed_stage;
const auto sequence = world.next_command_sequence(1);
accepted(send(world, dispatcher, CancelProductionPayload{id}));
require(world.find_production(id) && world.find_production(id)->suspended &&
world.find_production(id)->bed_stage == stage && !world.can_place_storage({9, 3}),
"cancel removed installed progress or its occupied site");
const auto suspended_cancel = envelope(dispatcher.next_request(host), CancelProductionPayload{id});
const auto busy = dispatcher.dispatch(world, host, suspended_cancel);
require(busy.status == DispatchStatus::Completed && busy.command_status == CommandStatus::Busy &&
dispatcher.dispatch(world, host, suspended_cancel) == busy);
for (int tick = 0; tick < 5; ++tick) world.step();
const auto resume = envelope(dispatcher.next_request(host), ResumeProductionPayload{id});
const auto resumed = dispatcher.dispatch(world, host, resume);
accepted(resumed);
require(world.find_production(id) && !world.find_production(id)->suspended &&
world.find_production(id)->bed_stage == stage && dispatcher.dispatch(world, host, resume) == resumed &&
world.next_command_sequence(1) == sequence && !before_cancel->find_production(id)->suspended);
require(dispatcher.dispatch(world, host, suspended_cancel) == busy && !world.find_production(id)->suspended,
"old refused cancellation changed after the same durable order was resumed");
world.stock_storage(storage, bed ? ItemType::Cloth : ItemType::Flax, 2);
step_until(world, [&] { return bed ? world.find_production(id)->state == JobState::Completed :
world.find_storage(storage)->item_count(ItemType::Cloth) > 0; });
require(world.find_storage(storage)->item_count(ItemType::Wood) == (bed ? 1U : 0U),
"resume charged for an already installed stage twice");
if (bed) {
const auto refused = send(world, dispatcher, CancelProductionPayload{id});
require(refused.command_status == CommandStatus::Busy,
"completed final bed accepted cancel");
}
}
}
Test ProductionCommandsTests::runtime_publishes_and_retains_modern_receipts() {
auto world = cabin();
step_until(*world, [&] { return !world->agents().front().inventory.empty(); });
const auto id = world->production_orders().front().id;
const auto rules = default_rules_manifest();
require(rules.has_value());
SimulationRuntime runtime(WorldCheckpoint{std::move(world), identity().world, 1, *rules}, {.ticking = false});
const auto opening = runtime.latest();
const auto cancel = envelope(1, CancelProductionPayload{id}, opening->identity);
const auto first = finish(runtime.try_submit(host, cancel));
accepted(*first.receipt);
require(first.snapshot->world->find_production(id) == nullptr &&
first.snapshot->world->agents().front().state == AgentState::Returning &&
opening->world->find_production(id) && opening->world->agents().front().state != AgentState::Returning,
"modern runtime effect was not published with independent old snapshot");
const auto repeat = finish(runtime.try_submit(host, cancel));
require(repeat.receipt == first.receipt && runtime.lookup(host, cancel) == first.receipt &&
repeat.snapshot->revision == first.snapshot->revision && repeat.snapshot->next_requests[0] == 2);
const auto changed = finish(runtime.try_submit(host, envelope(1, ResumeProductionPayload{id}, opening->identity)));
require(changed.receipt->status == DispatchStatus::Conflict);
const auto refusal = envelope(2, ResumeProductionPayload{id}, opening->identity);
const auto denied = finish(runtime.try_submit(host, refusal));
require(denied.receipt->command_status == CommandStatus::InvalidTarget &&
finish(runtime.try_submit(host, refusal)).receipt == denied.receipt &&
runtime.latest()->world->next_command_sequence(1) == 1 && runtime.view().state == RuntimeState::Running);
runtime.latest()->world->validate_custody();
}
} // namespace
+330
View File
@@ -0,0 +1,330 @@
// Exercise the real private Win32 controls and modal handlers in their own
// executable, without adding test hooks to the shipping UI or wire protocol.
#include "../app/viewer_win32.cpp"
#include <Void/Testing/Suite.hpp>
#include <chrono>
#include <functional>
namespace production_controls {
using namespace settlement;
using Void::Testing::Test;
using namespace std::chrono_literals;
void require(bool condition, const char* message = "production controls invariant failed") {
if (!condition) throw std::runtime_error(message);
}
constexpr UINT_PTR drive_timer = 904;
struct MenuStep { UINT command; std::function<void()> before_select; };
std::vector<MenuStep> steps;
std::vector<std::vector<std::wstring>> observed_menus;
HMENU active_menu = nullptr;
std::string driver_error;
unsigned timer_attempts = 0;
void key(std::vector<INPUT>& input, WORD code) {
INPUT down{};
down.type = INPUT_KEYBOARD;
down.ki.wVk = code;
input.push_back(down);
down.ki.dwFlags = KEYEVENTF_KEYUP;
input.push_back(down);
}
LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
if (message == WM_INITMENUPOPUP) {
active_menu = reinterpret_cast<HMENU>(wparam);
std::vector<std::wstring> labels;
for (int index = 0; index < GetMenuItemCount(active_menu); ++index) {
wchar_t label[512]{};
GetMenuStringW(active_menu, static_cast<UINT>(index), label, 512, MF_BYPOSITION);
labels.emplace_back(label);
}
observed_menus.push_back(std::move(labels));
}
if (message == WM_TIMER && wparam == drive_timer) {
if (++timer_attempts > 100) {
driver_error = "real popup did not accept input: menus=" + std::to_string(observed_menus.size()) +
" remaining=" + std::to_string(steps.size()) + " active=" + std::to_string(active_menu != nullptr);
KillTimer(window, drive_timer);
EndMenu();
return 0;
}
if (!active_menu || steps.empty()) return 0;
const auto menu = std::exchange(active_menu, nullptr);
auto step = std::move(steps.front());
steps.erase(steps.begin());
int target = -1;
for (int index = 0; index < GetMenuItemCount(menu); ++index) {
if (GetMenuItemID(menu, index) == step.command) { target = index; break; }
}
if (target < 0) {
driver_error = "expected action absent from actual popup";
EndMenu();
return 0;
}
try {
if (step.before_select) step.before_select();
} catch (const std::exception& error) {
driver_error = error.what();
EndMenu();
return 0;
}
std::vector<INPUT> input;
key(input, VK_HOME);
for (int index = 0; index < target; ++index) {
if ((GetMenuState(menu, static_cast<UINT>(index), MF_BYPOSITION) & MF_SEPARATOR) == 0) key(input, VK_DOWN);
}
key(input, VK_RETURN);
if (SendInput(static_cast<UINT>(input.size()), input.data(), sizeof(INPUT)) != input.size()) {
driver_error = "SendInput failed for actual popup";
EndMenu();
}
return 0;
}
return window_proc(window, message, wparam, lparam);
}
struct Window {
HWND handle = nullptr;
std::filesystem::path user_data;
std::wstring old_user_data;
explicit Window(std::unique_ptr<World> initial) {
const auto uuid = Void::Uuid::try_v4();
require(uuid.has_value());
user_data = std::filesystem::temp_directory_path() / ("settlement-order-controls-" + uuid->to_string());
require(std::filesystem::create_directory(user_data));
wchar_t old[32768]{};
const auto size = GetEnvironmentVariableW(L"LOCALAPPDATA", old, 32768);
old_user_data.assign(old, size < 32768 ? size : 0);
require(SetEnvironmentVariableW(L"LOCALAPPDATA", user_data.c_str()));
auto rules = default_rules_manifest();
require(rules.has_value());
session = std::make_unique<settlement::viewer::ViewerSession>(
WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 2);
world = session->world();
showing_title = true;
has_session = true;
lan = std::make_unique<settlement::viewer::LanSession>();
displayed_lan_state = LanState::Offline;
placement_mode = PlacementMode::None;
camera = {};
placement_message.clear();
steps.clear();
observed_menus.clear();
active_menu = nullptr;
driver_error.clear();
timer_attempts = 0;
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES};
require(InitCommonControlsEx(&controls));
WNDCLASSW type{};
type.lpfnWndProc = test_window_proc;
type.hInstance = GetModuleHandleW(nullptr);
type.lpszClassName = L"SettlementProductionControlsTest";
type.hCursor = LoadCursorW(nullptr, IDC_ARROW);
require(RegisterClassW(&type) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS);
handle = CreateWindowExW(0, type.lpszClassName, L"Production controls test",
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 32, 32, 1120, 752, nullptr, nullptr, type.hInstance, nullptr);
require(handle != nullptr);
show_title_screen(handle, false);
file_dialog_active = true; // Freeze ticks while exercising UI receipt delivery.
KillTimer(handle, timer_id);
session->set_ticking(false);
ShowWindow(handle, SW_SHOW);
UpdateWindow(handle);
SetForegroundWindow(handle);
}
~Window() {
if (handle) DestroyWindow(handle);
session.reset();
world.reset();
file_dialog_active = false;
MSG message{};
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {}
SetEnvironmentVariableW(L"LOCALAPPDATA", old_user_data.empty() ? nullptr : old_user_data.c_str());
std::error_code error;
std::filesystem::remove_all(user_data, error);
}
void menu(std::vector<MenuStep> actions, const std::function<void()>& open) {
steps = std::move(actions);
require(SetTimer(handle, drive_timer, 50, nullptr) != 0);
open();
KillTimer(handle, drive_timer);
require(driver_error.empty(), driver_error.c_str());
require(steps.empty(), "not all popup pages were reachable");
}
void pump_until(const std::function<bool()>& done) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (!done()) {
SendMessageW(handle, WM_TIMER, timer_id, 0);
require(std::chrono::steady_clock::now() < deadline, "UI receipt/replacement did not finish");
std::this_thread::yield();
}
}
void activate_tool() {
menu({{manage_orders_id, {}}}, [&] { SendMessageW(work_list_button, BM_CLICK, 0, 0); });
// The normal work menu posts WM_COMMAND after closing its popup.
MSG message{};
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
require(placement_mode == PlacementMode::ManageOrders, "Работы menu did not activate order management");
}
void click_cell(GridPosition cell) {
RECT client{};
GetClientRect(handle, &client);
const auto scale = camera.scale();
const auto offset = camera.offset();
POINT point{static_cast<LONG>((client.right / 2.0 + (cell.x - cell.y) * tile_width / 2.0) * scale + offset.x),
static_cast<LONG>((map_origin_y + (cell.x + cell.y) * tile_height / 2.0) * scale + offset.y)};
require(map_cell(client, point) == cell, "normal map hit test did not select the target cell");
auto screen = point;
ClientToScreen(handle, &screen);
SetCursorPos(screen.x, screen.y);
const auto coordinates = MAKELPARAM(point.x, point.y);
SendMessageW(handle, WM_LBUTTONDOWN, MK_LBUTTON, coordinates);
SendMessageW(handle, WM_LBUTTONUP, 0, coordinates);
}
};
std::unique_ptr<World> orders(unsigned count = 2) {
auto result = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference);
for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::SawPlank);
return result;
}
struct [[= Void::Testing::name("ProductionControlsTests")]] ProductionControlsTests
: Void::Testing::Suite<ProductionControlsTests> {
[[= Void::Testing::tag("production-controls")]] Test real_work_menu_selects_exact_id_and_waits_for_receipt();
[[= Void::Testing::tag("production-controls")]] Test real_resume_choice_keeps_installed_loom_and_waits_for_receipt();
[[= Void::Testing::tag("production-controls")]] Test every_order_remains_accessible_across_popup_pages();
[[= Void::Testing::tag("production-controls")]] Test replacement_during_popup_cannot_cancel_in_new_world();
[[= Void::Testing::tag("production-controls")]] Test legacy_guest_has_no_action_or_modern_submission();
[[= Void::Testing::tag("production-controls")]] Test returning_resident_explains_wait_for_storage();
};
Test ProductionControlsTests::real_work_menu_selects_exact_id_and_waits_for_receipt() {
Window fixture(orders());
const auto first = world->production_orders().front().id;
const auto second = world->production_orders().back().id;
fixture.activate_tool();
fixture.menu({{2, {}}}, [&] { fixture.click_cell({8, 8}); });
require(world->find_production(second) && world->find_production(first) &&
placement_message.find(L"ожидает подтверждения") != std::wstring::npos,
"UI forged success before a committed receipt");
require(observed_menus.back().at(1).find(L"Отменить: Распилить доску №" + std::to_wstring(second)) != std::wstring::npos &&
observed_menus.back().at(1).find(L"[9, 9]") != std::wstring::npos,
"actual popup lost the order name, durable id or user-facing position");
fixture.pump_until([&] { return !world->find_production(second); });
require(world->find_production(first) && placement_message.find(L"Заказ отменён") != std::wstring::npos &&
session->runtime().latest()->next_requests[0] == 2 && world->next_command_sequence(1) == 1);
}
Test ProductionControlsTests::every_order_remains_accessible_across_popup_pages() {
Window fixture(orders(35));
const auto last = world->production_orders().back().id;
fixture.activate_tool();
fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { fixture.click_cell({8, 8}); });
fixture.pump_until([&] { return !world->find_production(last); });
require(world->production_orders().size() == 34 && world->production_orders().front().id == 1);
for (const auto& page : observed_menus) require(page.size() <= 19, "popup page exceeded its bounded display size");
}
Test ProductionControlsTests::real_resume_choice_keeps_installed_loom_and_waits_for_receipt() {
auto initial = orders(0);
initial->queue_production({8, 8}, RecipeId::WeaveCloth);
const auto id = initial->production_orders().front().id;
require(initial->cancel_production(id) == CommandStatus::Accepted && initial->find_production(id)->suspended);
Window fixture(std::move(initial));
fixture.activate_tool();
fixture.menu({{1, {}}}, [&] { fixture.click_cell({8, 8}); });
require(world->find_production(id)->suspended &&
placement_message.find(L"ожидает подтверждения") != std::wstring::npos);
require(observed_menus.back().at(0).find(L"Возобновить: Ткать ткань №" + std::to_wstring(id)) != std::wstring::npos);
fixture.pump_until([&] { return !world->find_production(id)->suspended; });
require(world->find_production(id)->recipe == RecipeId::WeaveCloth &&
placement_message.find(L"возобновлена") != std::wstring::npos && world->next_command_sequence(1) == 1);
}
Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_world() {
for (const bool complete_replacement : {false, true}) {
Window fixture(orders());
const auto opening = session->runtime().latest();
fixture.activate_tool();
fixture.menu({{1, [&] {
session->new_colony();
if (complete_replacement) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (session->changing_world()) {
static_cast<void>(session->poll());
require(std::chrono::steady_clock::now() < deadline);
std::this_thread::yield();
}
world = session->world();
}
}}}, [&] { fixture.click_cell({8, 8}); });
fixture.pump_until([&] { return !session->changing_world(); });
const auto current = session->runtime().latest();
require(current->identity != opening->identity && current->next_requests[0] == 1 &&
current->world->next_command_sequence(1) == 1,
"stale popup enqueued a production command into the new session");
require(opening->world->production_orders().size() == 2, "modal selection invalidated pinned snapshot");
}
}
Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() {
Window fixture(orders());
const auto host_id = Void::Uuid::try_v4();
const auto rules = default_rules_manifest();
require(host_id.has_value() && rules.has_value());
SimulationRuntime host_runtime(WorldCheckpoint{make_first_colony(2), *host_id, 1, *rules}, {.ticking = false});
settlement::viewer::LanSession host_peer;
host_peer.host(0, true);
session->enter_guest();
lan->join("127.0.0.1", host_peer.join_code(), host_peer.port());
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (lan->state() != LanState::GuestConnected) {
host_peer.poll_host(host_runtime);
if (auto incoming = lan->poll_guest()) session->receive_guest(std::move(incoming));
require(std::chrono::steady_clock::now() < deadline, "real legacy guest did not connect");
std::this_thread::yield();
}
world = session->world();
require(lan->is_guest() && session->guest());
const auto before = session->runtime().latest();
const auto menu = create_work_menu();
require(menu != nullptr && GetMenuState(menu, manage_orders_id, MF_BYCOMMAND) == static_cast<UINT>(-1),
"legacy guest saw the modern management action");
DestroyMenu(menu);
SendMessageW(fixture.handle, WM_COMMAND, manage_orders_id, 0);
require(placement_mode != PlacementMode::ManageOrders && !can_manage_orders());
placement_mode = PlacementMode::ManageOrders;
edit_at_cell(fixture.handle, {8, 8});
require(!enqueue_command(CancelProductionPayload{1}) && !enqueue_command(ResumeProductionPayload{1}) &&
session->runtime().latest() == before && guest_intents.empty(),
"legacy guest admitted a modern order payload");
}
Test ProductionControlsTests::returning_resident_explains_wait_for_storage() {
auto initial = orders(0);
initial->queue_production({8, 8}, RecipeId::BuildCabin);
const auto storage = initial->add_storage({3, 3}, 5);
initial->stock_storage(storage, ItemType::Plank, 3);
initial->stock_storage(storage, ItemType::StoneBlock, 2);
const auto resident = initial->spawn_agent({1, 3});
for (int tick = 0; tick < 100 && initial->agents().front().inventory.empty(); ++tick) initial->step();
require(!initial->agents().front().inventory.empty());
initial->stock_storage(storage, ItemType::Wood, 5);
require(initial->cancel_production(initial->production_orders().front().id) == CommandStatus::Accepted);
for (int tick = 0; tick < 5; ++tick) initial->step();
Window fixture(std::move(initial));
selected_resident = resident;
const auto details = resident_details();
require(details.find(L"Возвращает материалы") != std::wstring::npos &&
(details.find(L"нет доступного склада с местом") != std::wstring::npos ||
details.find(L"на складе недостаточно места") != std::wstring::npos) &&
details.find(L"доски ×3") != std::wstring::npos && details.find(L"блоки ×2") != std::wstring::npos,
"real returning resident did not expose actual cargo and waiting reason");
}
} // namespace production_controls
+192 -7
View File
@@ -87,16 +87,18 @@ 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) {
void flush_owner(ViewerSession& session, RuntimeOutcome expected = RuntimeOutcome::Completed) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
for (;;) {
auto sync = session.runtime().synchronize();
if (sync.admission == RuntimeAdmission::Busy) {
require(std::chrono::steady_clock::now() < deadline);
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);
require(sync.completion.wait_until(deadline) == std::future_status::ready);
require(sync.completion.get().outcome == expected);
return;
}
}
@@ -112,6 +114,11 @@ struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void
[[= 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();
[[= Void::Testing::tag("viewer-session")]] Test test_profiles_new_save_load_and_legacy_host_admission();
[[= Void::Testing::tag("viewer-session")]] Test test_profile_validation_rejects_initial_and_loaded_mismatches();
[[= Void::Testing::tag("viewer-session")]] Test test_pending_optional_load_blocks_host_and_newest_invalid_load_wins();
[[= Void::Testing::tag("viewer-session")]] Test test_historical_default_modes_and_guest_leave_keep_default_rules();
[[= Void::Testing::tag("viewer-session")]] Test test_legacy_host_requires_representable_published_custody();
};
Test ViewerSessionTests::test_commands_wait_for_commit_and_keep_rejected_drafts_retryable() {
@@ -355,10 +362,7 @@ Test ViewerSessionTests::test_fault_retains_view_and_explicit_load_recovers() {
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);
flush_owner(session, RuntimeOutcome::Faulted);
static_cast<void>(session.poll());
session.load(files.root / "recover.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
@@ -392,4 +396,185 @@ Test ViewerSessionTests::test_failed_guest_transitions_retain_received_replica()
require(rejected_leave && session.guest() && session.world() == received);
}
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 checkpoint_bytes(const WorldCheckpoint& candidate) {
return checked(encode_checkpoint(*candidate.world, candidate.world_id, candidate.city, candidate.rules));
}
Test ViewerSessionTests::test_profiles_new_save_load_and_legacy_host_admission() {
TempFiles files;
ViewerSession session(2);
for (const auto profile : {ColonyProfile::PlankBeds, ColonyProfile::Default}) {
const auto before = session.runtime().latest();
session.new_colony(profile);
require(session.changing_world() && !session.can_host_legacy());
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
const auto created = session.runtime().latest();
const auto expected = checked(colony_rules(profile));
require(created->identity.world != before->identity.world && created->identity.session != before->identity.session);
require(*created->rules == expected.manifest());
require(created->world->staged_beds() == (profile == ColonyProfile::Default));
require(session.can_host_legacy() == (profile == ColonyProfile::Default));
const auto path = files.root / "profile.settlement";
session.save(path);
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Saved); });
CheckpointFiles reader;
auto read = reader.try_load(path, 2);
require(read.admission == CheckpointLoadAdmission::Accepted);
require(read.completion.wait_for(5s) == std::future_status::ready);
const auto saved = checked(read.completion.get());
require(saved.rules == expected.manifest() && saved.world_id == created->identity.world);
require(bytes(*saved.world) == bytes(*created->world));
session.new_colony(profile == ColonyProfile::Default ? ColonyProfile::PlankBeds : ColonyProfile::Default);
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
session.load(path);
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(*session.runtime().latest()->rules == saved.rules);
require(session.runtime().latest()->identity.world == saved.world_id);
require(bytes(*session.world()) == bytes(*saved.world));
}
}
Test ViewerSessionTests::test_profile_validation_rejects_initial_and_loaded_mismatches() {
TempFiles files;
auto catalog = checked(builtin_rule_packages());
const auto optional_rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest();
const auto core_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.core"}}));
catalog.push_back(checked(load_rule_package("extra",
R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})")));
const auto extra_rules = checked(resolve_rules(catalog,
std::array{std::string{"settlement.colony"}, std::string{"game.extra"}}));
auto altered = std::string(catalog[1].canonical_json());
const auto recipe = altered.find("\"output_count\":1");
require(recipe != std::string::npos);
altered.replace(recipe, std::string_view{"\"output_count\":1"}.size(), "\"output_count\":2");
catalog[1] = checked(load_rule_package("forged", altered));
const auto forged_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.colony"}}));
ViewerSession session(2);
const auto before = session.runtime().latest();
for (const auto& rules : {core_rules, extra_rules, forged_rules, optional_rules}) {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
candidate.rules = rules;
write(files.root / "invalid.settlement", checkpoint_bytes(candidate));
bool rejected = false;
try { ViewerSession invalid(std::move(candidate), 2); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected);
session.load(files.root / "invalid.settlement");
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
require(!has(events, ViewerEventKind::Replaced));
require(session.runtime().latest() == before && !session.changing_world());
}
for (int problem = 0; problem < 3; ++problem) {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
if (problem == 0) candidate.world.reset();
if (problem == 1) candidate.world_id = {};
if (problem == 2) candidate.city = 0;
bool rejected = false;
try { ViewerSession invalid(std::move(candidate), 2); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected);
}
bool rejected = false;
try { session.new_colony(static_cast<ColonyProfile>(255)); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected && session.runtime().latest() == before && session.can_host_legacy());
auto supported = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
ViewerSession optional(std::move(supported), 2);
require(!optional.world()->staged_beds() && !optional.can_host_legacy());
}
Test ViewerSessionTests::test_pending_optional_load_blocks_host_and_newest_invalid_load_wins() {
TempFiles files;
auto valid = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
write(files.root / "optional.settlement", checkpoint_bytes(valid));
valid.world = make_first_colony(2);
write(files.root / "invalid.settlement", checkpoint_bytes(valid));
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();
require(session.can_host_legacy());
session.load(files.root / "optional.settlement");
gate->wait();
require(session.changing_world() && !session.can_host_legacy() && session.runtime().latest() == before);
// Invalid direct New preparation must retain the pending load and its ticket.
const auto generation = session.generation();
try { session.new_colony(static_cast<ColonyProfile>(255)); }
catch (const std::runtime_error&) {}
require(session.changing_world() && session.generation() == generation);
session.load(files.root / "invalid.settlement");
gate->release();
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
require(!has(events, ViewerEventKind::Replaced) && session.runtime().latest() == before);
flush_owner(session);
require(session.poll().empty() && session.runtime().latest() == before && session.can_host_legacy());
}
Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_default_rules() {
TempFiles files;
const auto defaults = checked(default_rules_manifest());
for (int mode = 0; mode < 3; ++mode) {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
if (mode == 1) candidate.world = make_first_colony(2, BedConstructionMode::Plank);
if (mode == 2) candidate.world = std::make_unique<World>(17, 32, 32, 2);
const auto expected = bytes(*candidate.world);
ViewerSession session(std::move(candidate), 2);
require(bytes(*session.world()) == expected && session.can_host_legacy() == (mode != 2));
write(files.root / "legacy.settlement", expected);
session.load(files.root / "legacy.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(bytes(*session.world()) == expected && *session.runtime().latest()->rules == defaults);
}
ViewerSession session(checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2)), 2);
session.enter_guest();
session.receive_guest(make_first_colony(2, BedConstructionMode::Plank));
session.leave_guest();
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(!session.world()->staged_beds() && *session.runtime().latest()->rules == defaults && session.can_host_legacy());
}
Test ViewerSessionTests::test_legacy_host_requires_representable_published_custody() {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
candidate.world = std::make_unique<World>(43, 32, 32, 2);
auto& world = *candidate.world;
const auto store = world.add_storage({3, 3}, 5);
world.stock_storage(store, ItemType::Plank, 3);
world.stock_storage(store, ItemType::StoneBlock, 2);
static_cast<void>(world.spawn_agent({1, 3}));
world.start_scenario({6, 6});
world.queue_production({14, 3}, RecipeId::BuildCabin);
for (int tick = 0; tick < 100 && world.agents().front().inventory.empty(); ++tick) world.step();
require(world.agents().front().inventory.item_count(ItemType::Plank) == 3 &&
world.agents().front().inventory.item_count(ItemType::StoneBlock) == 2);
world.stock_storage(store, ItemType::Wood, 5);
require(world.legacy_representable());
require(world.cancel_production(world.production_orders().front().id) == CommandStatus::Accepted);
require(!world.legacy_representable());
ViewerSession session(std::move(candidate), 2);
const auto published = session.runtime().latest();
require(!session.can_host_legacy() && session.can_submit());
require(session.world() == published->world && session.runtime().view().state == RuntimeState::Running);
TempFiles files;
session.save(files.root / "custody.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Saved); });
session.load(files.root / "custody.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(!session.can_host_legacy() && !session.world()->legacy_representable() && session.can_submit());
session.new_colony();
require(session.changing_world() && !session.can_host_legacy());
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(session.can_host_legacy());
}
} // namespace