diff --git a/app/lan_session.hpp b/app/lan_session.hpp index 96f5307..cfcc08b 100644 --- a/app/lan_session.hpp +++ b/app/lan_session.hpp @@ -53,7 +53,9 @@ public: // poll_guest pauses further sends until this one retained result is drained. [[nodiscard]] std::optional take_result() noexcept; [[nodiscard]] std::unique_ptr 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); diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index dab4ab7..ba5c55e 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -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 { @@ -300,13 +310,18 @@ struct LanSession::Impl { } } - 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 +336,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 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& 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 +399,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 +427,9 @@ struct LanSession::Impl { awaiting_receipt = action; } - template - void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) { + template + 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 +439,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,6 +454,8 @@ 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(); } @@ -536,7 +571,9 @@ std::unique_ptr 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 +586,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(connection.current_runtime_snapshot(runtime)); }, !connection.pending_command); } catch (const std::exception& error) { connection.notice = error.what(); connection.drop_peer(); @@ -573,7 +612,7 @@ std::unique_ptr 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(); diff --git a/app/viewer_session.cpp b/app/viewer_session.cpp index dd91714..85948de 100644 --- a/app/viewer_session.cpp +++ b/app/viewer_session.cpp @@ -76,7 +76,11 @@ bool ViewerSession::can_submit() const { bool ViewerSession::can_host_legacy() const { const auto current = runtime_.view(); return !guest_ && !changing_world_ && current.state == RuntimeState::Running && - current.snapshot->rules && *current.snapshot->rules == supported_rules_; + 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 ViewerSession::submit(SessionPayload payload) { diff --git a/docs/agent-workflow/tasks/S16-03.md b/docs/agent-workflow/tasks/S16-03.md new file mode 100644 index 0000000..9565969 --- /dev/null +++ b/docs/agent-workflow/tasks/S16-03.md @@ -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 --parallel 6, run ctest --test-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. diff --git a/docs/plan/systems/S16.md b/docs/plan/systems/S16.md index 6393cd1..1b21266 100644 --- a/docs/plan/systems/S16.md +++ b/docs/plan/systems/S16.md @@ -51,6 +51,12 @@ Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается. +Проверка представимости фактического имущества выполняется до приёма соединения, перед каждым разобранным сообщением и перед отправкой, включая продолжение ранее поставленного снимка или квитанции. `World::legacy_representable()` проверяет игровой контракт без пробной сериализации. Если отменённый груз или приостановленная площадка не имеют точного представления в формате 13, адаптер закрывает гостя и очищает его буферы. Слушатель, современный владелец и принятая им работа сохраняются; готовая квитанция прежнего подключения не отправляется следующему гостю. При работе с фоновым владельцем каждое сообщение и отправка сверяют свежую публикацию и инкарнацию. Прежний `poll(World&)` применяет ту же проверку представимости. + +Общий `ViewerSession::can_host_legacy()` разрешает создание слушателя только для опубликованной представимой активной колонии 32×32 с точными встроенными правилами, вне гостевого режима и смены партии. Это ограничение совместимости не блокирует современные команды и контрольные точки. Историческая активная колония с простым рецептом кровати и встроенным манифестом остаётся допустимой. [Контракт S16-03](../../agent-workflow/tasks/S16-03.md) + +Для этого адаптера повторно проверены публичный `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); новое универсальное сетевое средство не вводится. + Пять проверок `--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) diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index c7a078a..162cff5 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -48,6 +48,29 @@ WorldCheckpoint colony_checkpoint() { return {make_first_colony(2), *identity, 1, std::move(*rules)}; } +std::unique_ptr mixed_delivery() { + auto world = std::make_unique(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(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 void pump_until(Pump pump, Condition condition, const char* message) { const auto deadline = std::chrono::steady_clock::now() + 3s; @@ -115,8 +138,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 +187,8 @@ struct LanTests : Void::Testing::Suite { [[= 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(); }; Test LanTests::test_protocol_11_fixed_messages() { @@ -617,4 +643,80 @@ 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(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(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(Profession::Miner), + world->agents().front().id); + guest.poll(); + pump_until([&] { static_cast(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(host.poll(*compatible)); next.poll(); }; + pump_until(pump, [&] { return next.snapshot != nullptr; }, "Representable counterpart could not join."); + next.command(1, CommandKind::AssignProfession, {}, static_cast(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); +} + } // namespace diff --git a/tests/viewer_session_tests.cpp b/tests/viewer_session_tests.cpp index 6526a83..6ec7507 100644 --- a/tests/viewer_session_tests.cpp +++ b/tests/viewer_session_tests.cpp @@ -116,6 +116,7 @@ struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void [[= 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() { @@ -530,7 +531,7 @@ Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_defa if (mode == 2) candidate.world = std::make_unique(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()); + 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); }); @@ -544,4 +545,37 @@ Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_defa 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(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(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