diff --git a/CMakeLists.txt b/CMakeLists.txt index 185bbc4..3be310b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,6 +41,7 @@ find_package(Threads REQUIRED) add_library(settlement_core engine/src/checkpoint.cpp engine/src/checkpoint_files.cpp + engine/src/colony_profile.cpp engine/src/command_dispatcher.cpp engine/src/first_colony.cpp engine/src/rules_manifest.cpp @@ -117,6 +118,7 @@ if(BUILD_TESTING) tests/core_tests.cpp tests/executor_tests.cpp tests/identity_tests.cpp + tests/profile_tests.cpp tests/replay_tests.cpp tests/rules_tests.cpp tests/runtime_tests.cpp diff --git a/docs/agent-workflow/tasks/S19-02.md b/docs/agent-workflow/tasks/S19-02.md new file mode 100644 index 0000000..788d96e --- /dev/null +++ b/docs/agent-workflow/tasks/S19-02.md @@ -0,0 +1,48 @@ +# Compile a selectable plank-bed package into actual colony behavior + +Task ID: S19-02 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Exclusive s19 worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 60154bd. Prior S19 catalog/manifest reviewed, M01-P4 and F6 preflight approved both existing bed production paths. Current World::start_scenario sets staged_beds_=true unconditionally; legacy/restored worlds already execute nonstaged SawPlank + BuildBed. S18 initial UI work/other World changes in distinct checkouts. + +## 2. Objective and deliverables +Allow real selection between the existing default staged bed assembly and optional one-plank bed assembly at colony creation. Freeze compatible manifest/engine configuration and provide supported-profile validation at the application boundary for creation and loading. + +## 3. Scope and non-goals +S19 core package, game-profile compiler/factory, narrow World scenario initialization and runtime-neutral validation tests. No UI/transport changes in this slice. No change to generic resolver/decoder acceptance or Lua VM. Preserve all original package contents, default game output and original call signatures/behavior. + +## 4. Files to inspect +Inspect rules_manifest.{hpp,cpp}, first_colony.cpp, world.hpp/.cpp start_scenario/PlaceBed/PlaceRoom/recipes, world_save.cpp staged flag/state validation, checkpoint.hpp, actual tests/rules_tests, core_tests, legacy fixtures, prime S18 viewer_session.cpp constructor/load/host gates via sibling and plans S19/F6. Pin has resolver primitives used earlier, existing issue #4. Current default SawPlank executes 12 ticks; the old manifest's sample work_ticks=8 is not activated by this feature. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/colony_profile.hpp and engine/src/colony_profile.cpp (NEW); engine/src/rules_manifest.cpp; engine/include/settlement/core/world.hpp; engine/src/world.cpp (scenario initialization only); engine/src/first_colony.cpp; tests/rules_tests.cpp; tests/profile_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S19.md +Skip all UI and unrelated caller edits. S04 changes production identity in separate worktree. You are not alone; root integrates and handles simultaneous CMake/World edits. Never revert another worker, change Git or shared Serena. + +## 6. Implementation or investigation approach +Add additive optional built-in exact package settlement.plankbeds with an allowed recipe definition in its own namespace, stable dependency on settlement.colony and no conflicting exclusive construction capability. Interpret explicit typed data describing one plank/simple assembly to select the actually existing engine bed mode. Use resolver/checkpoint typed APIs, validate supported exact closure/digests and content before building a supported colony. Compute prechange default manifest canonical bytes/fingerprint using the verified baseline first, hardcode golden from it into regression (old two-package closure/content unchanged); do not recompute expected with candidate. New default=false option meaning must be clear by names. Expose concise NEW profile enum/options and a game-specific factory producing validated WorldCheckpoint (owned World, fresh stable nonnil UUID, city1, correct manifest), plus supported-profile validation taking World/manifest or candidate. Name signatures early so S18 follow-up can wire title. + +## 7. Interfaces and data contracts +Keep existing World::start_scenario(sawmill), make_first_colony(workers) staged by default; add explicit creation-only mode/profile parameter or overload, no mutable post-creation toggle. When active optional package selected, actual simple path: SawPlank + one BuildBed, one plank consumed; default already uses foundation wood/stone plus cloth twice. Furnished rooms must respect same rule. Existing schemas saved real mode; loaded exact default is allowed with EITHER persisted mode, inactive legacy worlds included (historical v1 or raw-format import). Do not alter their rules/mode at load. Optional exact profile requires active scenario staged=false where applicable; reject exact simple-manifest with active staged world. Unknown package/digest/config rejected by supported-profile gate; generic decode/runtime continue to handle caller-supplied catalogs independently. Reuse shared immutable definitions/lookup as suitable; avoid catalog-size assumptions and requiring every installed unrelated package. + +## 8. Dependencies and integration +Viewer later calls this public factory and canonical compatibility gate on BOTH initial and prepared worlds, and keeps immediate/deferred old LAN11 exact-default-only. Do not mix S18 UI edits on s19; communicate the trusted support check and whether a profile may host to root. New catalog optional must not automatically activate or alter existing default hashes. + +## 9. Edge cases security and performance +Exercise active/inactive imported historical worlds, current resaves, no silent toggle or package rewriting. Avoid claiming all base/ACE systems implemented. Use an actual complete bed production run under both options with relevant materials/outputs (incl furnished room), mature/paused snapshots persisted and continued. Preserve wire13/old baseline normal path. An altered content package using same ID/version must not pass compiled-profile support. + +## 10. Acceptance criteria +1. Old default known fingerprint/bytes and baseline gameplay preserved; selecting optional package changes material chain and completes bed with actual initial supply. 2. Compare modern canonical per tick across serial/2/6/12 for representative events; held view does not change; mid-carry save/load continues identically. 3. Exact optional mismatch, default historical raw/v1 active simple and inactive accepted without rewriting; catalog reordering and missing/changed/extra activated packages handled. 4. Correct real startup factory and no mutable rules switch. 5. All cross suites pass. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/profile-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Run wine /settlement_core_tests.exe --tag profile and tagged rules, full verbose CTest, git diff --check; source actual old baseline digest from already built branch or separate helper, log its hash. Provide exact logs profile-*. + +## 12. Constraints and stop conditions +No editing S18 UI, no broad changing existing recipes to fit sample data and no rewriting old manifests, formats or resources. Stop/escalate after two failed repairs of same issue or if actual optional mode cannot complete the scenario. No children/Git/remote mutations. + +## 13. Authorization and decisions +Plan explicitly requires new-world module selection. Existing bed behaviors were chosen as first reversible demonstration, preserving old defaults and P4/F6 restoration policy. User authorized commits, issues and PRs through root. + +## 14. Return format +Return S19-02 status, early exact creation/validation API, source derived default golden, observed actual bed/room/canonical and legacy compatibility, counts and residual native/UI risks. diff --git a/docs/plan/systems/S19.md b/docs/plan/systems/S19.md index 1f36517..b73ae68 100644 --- a/docs/plan/systems/S19.md +++ b/docs/plan/systems/S19.md @@ -10,6 +10,18 @@ На Windows x64 под Wine прошли 9 сценариев для манифестов. Разбор JSON, версии, граф и хеш использованы из закреплённой VoidLibrary. Для замены локального разрешения наборов библиотечным сервисом повторить проверки транзитивных зависимостей, перестановок, конфликтов и идентичности. [Запрос в Void/Library](https://git.faumaray.com/Void/Library/issues/4) +## Выбор исполняемого профиля колонии + +Первый выбор механики использует два существующих способа постройки кровати. Профиль по умолчанию собирает основание из дерева или камня, затем отдельно доставляет ткань для постели и подушки. Дополнительный пакет `settlement.plankbeds@1.0.0` задаёт простую кровать из одной доски. Для неё жители сначала выполняют распил за 12 рабочих тактов, затем собирают кровать за 14. Команды отдельной кровати и меблированной комнаты используют выбранный способ. [Профиль и создание колонии](../../../engine/include/settlement/core/colony_profile.hpp) · [Игровые проверки](../../../tests/profile_tests.cpp) + +Компилятор профиля проверяет точный состав, версии и SHA-256 реализованных пакетов, затем связывает проверенные поля определения рецепта с начальной конфигурацией мира. Фабрика возвращает мир вместе с его манифестом и постоянным UUID. Настройка выполняется при запуске сценария. Поля демонстрационного определения доски в исходном пакете сохраняют прежнее содержимое. Общее исполнение произвольных данных рецепта относится к S19-W02. + +Два исходных пакета и их канонический манифест закреплены проверкой с отпечатком `06d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1`, полученным из ядра до добавления профилей. Выбор по умолчанию включает эти два пакета. Дополнительный профиль разрешает их вместе с пакетом простых кроватей. + +Старое сохранение с исходным манифестом может содержать любой из двух способов постройки, включая неактивный сценарий. Проверка загрузки сохраняет этот способ и манифест. Для дополнительного пакета требуется сохранённый способ простых кроватей. Изменённый пакет, неизвестная комбинация или сочетание дополнительного пакета с поэтапной сборкой получает диагностический отказ до замены партии. Общие кодеки остаются доступными для каталогов вызывающего приложения. Прежний LAN11 допускает точный исходный манифест. Интерфейс выбора профиля подключается через S18. + +Семь случаев `--tag profile` прошли в Windows x64 под Wine. Оба профиля завершили цель с тремя кроватями и едой, проверены меблированная комната, материал в переноске, продолжение после загрузки и одинаковые контрольные точки на последовательном эталоне и 2/6/12 потоках. Сохранён подлинный файл схемы 1 с исходным манифестом и простой сборкой. Общая сборка прошла 113 тестов ядра и 4 LAN. Все 738 386 байтов прежней траектории совпали с исходной сборкой во всех четырёх режимах. Нативная Windows и подключение выбора в окно проверяются отдельно. + ## Исходное состояние Предметы, профессии, рецепты и команды прототипа определяются C++-типами, а стартовая партия создаётся кодом. В проверенной CMake-конфигурации подключены `Void::Binary`, `Void::Core` и `Void::Testing`. Скриптовый runtime в этот перечень не входит. План вводит новые определения контента и границу расширения. [Текущая конфигурация сборки](../../../CMakeLists.txt) @@ -28,6 +40,8 @@ Долговременное состояние обработчика представляет собой проверяемые сериализуемые значения с явной схемой. Продолжение события хранит идентификатор шага, данные и запланированный такт. Персистентные coroutine-стеки, нативные замыкания и произвольная память интерпретатора в формат сохранения не входят. Сам обработчик выполняется с фиксированным входом и возвращает предлагаемые изменения. +Состояние обработчика получает ключ пакета, обработчика и версии схемы. Продолжение имеет постоянный идентификатор, детерминированные данные и назначенный такт. Предложения связываются с исходной ревизией снимка и инкарнацией. Владелец проверяет их в устойчивом порядке и одной операцией применяет новое состояние, продвижение генератора случайности, расписание и игровые изменения. Отказ либо устаревшая инкарнация отбрасывают весь этот результат. Исполнение Lua вводится в S19-W03. + Игровой API задаёт детерминированный порядок коллекций, отдельные потоки случайных чисел и правила числовых значений. Авторитетные решения используют разрешённые целочисленные либо явно квантованные величины. Прикладное API запрещает неупорядоченную итерацию для последовательности игровых изменений. Время берётся из номера такта. Вызовы системы, сети, произвольных файлов и нативных расширений недоступны исполняемому игровому скрипту. Каждый обработчик ограничен по инструкциям, памяти, размеру результата и стоимости вызванных функций хоста. Счётчик Lua-инструкций дополняется ограничением работы C++-функций, поскольку эта работа выполняется вне счётчика интерпретатора. Состояние обработчика и предложения применяются атомарно. Ошибка отбрасывает его незавершённый результат и ставит авторитетное продвижение на безопасную границу с диагностикой. Состав правил мира сохраняется. [Стадии симуляции](S01.md) diff --git a/engine/include/settlement/core/colony_profile.hpp b/engine/include/settlement/core/colony_profile.hpp new file mode 100644 index 0000000..799bdf5 --- /dev/null +++ b/engine/include/settlement/core/colony_profile.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include "settlement/core/checkpoint.hpp" + +namespace settlement { + +enum class ColonyProfile { Default, PlankBeds }; + +// Constructed only after the selected packages match an implemented profile. +class ColonyRules { +public: + [[nodiscard]] ColonyProfile profile() const noexcept { return profile_; } + [[nodiscard]] BedConstructionMode bed_mode() const noexcept { return bed_mode_; } + [[nodiscard]] const RulesManifest& manifest() const noexcept { return manifest_; } + +private: + ColonyRules(ColonyProfile profile, BedConstructionMode beds, RulesManifest manifest); + ColonyProfile profile_; + BedConstructionMode bed_mode_; + RulesManifest manifest_; + friend std::expected compile_colony_rules(const RulesManifest&); +}; + +[[nodiscard]] std::expected compile_colony_rules(const RulesManifest&); +[[nodiscard]] std::expected colony_rules(ColonyProfile); + +// Initializes both the enacted mechanics and their frozen package identities. +[[nodiscard]] std::expected make_colony_checkpoint( + ColonyProfile profile, std::size_t workers = min_worker_count, + ExecutionMode mode = ExecutionMode::Parallel); + +// Default rules preserve historical saved bed modes, including inactive worlds. +// The optional plank-bed profile requires a saved nonstaged mode. This gate is +// game-specific; generic codecs and SimulationRuntime accept caller-owned catalogs. +[[nodiscard]] std::expected validate_colony_checkpoint( + const WorldCheckpoint&); + +} // namespace settlement diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index e59bd9e..48c8d48 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -105,6 +105,7 @@ enum class RecipeId : std::uint8_t { }; enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; +enum class BedConstructionMode : std::uint8_t { Staged, Plank }; constexpr RecipeId room_part_shape(RecipeId recipe) noexcept { if (recipe == RecipeId::InstallDoorAlongX) return RecipeId::BuildDoorAlongX; @@ -415,7 +416,7 @@ public: return scenario_sawmill_; } void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); - void start_scenario(GridPosition sawmill); + void start_scenario(GridPosition sawmill, BedConstructionMode beds = BedConstructionMode::Staged); [[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command); [[nodiscard]] std::uint64_t next_command_sequence(std::uint8_t player) const noexcept; [[nodiscard]] bool can_place_bed(GridPosition position) const noexcept; @@ -498,6 +499,8 @@ private: }; inline constexpr std::int32_t first_colony_map_size = 32; -[[nodiscard]] std::unique_ptr make_first_colony(std::size_t workers); +[[nodiscard]] std::unique_ptr make_first_colony( + std::size_t workers, BedConstructionMode beds = BedConstructionMode::Staged, + ExecutionMode mode = ExecutionMode::Parallel); } // namespace settlement diff --git a/engine/src/colony_profile.cpp b/engine/src/colony_profile.cpp new file mode 100644 index 0000000..63ead5d --- /dev/null +++ b/engine/src/colony_profile.cpp @@ -0,0 +1,134 @@ +#include "settlement/core/colony_profile.hpp" + +#include + +#include +#include +#include +#include + +namespace settlement { +namespace { + +RulesDiagnostic unsupported(std::string package, std::string message) { + return {std::move(package), "builtin/colony-profile", "profile", std::move(message), 0}; +} + +std::expected resolve_profile( + ColonyProfile profile, std::span catalog) { + if (profile != ColonyProfile::Default && profile != ColonyProfile::PlankBeds) { + return std::unexpected{unsupported({}, "Unknown colony profile.")}; + } + const std::array selected{std::string{profile == ColonyProfile::Default ? + "settlement.colony" : "settlement.plankbeds"}}; + return resolve_rules(catalog, selected); +} + +std::expected plank_bed_mode(const RulePackage& package) { + namespace json = Void::Json::Strict; + const auto definitions = package.definitions(); + if (definitions.size() != 1 || definitions.front().id != "settlement.plankbeds:bed" || + definitions.front().kind != "recipe") { + return std::unexpected{unsupported(package.identity().id, "Plank-bed recipe is missing.")}; + } + const auto parsed = json::parse(definitions.front().canonical_data, + {.maximumDepth = 4, .allowDecimals = false}); + const auto* fields = parsed ? std::get_if(&parsed->value) : nullptr; + if (!fields || fields->size() != 5) { + return std::unexpected{unsupported(package.identity().id, "Invalid plank-bed recipe data.")}; + } + const auto matches = [&](std::string_view key, const T& expected) { + const auto entry = fields->find(key); + if (entry == fields->end()) return false; + const auto* value = std::get_if(&entry->second.value); + return value && *value == expected; + }; + // This finite profile binds typed content to the already implemented recipe. + // General recipe-data execution is scheduled separately in S19-W02. + if (!matches("assembly", std::string{"plank"}) || + !matches("input", std::string{"settlement.colony:board"}) || + !matches("input_count", std::int64_t{1}) || + !matches("saw_work_ticks", std::int64_t{12}) || + !matches("work_ticks", std::int64_t{14})) { + return std::unexpected{unsupported(package.identity().id, "Plank-bed recipe is not implemented.")}; + } + return BedConstructionMode::Plank; +} + +CheckpointDiagnostic checkpoint_error(const RulesDiagnostic& error) { + return {CheckpointError::RulesMismatch, error.field, error.package, error.message}; +} + +} // namespace + +ColonyRules::ColonyRules(ColonyProfile profile, BedConstructionMode beds, RulesManifest manifest) + : profile_(profile), bed_mode_(beds), manifest_(std::move(manifest)) {} + +std::expected compile_colony_rules(const RulesManifest& manifest) { + const auto catalog = builtin_rule_packages(); + if (!catalog) return std::unexpected{catalog.error()}; + for (const auto& identity : manifest.packages()) { + const auto installed = std::find_if(catalog->begin(), catalog->end(), + [&](const auto& package) { return package.identity().id == identity.id; }); + if (installed == catalog->end() || installed->identity() != identity) { + return std::unexpected{unsupported(identity.id, "Package has no matching compiled colony implementation.")}; + } + } + const auto default_manifest = resolve_profile(ColonyProfile::Default, *catalog); + if (!default_manifest) return std::unexpected{default_manifest.error()}; + if (manifest == *default_manifest) { + return ColonyRules{ColonyProfile::Default, BedConstructionMode::Staged, manifest}; + } + const auto plank_manifest = resolve_profile(ColonyProfile::PlankBeds, *catalog); + if (!plank_manifest) return std::unexpected{plank_manifest.error()}; + if (manifest != *plank_manifest) { + return std::unexpected{unsupported({}, "Selected package closure is not an implemented colony profile.")}; + } + const auto package = std::find_if(catalog->begin(), catalog->end(), + [](const auto& entry) { return entry.identity().id == "settlement.plankbeds"; }); + const auto mode = plank_bed_mode(*package); + if (!mode) return std::unexpected{mode.error()}; + return ColonyRules{ColonyProfile::PlankBeds, *mode, manifest}; +} + +std::expected colony_rules(ColonyProfile profile) { + const auto catalog = builtin_rule_packages(); + if (!catalog) return std::unexpected{catalog.error()}; + const auto manifest = resolve_profile(profile, *catalog); + if (!manifest) return std::unexpected{manifest.error()}; + return compile_colony_rules(*manifest); +} + +std::expected make_colony_checkpoint( + ColonyProfile profile, std::size_t workers, ExecutionMode mode) { + const auto rules = colony_rules(profile); + if (!rules) return std::unexpected{checkpoint_error(rules.error())}; + const auto world_id = Void::Uuid::try_v4(); + if (!world_id) { + return std::unexpected{CheckpointDiagnostic{ + CheckpointError::ResourceFailure, "world_id", {}, "Could not create a world identity."}}; + } + try { + return WorldCheckpoint{make_first_colony(workers, rules->bed_mode(), mode), + *world_id, 1, rules->manifest()}; + } catch (const std::exception& error) { + return std::unexpected{CheckpointDiagnostic{ + CheckpointError::ResourceFailure, "world", {}, error.what()}}; + } +} + +std::expected validate_colony_checkpoint(const WorldCheckpoint& candidate) { + if (!candidate.world || candidate.world_id.is_nil() || candidate.city == 0) { + return std::unexpected{CheckpointDiagnostic{ + CheckpointError::InvalidIdentity, "world", {}, "A colony needs an owned world and nonzero identities."}}; + } + const auto rules = compile_colony_rules(candidate.rules); + if (!rules) return std::unexpected{checkpoint_error(rules.error())}; + if (rules->profile() == ColonyProfile::PlankBeds && candidate.world->staged_beds()) { + return std::unexpected{CheckpointDiagnostic{CheckpointError::RulesMismatch, "world.staged_beds", + "settlement.plankbeds", "Saved bed assembly does not match the selected plank-bed package."}}; + } + return {}; +} + +} // namespace settlement diff --git a/engine/src/first_colony.cpp b/engine/src/first_colony.cpp index aff7e37..40791dd 100644 --- a/engine/src/first_colony.cpp +++ b/engine/src/first_colony.cpp @@ -5,9 +5,9 @@ namespace settlement { -std::unique_ptr make_first_colony(std::size_t workers) { +std::unique_ptr make_first_colony(std::size_t workers, BedConstructionMode beds, ExecutionMode mode) { constexpr auto size = first_colony_map_size; - auto world = std::make_unique(2026, size, size, workers); + auto world = std::make_unique(2026, size, size, workers, mode); DeterministicRng terrain_rng(0x534554544C454D45ULL); for (int y = 2; y < size - 2; ++y) { for (int x = 2; x < size - 2; ++x) { @@ -28,7 +28,7 @@ std::unique_ptr make_first_colony(std::size_t workers) { for (const auto position : {GridPosition{13, 14}, {14, 12}, {18, 12}, {19, 14}}) { static_cast(world->add_resource_node(position, ItemType::Berries, 16)); } - world->start_scenario({15, 14}); + world->start_scenario({15, 14}, beds); return world; } diff --git a/engine/src/rules_manifest.cpp b/engine/src/rules_manifest.cpp index 5a91e44..04da3ab 100644 --- a/engine/src/rules_manifest.cpp +++ b/engine/src/rules_manifest.cpp @@ -386,7 +386,10 @@ std::expected, RulesDiagnostic> builtin_rule_packages() if (!first) return std::unexpected{first.error()}; auto second = load_rule_package("builtin/colony", colony); if (!second) return std::unexpected{second.error()}; - return std::vector{std::move(*first), std::move(*second)}; + constexpr std::string_view plankbeds = R"({"schema":1,"id":"settlement.plankbeds","version":"1.0.0","dependencies":[{"id":"settlement.colony","version":"1.0.0"}],"exclusive_capabilities":[],"definitions":[{"id":"settlement.plankbeds:bed","kind":"recipe","data":{"assembly":"plank","input":"settlement.colony:board","input_count":1,"saw_work_ticks":12,"work_ticks":14},"references":["settlement.colony:board"]}]})"; + auto third = load_rule_package("builtin/plankbeds", plankbeds); + if (!third) return std::unexpected{third.error()}; + return std::vector{std::move(*first), std::move(*second), std::move(*third)}; } std::expected default_rules_manifest() { diff --git a/engine/src/world.cpp b/engine/src/world.cpp index 2843d20..3391f2c 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -611,13 +611,14 @@ void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPositio queue_production(position, RecipeId::BuildCabin); } -void World::start_scenario(GridPosition sawmill) { - if (scenario_active_ || !can_place_cabin(sawmill)) { +void World::start_scenario(GridPosition sawmill, BedConstructionMode beds) { + if (scenario_active_ || !can_place_cabin(sawmill) || + (beds != BedConstructionMode::Staged && beds != BedConstructionMode::Plank)) { throw std::invalid_argument("scenario needs a free sawmill cell"); } enable_hunger(); scenario_active_ = true; - staged_beds_ = true; + staged_beds_ = beds == BedConstructionMode::Staged; scenario_sawmill_ = sawmill; for (auto& node : resource_nodes_) { if (node.type == ItemType::Berries) node.foraging_enabled = false; diff --git a/tests/profile_tests.cpp b/tests/profile_tests.cpp new file mode 100644 index 0000000..4f26a5c --- /dev/null +++ b/tests/profile_tests.cpp @@ -0,0 +1,285 @@ +#include "settlement/core/colony_profile.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace settlement; +using Void::Testing::Test; + +void require(bool condition, std::string_view message) { + if (!condition) throw std::runtime_error(std::string(message)); +} + +template +T checked(std::expected result) { + if (!result) throw std::runtime_error(result.error().message); + return std::move(*result); +} + +std::string saved(const World& world) { + std::ostringstream stream(std::ios::binary); + world.write_save(stream); + return std::move(stream).str(); +} + +std::string checkpoint(const World& world, const WorldCheckpoint& identity) { + return checked(encode_checkpoint(world, identity.world_id, identity.city, identity.rules)); +} + +void command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0, + GridPosition target = {}, AgentId resident = 0) { + const auto receipt = world.apply_command( + {1, world.next_command_sequence(1), kind, cell, value, target, resident}); + require(receipt.status == CommandStatus::Accepted, "profile command was rejected"); +} + +std::uint64_t stock(const World& world, ItemType item) { + std::uint64_t count = 0; + for (const auto& storage : world.storages()) count += storage.item_count(item); + for (const auto& agent : world.agents()) count += agent.inventory.item_count(item); + return count; +} + +void queue_three_beds(World& world) { + command(world, CommandKind::PlaceBed, {16, 18}); + command(world, CommandKind::PlaceBed, {17, 18}, 1); + command(world, CommandKind::PlaceBed, {18, 18}); + command(world, CommandKind::SetForaging, {14, 12}, 1); + command(world, CommandKind::SetForaging, {13, 14}, 1); +} + +std::size_t count_recipe(const World& world, RecipeId recipe) { + return static_cast(std::count_if( + world.production_orders().begin(), world.production_orders().end(), + [recipe](const auto& order) { return order.recipe == recipe; })); +} + +std::string from_hex(std::string_view hex) { + const auto digit = [](char value) { + return value <= '9' ? value - '0' : value - 'a' + 10; + }; + std::string bytes; + for (std::size_t i = 0; i < hex.size(); i += 2) { + bytes.push_back(static_cast(digit(hex[i]) * 16 + digit(hex[i + 1]))); + } + return bytes; +} + +// Produced by the pre-profile core and header at 60154bd, SHA-256 +// 8936352f8f8c939f866195bd434fe58c3bcf9ace49202c937c9cb2a026583d48. +// Checkpoint schema 1 holds an active default-manifest world with simple beds. +const std::string legacy_simple_checkpoint = from_hex( + "53544843484b505401000000b6000000b7000000000000000102030405064708890a0b0c0d0e0f10" + "0100000000000000000000000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72d" + "c0984cfc62cd83d1020000001100736574746c656d656e742e636f6c6f6e790500312e302e3008e1" + "8a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c0890f00736574746c656d65" + "6e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530d0000002f010000000000000500000005000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000010100000000" + "00000001000000000000000100000000000000010000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000100000002000000" + "0200000000000000000000000000000000000000000000000000000000ada3be851474c1ab6aa6bb" + "0efc1a3cc103430f5b1a69fd602ec6bf02b93f98c6"); + +struct [[= Void::Testing::name("ProfileTests")]] ProfileTests : Void::Testing::Suite { + [[= Void::Testing::tag("profile")]] Test test_compiled_profiles_resolve_exact_content(); + [[= Void::Testing::tag("profile")]] Test test_both_first_colonies_complete_with_the_selected_material_chain(); + [[= Void::Testing::tag("profile")]] Test test_furnished_rooms_use_the_selected_bed_recipe(); + [[= Void::Testing::tag("profile")]] Test test_profiles_replay_and_resume_mid_delivery(); + [[= Void::Testing::tag("profile")]] Test test_historical_default_simple_and_inactive_worlds_keep_their_mode(); + [[= Void::Testing::tag("profile")]] Test test_supported_profile_gate_rejects_mismatches_without_mutation(); + [[= Void::Testing::tag("profile")]] Test test_scenario_profile_cannot_change_after_start(); +}; + +Test ProfileTests::test_compiled_profiles_resolve_exact_content() { + const auto original = checked(colony_rules(ColonyProfile::Default)); + const auto planks = checked(colony_rules(ColonyProfile::PlankBeds)); + require(original.manifest() == checked(default_rules_manifest()) && + original.bed_mode() == BedConstructionMode::Staged, "default compilation changed"); + require(planks.manifest().packages().size() == 3 && planks.bed_mode() == BedConstructionMode::Plank, + "optional package did not select plank construction"); + auto catalog = checked(builtin_rule_packages()); + std::reverse(catalog.begin(), catalog.end()); + const std::array selected{std::string{"settlement.plankbeds"}}; + const auto shuffled = checked(resolve_rules(catalog, selected)); + require(shuffled == planks.manifest() && + checked(compile_colony_rules(shuffled)).profile() == ColonyProfile::PlankBeds, + "catalog order changed the compiled profile"); + require(!colony_rules(static_cast(255)), "unknown profile compiled"); + require(!make_colony_checkpoint(ColonyProfile::Default, 1), + "parallel one-worker colony was created"); +} + +Test ProfileTests::test_both_first_colonies_complete_with_the_selected_material_chain() { + for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) { + auto candidate = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference)); + require(!candidate.world_id.is_nil() && candidate.city == 1, "colony identity is missing"); + require(validate_colony_checkpoint(candidate).has_value(), "new colony profile failed validation"); + auto& world = *candidate.world; + queue_three_beds(world); + const bool staged = profile == ColonyProfile::Default; + require(world.staged_beds() == staged && + count_recipe(world, RecipeId::SawPlank) == (staged ? 0U : 3U), + "bed command ignored its selected recipe"); + for (const auto& order : world.production_orders()) { + if (order.recipe != RecipeId::BuildBed) continue; + require(order.bed_material() == (staged ? + (order.bed_base == BedBase::Stone ? ItemType::Stone : ItemType::Wood) : ItemType::Plank), + "material preview does not match the enacted profile"); + } + for (int tick = 0; tick < 1200 && !world.scenario_progress().completed; ++tick) world.step(); + require(world.scenario_progress().completed && world.scenario_progress().assigned_beds == 3, + "selected first-colony profile did not complete the three-bed food objective"); + require(stock(world, ItemType::Cloth) == (staged ? 6U : 12U) && + stock(world, ItemType::Stone) == (staged ? 5U : 6U), + "bed profile consumed the wrong cloth or foundation material"); + require(std::all_of(world.production_orders().begin(), world.production_orders().end(), + [](const auto& order) { return order.state == JobState::Completed; }), + "selected profile left an unfinished prerequisite"); + } +} + +Test ProfileTests::test_furnished_rooms_use_the_selected_bed_recipe() { + for (auto mode : {BedConstructionMode::Staged, BedConstructionMode::Plank}) { + World world(64, 20, 18, 1, ExecutionMode::SerialReference); + const auto builder = world.spawn_agent({5, 3}); + const auto carpenter = world.spawn_agent({3, 3}); + const auto materials = world.add_storage({3, 4}, 128); + world.stock_storage(materials, ItemType::Wood, 80); + world.stock_storage(materials, ItemType::Stone, 6); + world.stock_storage(materials, ItemType::Cloth, 2); + const auto food = world.add_storage({2, 4}, 200, StorageKind::Pantry); + world.stock_storage(food, ItemType::Berries, 200); + world.start_scenario({4, 3}, mode); + command(world, CommandKind::AssignProfession, {}, static_cast(Profession::Builder), {}, builder); + command(world, CommandKind::AssignProfession, {}, static_cast(Profession::Carpenter), {}, carpenter); + const RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, RoomTemplate::Miner}; + command(world, CommandKind::PlaceRoom, plan.first, plan.placement_value(), plan.last); + require(count_recipe(world, RecipeId::SawPlank) == (mode == BedConstructionMode::Plank ? 1U : 0U), + "furnished room ignored the optional plank prerequisite"); + for (int tick = 0; tick < 2200 && world.scenario_progress().assigned_beds == 0; ++tick) world.step(); + require(world.scenario_progress().assigned_beds == 1, "room bed did not complete"); + require(stock(world, ItemType::Cloth) == (mode == BedConstructionMode::Plank ? 2U : 0U), + "furnished room consumed the wrong bedding"); + } +} + +Test ProfileTests::test_profiles_replay_and_resume_mid_delivery() { + const auto catalog = checked(builtin_rule_packages()); + for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) { + auto initial = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference)); + queue_three_beds(*initial.world); + const auto initial_bytes = checkpoint(*initial.world, initial); + std::vector runs; + for (std::size_t workers : {2U, 6U, 12U}) { + runs.push_back(checked(decode_checkpoint(initial_bytes, catalog, workers))); + } + std::shared_ptr held; + std::string held_bytes; + bool resumed = false; + for (int tick = 0; tick < 500; ++tick) { + initial.world->step(); + for (auto& run : runs) run.world->step(); + const auto expected = checkpoint(*initial.world, initial); + for (const auto& run : runs) { + require(checkpoint(*run.world, run) == expected, "profile parallel replay diverged"); + } + if (!resumed && std::any_of(initial.world->agents().begin(), initial.world->agents().end(), + [](const auto& agent) { + return agent.state == AgentState::Hauling && + (agent.inventory.item_count(ItemType::Wood) != 0 || + agent.inventory.item_count(ItemType::Stone) != 0 || + agent.inventory.item_count(ItemType::Plank) != 0 || + agent.inventory.item_count(ItemType::Cloth) != 0); + })) { + held = initial.world->capture(); + held_bytes = saved(*held); + runs.push_back(checked(decode_checkpoint(expected, catalog, 1, ExecutionMode::SerialReference))); + resumed = true; + } + } + require(resumed && saved(*held) == held_bytes, "held material snapshot changed or was never captured"); + require(initial.world->scenario_progress().assigned_beds == 3, "replay profile failed its bed objective"); + } +} + +Test ProfileTests::test_historical_default_simple_and_inactive_worlds_keep_their_mode() { + const auto catalog = checked(builtin_rule_packages()); + auto legacy = checked(decode_checkpoint(legacy_simple_checkpoint, catalog, 1, ExecutionMode::SerialReference)); + require(legacy.world->scenario_active() && !legacy.world->staged_beds(), + "authentic schema-1 fixture lost its historical mode"); + const auto before = saved(*legacy.world); + require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == before, + "default profile gate rewrote a historical simple colony"); + auto current = checked(decode_checkpoint(checkpoint(*legacy.world, legacy), catalog, 1, ExecutionMode::SerialReference)); + require(validate_colony_checkpoint(current).has_value() && saved(*current.world) == before, + "resaving historical defaults changed their enacted rules"); + // The corresponding v2 raw format omitted the staged flag and used an FNV footer. + auto raw_v2 = before; + raw_v2[8] = 2; + raw_v2.pop_back(); + auto digest = Void::Hash::fnv1a64_offset_basis; + digest = Void::Hash::fnv1a64_update(digest, std::as_bytes(std::span{raw_v2})); + for (unsigned shift = 0; shift < 64; shift += 8) raw_v2.push_back(static_cast(digest >> shift)); + std::istringstream input(raw_v2, std::ios::binary); + legacy.world = World::read_save(input, 1, ExecutionMode::SerialReference); + require(legacy.world->scenario_active() && !legacy.world->staged_beds() && + validate_colony_checkpoint(legacy).has_value(), "active raw-v2 import lost default compatibility"); + legacy.world = std::make_unique(17, 5, 5, 1, ExecutionMode::SerialReference); + const auto inactive_before = saved(*legacy.world); + require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == inactive_before, + "inactive historical default was rejected or modified"); +} + +Test ProfileTests::test_supported_profile_gate_rejects_mismatches_without_mutation() { + auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 1, ExecutionMode::SerialReference)); + const auto before = saved(*candidate.world); + candidate.rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest(); + auto invalid = validate_colony_checkpoint(candidate); + require(!invalid && invalid.error().package == "settlement.plankbeds" && + saved(*candidate.world) == before, "staged world with plank rules was accepted or changed"); + auto catalog = checked(builtin_rule_packages()); + auto altered = std::string(catalog.back().canonical_json()); + const auto work = altered.find("\"work_ticks\":14"); + require(work != std::string::npos, "plank fixture has no work duration"); + altered.replace(work, std::string_view{"\"work_ticks\":14"}.size(), "\"work_ticks\":15"); + catalog.back() = checked(load_rule_package("altered/plankbeds", altered)); + const std::array selected{std::string{"settlement.plankbeds"}}; + candidate.rules = checked(resolve_rules(catalog, selected)); + require(!validate_colony_checkpoint(candidate) && saved(*candidate.world) == before, + "modified recipe content was accepted as an implemented profile"); + const std::array core_only{std::string{"settlement.core"}}; + require(!compile_colony_rules(checked(resolve_rules(catalog, core_only))), "incomplete profile compiled"); + const auto extra = checked(load_rule_package("extra", + R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})")); + catalog.push_back(extra); + const std::array with_extra{std::string{"settlement.colony"}, std::string{"game.extra"}}; + require(!compile_colony_rules(checked(resolve_rules(catalog, with_extra))), "unimplemented package compiled"); + require(!resolve_rules(catalog, std::array{std::string{"missing.package"}}), "missing package resolved"); +} + +Test ProfileTests::test_scenario_profile_cannot_change_after_start() { + World world(17, 5, 5, 1, ExecutionMode::SerialReference); + const auto before = saved(world); + Void::Testing::expect_throw([&] { + world.start_scenario({2, 2}, static_cast(255)); + }); + require(saved(world) == before, "invalid mode changed the world"); + world.start_scenario({2, 2}, BedConstructionMode::Plank); + const auto started = saved(world); + Void::Testing::expect_throw([&] { world.start_scenario({2, 2}); }); + require(saved(world) == started, "started colony changed its creation profile"); +} + +} // namespace diff --git a/tests/rules_tests.cpp b/tests/rules_tests.cpp index 6dc33c3..6f50ce6 100644 --- a/tests/rules_tests.cpp +++ b/tests/rules_tests.cpp @@ -218,6 +218,13 @@ Test RulesTests::test_builtin_default_and_known_digest() { const auto first = checked(default_rules_manifest()); const auto second = checked(default_rules_manifest()); require(first == second && first.packages().size() == 2, "default rules were not reproducible"); + // Recorded by profile-baseline.exe against the compiled pre-profile core. + require(rules_digest_hex(first.fingerprint()) == + "06d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1", + "default profile fingerprint changed"); + require(first.canonical_json() == + R"({"packages":[{"id":"settlement.colony","sha256":"08e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089","version":"1.0.0"},{"id":"settlement.core","sha256":"61b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab7124188d337f","version":"1.0.0"}],"schema":1})", + "default canonical manifest changed"); const auto empty = load(package("game.core")); require(rules_digest_hex(empty.identity().content_sha256) == "f6d1f704ccbb3ec707d2e1ba7b0db27dab8494b7787eeee10f1449dabee1477a", "package SHA-256 differs from the canonical-byte known vector"); require(empty.definitions().empty(), "empty package gained a definition");