Compare commits

...
Author SHA1 Message Date
faumaray 275956395d Compile selectable colony rules into real bed construction recipes 2026-12-02 22:28:05 +03:00
faumaray 60154bd5f0 Track verified file loading and persistent logistics references 2026-12-02 22:09:36 +03:00
faumaray 4ba64f7e62 Integrate bounded checkpoint reads with stable logistics identities 2026-12-02 22:05:11 +03:00
faumaray a063894637 Prepare bounded checkpoint reads and immutable saves off the client thread 2026-12-02 22:04:58 +03:00
faumaray c2d9d8d51a Integrate persistent logistics references with the simulation owner 2026-12-02 22:02:47 +03:00
faumaray 8260e09be7 Keep logistics targets stable through storage and resource removal 2026-12-02 22:02:29 +03:00
faumaray 512c9ef033 Record fixed-clock verification and client integration boundaries 2026-12-02 21:55:49 +03:00
faumaray 8c4c1fe235 Integrate the single-owner clock, publications and recovery 2026-12-02 21:52:31 +03:00
faumaray 7979fff16c Advance the authoritative world on a fixed background clock 2026-12-02 21:52:31 +03:00
faumaray a4cf99c265 Track durable identity and quantity reservation gaps in VoidLibrary 2026-12-02 21:47:12 +03:00
faumaray ce3a7dc937 Record M01 system verification, upstream issues and review branches 2026-12-02 21:43:34 +03:00
faumaray 2224299589 Integrate validated world checkpoints into M01 2026-12-02 21:38:31 +03:00
faumaray db4ac304b8 Combine rule-aware checkpoints with background save publication 2026-12-02 21:38:14 +03:00
faumaray 15da3f4336 Validate versioned world checkpoints against installed rule packages 2026-12-02 21:37:26 +03:00
faumaray 1fa37d8e87 Integrate background save publication into M01 2026-12-02 21:37:20 +03:00
faumaray 4921dffe71 Integrate immutable world snapshots into M01 2026-12-02 21:37:00 +03:00
faumaray 645abefac5 Integrate session-scoped command dispatch into M01 2026-12-02 21:36:51 +03:00
faumaray fd17a2f3ff Capture complete immutable world views at simulation boundaries 2026-12-02 21:36:31 +03:00
faumaray 3844ebb205 Publish queued Windows saves through atomic same-directory replacement 2026-12-02 21:35:49 +03:00
faumaray 84a78eff8a Fence commands by session and retain authoritative outcomes 2026-12-02 21:35:43 +03:00
faumaray cf0cc2f32c Integrate the Void executor and rule manifests into M01 2026-12-02 21:31:51 +03:00
faumaray 68f91a236a Run deterministic world stages on the bounded Void executor 2026-12-02 21:27:32 +03:00
faumaray de38aff2ff Resolve and fingerprint versioned game rule packages 2026-12-02 21:20:21 +03:00
faumaray 8d2870a6f8 Add the M01 serial simulation reference and per-tick replay 2026-12-02 21:03:50 +03:00
faumaray 904bdf8827 Record the M00 behavior inventory and demo provenance 2026-12-02 20:54:18 +03:00
88 changed files with 8537 additions and 288 deletions

No files matched your search

+27 -5
View File
@@ -23,7 +23,8 @@ function(add_void_library)
set(BUILD_SHARED_LIBS OFF)
set(VOID_ENABLE_TESTING OFF)
set(VOID_ENABLE_BENCHMARKS OFF)
set(VOID_ENABLED_MODULES Binary Core)
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Math Text Time)
set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON)
if(BUILD_TESTING)
list(APPEND VOID_ENABLED_MODULES Testing)
endif()
@@ -38,7 +39,14 @@ endif()
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
engine/src/save_service_win32.cpp
engine/src/simulation_runtime.cpp
engine/src/worker_pool.cpp
engine/src/world.cpp
engine/src/world_save.cpp
@@ -49,10 +57,10 @@ target_include_directories(settlement_core
${CMAKE_CURRENT_SOURCE_DIR}/engine/include
)
target_compile_features(settlement_core PUBLIC cxx_std_20)
target_compile_features(settlement_core PUBLIC cxx_std_23)
target_link_libraries(settlement_core
PUBLIC Threads::Threads
PRIVATE Void::Binary Void::Core
PUBLIC Threads::Threads Void::Async Void::Core Void::Time
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Math Void::Text
)
if(MSVC)
@@ -104,7 +112,21 @@ else()
endif()
if(BUILD_TESTING)
add_executable(settlement_core_tests tests/core_tests.cpp tests/test_main.cpp)
add_executable(settlement_core_tests
tests/checkpoint_tests.cpp
tests/checkpoint_file_tests.cpp
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
tests/save_service_tests.cpp
tests/session_tests.cpp
tests/snapshot_tests.cpp
tests/test_main.cpp
)
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
add_test(NAME settlement_core_tests COMMAND settlement_core_tests)
+2
View File
@@ -24,6 +24,8 @@
## План этапов
Результаты первого этапа доступны в [сверке базовых выпусков](docs/plan/base-evidence.md), [сверке ACE](docs/plan/ace-evidence.md), [ведомости материалов](docs/art/demo-inventory.md) и [передаче исходной сборки и контрольной сцены](docs/plan/prototype-handoff.md).
Номер задаёт порядок демонстрации. Планы систем развиваются через несколько этапов. Например, M03 реализует доставку для одного дома, M04 расширяет её до устойчивой экономики, M08 проверяет отправку груза в другой регион.
| Этап | Зависит от | Что должно получиться |
+2
View File
@@ -67,6 +67,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 -VoidLibrary
Void Library требует поддержки C++26. Тесты ядра и LAN используют рефлексию C++26. `Void::Testing::Suite<T>` регистрирует методы без аргументов с возвращаемым типом `Void::Testing::Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры без тестов задайте `-DBUILD_TESTING=OFF` при прямом вызове CMake.
Потактную проверку симуляции можно запустить командой `build\settlement_core_tests.exe --tag replay`. Она сравнивает последовательную партию с исполнением на 2, 6 и 12 рабочих потоках и с продолжением из сохранения. [Сценарий M01](docs/plan/milestones/M01.md)
## Структура
```text
+2 -3
View File
@@ -1884,9 +1884,8 @@ std::wstring resident_details() {
text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" :
L" Везёт материалы в мастерскую";
}
else if (resident->resource_node_index != settlement::no_entity_index &&
resident->storage_index == settlement::no_entity_index) {
const auto& site = world->resource_nodes()[resident->resource_node_index];
else if (resident->resource_node_id != 0 && resident->storage_id == 0) {
const auto& site = *world->find_resource_node(resident->resource_node_id);
const bool trees = site.site == settlement::ResourceSite::TreePlot;
if (resident->state == settlement::AgentState::Travelling) {
text += trees ? L" Идёт на посадку деревьев" : L" Идёт засевать поле";
+44
View File
@@ -43,3 +43,47 @@ ctest --test-dir "$SETTLEMENT_VERIFY/candidate" -V --output-on-failure
Повторная проверка исходной сборки выполнялась командами `cmake --build /tmp/stoneheart-plan-check.m7eQkO --parallel 8` и `ctest --test-dir /tmp/stoneheart-plan-check.m7eQkO --output-on-failure` в подготовленном окружении Windows x64 GCC 16.2.0/Wine. Сборка актуальна. Обе CTest-сюиты прошли, журнал содержит 28 успешных случаев ядра и 4 LAN. Изменения игровых исходников, CMake и тестов относительно `083b84e` отсутствуют.
Независимая проверка RM07 завершена с результатом **READY** для комплекта планов. Уточнены единый владелец резервов S04 при торговле и лечении, приёмка повторно используемого шаблона B22 на M10, перенос основателей B13 на M06, граница ранних правок чертежа и переход от локальной транзакционной загрузки к сетевой. Проверяющий повторно сверил исправленные места и ключевые выводы о VoidLibrary с исходниками закреплённой версии. Следующий этап игры — M00 и затем проверяемый перенос первого участка исполнения на M01.
## M00. Первый проход по выпускам и передача ядру
2 декабря 2026 года пользователь поручил начать реализацию согласованного плана с участием субагентов и отдельной веткой на этап. База — `chore/plans` на `0deacb3`, ветка инвентаризации — `milestone/m00-inventory`. Следующая ветка создаётся от локального коммита этой работы. Прежние неотслеживаемые `.serena/`, `TASKS.md` и старые задания V/RM не входят в коммит.
| Работа | Ответственный и результат |
|---|---|
| [План](tasks/M00-P.md) и [предварительная проверка](tasks/M00-F.md) | Планировщик и независимый проверяющий согласовали границы инвентаря и первый исполняемый тест M01. |
| [Базовая игра](tasks/M00-B.md) и [дополнение](tasks/M00-A.md) | Два исполнителя проследили 50 исходных записей до версии и источника либо конкретного пробела и добавили 30 самостоятельных проверок. В документах указаны просмотренные выпуски и ещё открытые диапазоны. [Реестр](../plan/parity.md) |
| [Материалы](tasks/M00-D.md) | Подготовлено производственное задание M03. Для трёх уже встроенных иконок подтверждение прав остаётся открытым. [Реестр материалов](../art/demo-inventory.md) |
| [Исследование Void](tasks/M01-R.md) | Сверены публичные контракты текущего pin и ветки main. Для эталона используются существующие игровые расчёты и байты сохранения. Испытания замены пула вынесены в отдельную часть M01. [Решение](../plan/void-library.md) |
| Исходная проверка и сцена | Зафиксированы состав старой сборки, путь открытия сохранений 13, условия прежних измерений, карта Q-HOME и три точки прерывания доставки. [Передача](../plan/prototype-handoff.md) |
Из корня игры собрана свежая Windows x64 Release в отдельном каталоге с закреплённым исходным деревом Void, CMake 4.5.0, GCC 16.2.0 и Ninja. Команды `cmake --build <build-dir> --parallel 8` и `ctest --test-dir <build-dir> -V --output-on-failure` под Wine 11 дали 28/28 случаев ядра и 4/4 LAN. Результат относится к кросс-сборке. Аппаратные измерения Windows и изготовление материалов относятся к следующим этапам.
[Итоговая проверка M00-V](tasks/M00-V.md) приняла этот срез и передачу M01. Проверены 80 идентификаторов, 43 документа и 1 041 локальная ссылка до добавления данной записи, хеши иконок, подключение ресурсов и журналы исходной сборки. Обход остальных исторических изменений, приёмка игровых сценариев и права на будущие файлы остаются открытыми.
## M01. Последовательный эталон и журнал
Пользователь подтвердил полный план, локальные коммиты и отправку веток этапов и систем в origin. M00 принят и опубликован в `milestone/m00-inventory` на `904bdf8`. Ветка `milestone/m01-authoritative-simulation` создана от него. Первая поставка S01 включает [режим мира](tasks/M01-C.md) и [пять сценариев воспроизведения](tasks/M01-T.md).
Под Wine 11 новая Windows x64 Release прошла 33/33 теста ядра и 4/4 LAN. Селектор `settlement_core_tests.exe --tag replay` выполнил пять новых случаев. Журнал из десяти команд дал 750 тактов с одинаковыми сохранениями в эталоне и на 2/6/12 потоках, включая продолжение с материалом в руках. Отдельная программа, собранная сначала с заголовками и ядром до M01, затем с новым ядром, сравнила квитанции и сохранения после каждой из 365 попыток шага. При 361 такте и пяти съеденных порциях все четыре режима совпали с прототипом по всем 738 386 байтам. [Итог M01-V1](tasks/M01-V1.md) — **READY** для эталона и тестов.
Контрольные команды из корня игры, в окружении кросс-сборки из записи выше:
```sh
cmake --build /tmp/stoneheart-milestones.xprJ2SVp/windows --parallel 8
ctest --test-dir /tmp/stoneheart-milestones.xprJ2SVp/windows -V --output-on-failure
wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag replay
```
Далее в M01 входят исполнитель Void с проверкой отказов, манифесты правил, авторитетный диспетчер команд, фоновый такт, снимки и транзакционная загрузка/запись. Приёмка этих систем ведётся отдельными коммитами.
### Ветки разработки и запросы на слияние
Для этапов используются ветки `milestone/*`, для систем — `system/*`. По поручению пользователя ветка [integration/roadmap](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/src/branch/integration/roadmap) содержит `chore/integrate-void-library`, `chore/plans` и принятые изменения каждой ветки этапа и системы. После проверки совместной сборки ответственный обновляет накопительную ветку. Она служит для получения всей работы одним checkout.
У каждой опубликованной рабочей ветки есть свой запрос в `main`. Описание ссылается на более ранние запросы этой серии. При параллельной работе подписи ссылок указывают, какие изменения послужили базой и какие развивались независимо. Новые коммиты ветки попадают в уже открытый запрос. Первыми открыты [VoidLibrary #3](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/3), [план #4](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/4), [M00 #5](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/5), [M01 #6](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/6), [модули правил S19 #7](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/7), [исполнитель S01 #8](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/8), [диспетчер S16 #9](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) и [сохранения S15 #10](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/10).
В `2224299` вместе собраны снимки мира, диспетчер команд, служба записи и кодек контрольных точек. Windows x64 Release под Wine прошла 82 из 82 случаев ядра и 4 из 4 LAN. Отдельная ветка S15 на `db4ac30` прошла 59 из 59 и 4 из 4 соответственно. По трём прогонам на поле 80×80 с шестью потоками медианы p50/p95 захвата снимка составили 2/4 мкс для 50 жителей и 23/68 мкс для 500. После 32 тактов прогрева каждый прогон измерял 240 захватов. При подключении службы записи к окну лимит одного файла должен вмещать `max_checkpoint_bytes`. Частота тактов, отзывчивость окна во время записи и работа на физической Windows проверяются отдельно. [Проверка команд и записи](tasks/M01-V4.md) · [Проверка снимка и контрольной точки](tasks/M01-V5.md) · [Совместная сборка](tasks/M01-V6.md) · [План постоянных ссылок](tasks/M01-P3.md)
В `cf0cc2f` объединены проверенные коммиты S19 `de38aff` и S01 `68f91a2`. После объединения под Wine 11 прошли 51 из 51 теста ядра и 4 из 4 тестов LAN, включая формат сохранений 13 и протокол 11. Независимый проверяющий сверил обе родительские версии, наследование параметров компиляции и встроенную реализацию SHA-256. [План владельца симуляции](tasks/M01-P2.md) · [Проверка библиотеки](tasks/M01-R2.md) · [Разбор отказов](tasks/M01-F2.md) · [Принятые контракты](tasks/M01-F3.md) · [Проверка S01 и S19](tasks/M01-V2.md) · [Проверка интеграции](tasks/M01-V3.md)
Срез S06 сохранил ссылки на склады и источники при удалении более раннего элемента. Два контрольных набора из 738 386 и 393 857 байтов совпали со старой сборкой в последовательном режиме и на 2/6/12 потоках. Второй набор включает разбор склада во время многоэтапной доставки. Изменения опубликованы отдельно в [S06 #11](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11). В `4ba64f7` также вошла фоновая подготовка старых и новых сохранений. В объединённой Windows x64-сборке под Wine прошли 106 тестов ядра и 4 LAN. Публичный аналог ограниченного чтения в Windows отслеживается в [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). [Проверка двух компонентов](tasks/M01-V8.md) · [Интеграционная проверка](tasks/M01-V9.md)
+48
View File
@@ -0,0 +1,48 @@
# Record ACE releases, active variants and open evidence
Task ID: M00-A
Role: sol_implementer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m00-inventory at 0deacb3. Prior untracked .serena and workflow/TASKS and older tasks belong to the user. M00-P and preflight approve the scoped inventory.
## 2. Objective and deliverables
Produce the actual M00 public-behavior audit for ACE through 0.9.6.22 in NEW docs/plan/ace-evidence.md (Russian).
## 3. Scope and non-goals
Cover the 26 existing ACE observations and add distinct concrete observations from inspected earlier releases/patches. Base-game and art work have other owners.
## 4. Files to inspect
Inspect docs/plan/parity.md (A01–A26 and [ace],[quality],[drink],[market],[latest]), M00.md, PLAN.md and matching system/milestone plans. Read ACE maintainers' public release notes up to the cutoff.
## 5. Write ownership and coordination
Write scope: docs/plan/ace-evidence.md
Shared checkout. Do not revert or edit others' work. Root links your file and integrates the indexes.
## 6. Implementation or investigation approach
Walk dated release posts from earlier installments through the actual .22 release with stable post-specific URLs. Track coverage, last inspected release, supersessions and concrete remaining questions. Audit A01–A26 individually or group only where source/version and status apply to every named member. Add worthwhile A27+ rules including interaction of seasonal irrigation/markets/occupations or distinct peaceful/hostile outcomes as supported. Verify exact release within a topic rather than attributing every post to its current title.
## 7. Interfaces and data contracts
For each new ID use a durable lowercase HTML anchor, module, version/source, trigger, player effect, independent equivalent/test and existing Sxx/Mxx links. Retain AT convention. Clearly distinguish unknown/outcome questions and required future acceptance checks.
## 8. Dependencies and integration
Root owns parity.md and M00 crosslinks. Base author owns Bxx. Report substantive corrections required to existing seed descriptions to root.
## 9. Edge cases security and performance
Unexamined ranges remain explicit. No claim of full patch coverage unless checked. Use primary public behavior descriptions only, no code, art, recipe text, credentials, uploads or unsupported rights statements.
## 10. Acceptance criteria
1. All 26 seeds map to explicit inspected evidence or concrete unknown. 2. Distinct testable new rows have stable IDs and linked evidence. 3. Honest chronological coverage including superseding fixes.
## 11. Verification commands and evidence
From game root rg -n 'A[0-9]{2}' docs/plan/parity.md, direct public-author release pages, git diff --check and verify anchors/relative targets in the new file. No build needed.
## 12. Constraints and stop conditions
No commits, dispatch, published content, third-party source or assets. Stop only for an ownership conflict or material decision. Report unresolved evidence as an explicit question.
## 13. Authorization and decisions
User asked to start the approved roadmap with one branch per milestone and subagents. Root owns integration and Git side effects.
## 14. Return format
Return M00-A status, path, new IDs, inspected releases and unresolved gaps, corrections to root and actual verification evidence. No subagents.
+48
View File
@@ -0,0 +1,48 @@
# Record the base-game behavior and release evidence
Task ID: M00-B
Role: sol_implementer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m00-inventory at 0deacb3. Prior untracked .serena and workflow/TASKS and older tasks belong to the user. M00-P and preflight approve the scoped inventory.
## 2. Objective and deliverables
Produce the actual M00 public-behavior audit for Stonehearth base through 1.1 in NEW docs/plan/base-evidence.md (Russian).
## 3. Scope and non-goals
Cover the 24 existing base observations and add distinct concrete observations from the inspected sources. ACE has a different owner. Do not copy game code, art or passages.
## 4. Files to inspect
Inspect docs/plan/parity.md (B01–B24, source links), docs/plan/milestones/M00.md, PLAN.md and matching system/milestone plans; consult developer announcements on Steam and primary release evidence through 1.1.
## 5. Write ownership and coordination
Write scope: docs/plan/base-evidence.md
You share the checkout with other authors. Do not revert or edit their work. Root links your file and integrates indexes.
## 6. Implementation or investigation approach
Walk identifiable releases chronologically, record dates/builds, which portions were inspected, which are still open, last examined and concrete next source. Audit B01–B24 individually or group only where source/version and status apply unambiguously to every member. Distinguish preview from stable release and claims from proposed checks. Add worthwhile nonduplicate B25+ behaviors including culture/peaceful branches and occupations where evidenced. Use stable deep links from developers, no secondary wiki assumptions.
## 7. Interfaces and data contracts
For each new ID use a durable lowercase HTML anchor and include module, applicable version/source, trigger, player effect, independent equivalent/test, linked existing Sxx/Mxx; retain original Bxx ids and AT naming. Use narrow open questions for unresolved version/outcome. Independent localized prose.
## 8. Dependencies and integration
Root owns parity.md and M00 crosslinks. ACE author owns Axx and art owner handles provenance. Report any substantive corrections to the original seed descriptions to root.
## 9. Edge cases security and performance
Treat old announcements and unsurveyed ranges honestly; no unsupported 1.1 confirmation or exhaustive claims. No Stonehearth/ACE code, assets, credentials or uploads.
## 10. Acceptance criteria
1. Every seed ID maps to checked primary evidence or an explicit reproducible evidence question. 2. New observations are testable, linked and distinct. 3. Source coverage ledger identifies work reviewed and still open.
## 11. Verification commands and evidence
From game root use rg -n 'B[0-9]{2}' docs/plan/parity.md, direct public-author release pages, git diff --check and verify new Markdown anchors/relative targets in your file. No application changes or builds necessary.
## 12. Constraints and stop conditions
No commits, dispatch, published content, third-party source or assets. Stop only for an ownership conflict or material decision. Report unresolved evidence as an explicit question.
## 13. Authorization and decisions
User asked to start the approved roadmap with one branch per milestone and subagents. Root owns integration and Git side effects.
## 14. Return format
Return M00-B DONE/PARTIAL, path, source coverage, new ID range, case-by-case caveats/corrections and executed checks. No subagents.
+48
View File
@@ -0,0 +1,48 @@
# Define original demo art and audit the inherited icons
Task ID: M00-D
Role: terra_specialist
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m00-inventory at 0deacb3. Prior untracked .serena and workflow/TASKS and older tasks belong to the user. M00-P and preflight approve the scoped inventory.
## 2. Objective and deliverables
Produce a Russian original art direction, M03 production budget and item-level provenance record in NEW docs/art/demo-inventory.md.
## 3. Scope and non-goals
Cover models, textures/materials, animation, sound, font use, UI and 3 legacy icons. Make production decisions concrete and bounded. Documentation work only.
## 4. Files to inspect
Inspect docs/plan/milestones/M00.md, M03.md, docs/plan/systems/S20.md, app/house_icons.rc, app/art/, app/viewer_win32.cpp house choices, CMakeLists.txt, build.ps1, LICENSE and icon Git history.
## 5. Write ownership and coordination
Write scope: docs/art/demo-inventory.md
The other authors own behavior catalogs and root owns integration. Do not change their work, any tracked art, CMake, or application code.
## 6. Implementation or investigation approach
Trace all three icon blobs individually with adding commit and current hash/reference. Check source/attribution evidence. Set a disposition if rights remain unknown. Design the M03 scene independently (voxel scale, readable silhouettes, palette/material/lighting, animation and sound cues, font fallback) and a finite asset inventory keyed to the Q-HOME route. Record named author/source/rights/evidence or explicit missing/owner/gate, derivative/attribution and intended tool/export. Do not invent completed art or rights.
## 7. Interfaces and data contracts
Distinguish source evidence, art brief and shipped inclusion. Current viewer embeds all three ICOs through house_icons.rc; M00 can record exclusion from the NEW demo and production owner/replacement gate. Preserve the historical build record. Document actual roles for the three house buttons.
## 8. Dependencies and integration
Root maps asset work to M00/M03 and decides package integration. No integration with any external service, no new commissioned/paid assets.
## 9. Edge cases security and performance
Existing license and Git commit author alone cannot establish provenance of imported images. Label planned assets, system fonts (no redistribution) and any rights questions truthfully. Provide precise what-to-check at release.
## 10. Acceptance criteria
1. Each ICO individually traceable and included/excluded status justified. 2. Independent, concrete style and artist-ready playable demo bill of materials with provenance status, source/export & budget. 3. No implied clearance of future deliverables; include a usable manual check from camera.
## 11. Verification commands and evidence
From game root git log --all --diff-filter=A -- app/art, git ls-tree -r 083b84e -- app/art, rg -n 'house_icons|house_artwork|house_choices' app CMakeLists.txt, git diff --check; verify links. Document source findings.
## 12. Constraints and stop conditions
Do not edit graphics/code or create assets. No branch changes, commits, external messages, or child agents; report genuine unresolved evidence.
## 13. Authorization and decisions
User asked to start the approved roadmap with one branch per milestone and subagents. Root owns integration and Git side effects.
## 14. Return format
Return M00-D status, owned file, each icon verdict, Q-HOME coverage, evidence and remaining production work. No subagents.
+48
View File
@@ -0,0 +1,48 @@
# Preflight the inventory and replay handoff
Task ID: M00-F
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root /home/faumaray/Projects/stoneheart_at_home, milestone/m00-inventory at 0deacb3. Old .serena and workflow tasks/TASKS untracked. M00-P mapped 50 seed rows, three icons and three parallel submission sites. M01-R investigates Void separately.
## 2. Objective and deliverables
Preflight the contracts for M00 and the first M01 slice. Give actionable blockers before authors make changes. This is a design check, followed later by independent diff review.
## 3. Scope and non-goals
M00 evidence/asset inventory and reproducible baseline, then M01 serial-reference/tick comparison with a scheduled prototype scenario and reload. Larger runtime redesign belongs to later work.
## 4. Files to inspect
Inspect PLAN.md, docs/plan/milestones/{M00,M01,M03}.md, docs/plan/{parity,void-library}.md, docs/plan/systems/{S01,S15,S20,S21}.md, CMakeLists.txt, engine/include/settlement/core/{world,worker_pool}.hpp, engine/src/{world,world_save}.cpp, tests/core_tests.cpp.
## 5. Write ownership and coordination
Write scope: none
Shared checkout. Root owns all edits/branches; no subagents.
## 6. Implementation or investigation approach
M00 authors own (a) behavior catalog and primary-source coverage/release/gap ledger, preserving stable anchors, (b) original art direction/M03 inventory and exclusion disposition for icons; root owns baseline, concrete Q-HOME/scale handoff and linking. M01 proposed explicit serial path for all parallel world passes, default pool and legacy counts intact, repeatable command fixture, exact serialized prototype state after every tick and across reload; only pinned applicable public Void utilities.
## 7. Interfaces and data contracts
Treat closed evidence versus planned/unknown behavior separately. Save 13/LAN 11 stay compatible; worker settings are execution state, not canonical game bytes. Require useful work in the fixture, independent expected results, fresh-world mismatch detection and preserved execution mode on load.
## 8. Dependencies and integration
M00 root records sources/test evidence before M01 branch; M01-R verifies Void reuse. The planner and researcher do not own implementation. Root reconciles findings before dispatch.
## 9. Edge cases security and performance
Assess accidental distribution of unverified icons through existing Win32 resources, rights versus Git author, public-source boundaries; assess default worker performance and serial-without-threads semantics, thread/queue/exception behavior, transient caches, tests under GCC16/Wine.
## 10. Acceptance criteria
1. Return READY or scoped blockers with fixes. 2. Identify missing acceptance checks and ownership collisions. 3. Distinguish M00 launch inventory from final release coverage and M01 starter slice from complete milestone.
## 11. Verification commands and evidence
From game root git status --short --branch, git diff 083b84e..HEAD --stat -- engine app tests CMakeLists.txt, rg -n 'worker_count|WorkerPool|submit\(|save\(|load\(' engine tests/core_tests.cpp. Available tests in CMake are settlement_core_tests, settlement_lan_tests. Use local read-only commands only.
## 12. Constraints and stop conditions
Stop once decisive constraints can be sent. No fixes, Git mutation, external writes or duplicate source research. Return M00 decision early if M01 needs longer.
## 13. Authorization and decisions
User authorized starting the existing plan on one new branch per milestone with subagents. Root approves product scope, reviewer checks technical readiness only.
## 14. Return format
Return M00-F preflight verdicts by milestone, concrete severity/location/trigger/fix, checks and regression risks. Send early actionable findings; do not spawn.
+48
View File
@@ -0,0 +1,48 @@
# Map the first milestone and the executable handoff
Task ID: M00-P
Role: astra_planner
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m00-inventory from chore/plans at 0deacb3. The old .serena and workflow tasks/TASKS are untracked. M00 precedes M01 under PLAN.md.
## 2. Objective and deliverables
Map what M00 still needs beyond the 50 seed rows, and design one runnable, dependency-correct first slice of M01 on its own descendant branch.
## 3. Scope and non-goals
Read-only Scout. Concentrate on baseline, parity, Q-HOME, requirements, tick/worker callers, independent work packages and the smallest meaningful implementation with tests.
## 4. Files to inspect
Inspect docs/plan/milestones/M00.md and M01.md, docs/plan/parity.md, docs/plan/systems/S01.md, S15.md, S20.md, S21.md, engine/include/settlement/core/{world,worker_pool}.hpp, engine/src/world.cpp, tests/core_tests.cpp.
## 5. Write ownership and coordination
Write scope: none
Shared checkout. Root owns all edits/branches. No child agents.
## 6. Implementation or investigation approach
Identify gaps versus existing artifacts, stable interfaces and failure modes. Check local symbol evidence for the M01 seam. Distinguish M00 acceptance from full future parity. Use the scoped graph only after root/coverage/freshness checks or use local sources for coverage gaps.
## 7. Interfaces and data contracts
Preserve B01–B24/A01–A26 anchors, old world save 13 and LAN 11, existing default and invalid pool sizes. Propose NEW M01 interfaces only when needed.
## 8. Dependencies and integration
Researcher separately investigates VoidLibrary so do not duplicate that investigation. Root integrates disjoint authors and gates each milestone.
## 9. Edge cases security and performance
Do not infer asset rights or Windows correctness from a filename or Wine. Keep reference-content research to public behavioral descriptions.
## 10. Acceptance criteria
1. Return a bounded milestone package map with acceptance evidence. 2. Identify M01 entry point, assumptions, state comparison, and regression cases with exact source locations. 3. Give dependency/branch boundaries.
## 11. Verification commands and evidence
From game root use git status --short --branch, git show -s --format=%H, rg -n 'WorkerPool|tick\(' engine tests app/main.cpp and relevant bounded file reads. Report observed commands and runnable tests.
## 12. Constraints and stop conditions
Stop for contradictions materially changing the product; no tracking issues, no Git edits, no installation. Return an early handoff when the plan is clear.
## 13. Authorization and decisions
User asked to start the approved plan, use new branches per milestone and subagents. This assignment supplies planning only.
## 14. Return format
Return M00-P status, files/evidence, proposed ownership, invariants, next verified checks and residual uncertainties.
+48
View File
@@ -0,0 +1,48 @@
# Review the integrated M00 inventory checkpoint
Task ID: M00-V
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m00-inventory, baseline 0deacb3. Old untracked .serena and legacy workflow/TASKS and V/RM are outside the diff. M00-P/F supplied plan and preflight; this is a fresh independent review.
## 2. Objective and deliverables
Review the actual M00 checkpoint for traceability, accuracy and readiness of its confirmed M01 handoff. Report READY, CHANGES_REQUIRED, or INSUFFICIENT_EVIDENCE with scope.
## 3. Scope and non-goals
Review inventory of 80 behavior IDs, released-vs-open evidence, original demo production inventory and legacy icons, reproducible baseline, Q-HOME/scale, Void decision, branch records. Review current changes, not author reports.
## 4. Files to inspect
Inspect git diff 0deacb3 plus NEW docs/plan/{base-evidence,ace-evidence,prototype-handoff}.md, docs/art/demo-inventory.md and linked M00/M03, parity.md, PLAN.md, docs/agent-workflow/STATE.md, docs/plan/void-library.md. Compare to CMakeLists.txt, app/house_icons.rc, build.ps1, benchmark records, M00 acceptance.
## 5. Write ownership and coordination
Write scope: none
Root owns all corrections and Git. Shared checkout; no child or external side effects.
## 6. Implementation or investigation approach
Check stable IDs/backlinks, source samples (stable vs preview, .22 edits, peaceful path, corrections), explicit unknowns and release-crawl limits. Verify scene consistency, compatibility evidence and whether old resource inclusion is recorded. Source-check via primary public descriptions and repository Git where useful.
## 7. Interfaces and data contracts
Do not infer parity from inventory or art rights from Git attribution. Planned Q-HOME seed/coordinates are a fixture, not already generated. Preserve M00 evidence while allowing M01 to start from confirmed boundaries.
## 8. Dependencies and integration
Root observed two successful baseline Windows CTest runs using GCC16/Wine; fresh dir /tmp/stoneheart-milestones.xprJ2SVp/windows; log baseline-ctest.log in its parent. Temporary validation script found 43 docs, 80 unique IDs, all 50 direct audit pointers, no broken local link, icon hash mismatch or table error.
## 9. Edge cases security and performance
Do not assign deep examination of every historical release or production of art as completed. Pay attention to references going to the wrong edition and unsupported hardware or compatibility claims.
## 10. Acceptance criteria
1. Return verdict on integrated M00 and M01-ready handoff. 2. Identify concrete evidence conflicts, broken links or misreported results. 3. Report remaining source/art checks separately from fixable document defects.
## 11. Verification commands and evidence
Game root: git diff 0deacb3 --stat; git diff --cached --check; python3 /tmp/stoneheart-milestones.xprJ2SVp/validate_docs.py; git log --diff-filter=A -- app/art; inspect scoped files plus actual runtime log. No new build required for docs.
## 12. Constraints and stop conditions
No edits, branch switching, staging, commits, merge, remote messages or unsupported claims. Return bounded findings as soon as evidence suffices.
## 13. Authorization and decisions
User authorized milestone implementation and local branches. This review is advisory on the checkpoint, not a release authorization.
## 14. Return format
Return M00-V verdict with severity, location, trigger, impact and verification for each actionable issue, actual checks/unrun checks and remaining inventory scope.
+48
View File
@@ -0,0 +1,48 @@
# Run the same world kernels in an explicit serial reference mode
Task ID: M01-C
Role: sol_implementer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation, M00 checkpoint 904bdf8. Legacy task notes/.serena are user work. M00-P/F and M01-R established the prototype's three worker sites and checked the pinned Void APIs.
## 2. Objective and deliverables
Implement the first M01 execution seam: an explicit true serial reference and the existing threaded game mode for World construction and load.
## 3. Scope and non-goals
Work only on simulation execution selection, including path selection/route/advancement. Keep normal CLI, viewer, LAN, wire bytes, command behavior and parallel executor compatible.
## 4. Files to inspect
Inspect engine/include/settlement/core/world.hpp, engine/src/{world,world_save}.cpp, worker_pool.hpp/cpp, tests/core_tests.cpp, docs/plan/milestones/M01.md and docs/plan/void-library.md. choose_jobs, find_path and advance_agents already exist in World.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp
You are not alone in this checkout. Other authors own tests and CMake; root owns docs and Git. Do not revert others' work.
## 6. Implementation or investigation approach
Add the explicit mode to World construction and read_save. Validate count/mode before stepping. For serial work call the same domain kernels on the caller thread: compute all candidate choices against one starting state before committing winners, run the same find_path and apply requests in the same order, advance agents for the whole range once and sum actual completions. Preserve existing chunking and order in threaded mode. Use direct domain calls and avoid building any generic executor or new state codec.
## 7. Interfaces and data contracts
NEW settlement::ExecutionMode::{Parallel, SerialReference}. World(seed,w,h, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel); World::read_save(stream, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel). Parallel accepts 2..64 as today. SerialReference requires logical count 1, creates zero OS workers and reports worker_count()==1. Reject invalid combinations/unknown enum with std::invalid_argument. Configuration is local and never serialized. Other source-compatible choices inside these paths are discretionary.
## 8. Dependencies and integration
Tests owner will use frozen interface immediately. Preserve save v13 fixture, old versions, LAN 11, performance of ordinary pool dispatch and its current lifetimes. Pinned Void covers binary/test primitives; game-specific direct invocation adds no generic library facility. ThreadExecutor migration has its own later failure/performance contract.
## 9. Edge cases security and performance
Account for no agents/jobs, paused world, one resident, fewer agents than workers, competing jobs, retries for unreachable routes, reload and cache state. Keep parallel error behavior; do not broaden lifetime hazards. No detached tasks or implicit threads in serial.
## 10. Acceptance criteria
1. Serial mode reaches all 3 sites without a worker pool. 2. Invalid ordinary counts still fail, valid serial passes constructor and load. 3. Exact v13 save bytes and outcomes match 2/6/12 for useful scenarios. 4. Default behavior and old consumers compile.
## 11. Verification commands and evidence
From game root source /tmp/stoneheart-verify.KoZwE4o8/env.sh; then cmake --build "$SETTLEMENT_VERIFY/candidate" --parallel 8 --target settlement_core. Use git diff --check and inspect actual diff. Tell root/tests when implementation compiles; tests use another build directory and root runs integrated suites.
## 12. Constraints and stop conditions
Do not alter other files, registry, network, branch or legacy pool, stage/commit or spawn. Escalate a required interface change and report errors before changing approach twice.
## 13. Authorization and decisions
User approved starting the roadmap on per-milestone branches and parallel subagents. Root selected first M01 replay increment after independent preflight.
## 14. Return format
Return M01-C status, changed paths/symbols, mode and ordering decisions, commands/results, untested paths and integration notes.
+48
View File
@@ -0,0 +1,48 @@
# Preflight the rules, executor and authoritative runtime packages
Task ID: M01-F2
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home on milestone/m01-authoritative-simulation, M00 at 904bdf8, M01 serial tranche under separate final review. User authorized the entire roadmap with remote pushes by milestone/system.
## 2. Objective and deliverables
Check next M01 system contracts before implementation. Prioritize a verdict for independent S19 rules and S01 Void pool migration, then S16 authority, S15 persistence and S01 viewer runtime.
## 3. Scope and non-goals
Review technical design/failure boundaries and independent branch ownership. Later M02+ behavior is outside this preflight; the existing prototype remains runnable while these staged features integrate.
## 4. Files to inspect
Inspect plans M01, S01/S15/S16/S19, world.hpp/cpp, world_save.cpp, app/viewer_win32.cpp, app/lan_session_win32.cpp, engine/include/settlement/core/worker_pool.hpp, CMakeLists.txt. For Void check docs/plan/void-library.md and exact pin headers selected below.
## 5. Write ownership and coordination
Write scope: none
Root owns checkout and branches. Separate system worktrees will isolate CMake/test changes; no new child agents.
## 6. Implementation or investigation approach
S19 proposed bounded UTF-8 strict JSON manifest with namespaced IDs, schema+SemVer versions, definitions/references, dependencies, exclusive capabilities and recomputed per-package SHA256. A selected installed set is transitively resolved, duplicates/missing/range incompatibility/cycles/exclusive conflicts/unknown definitions rejected. Canonical encoding sorted by stable IDs plus exact SemVer incl build and digest frozen with a world/save/network. Reuse Void::Json::Strict, Semver, Algorithms graph and Crypto or report target blockers. Test actual input, deterministic permutation, malformed bounds, meaningful differences. S01 worker migration uses exact-pinned ThreadExecutor and FuturePool with overload retention, startup failure cleanup, draining accepted futures before captured locals unwind, reference and pressure tests plus measured useful work.
## 7. Interfaces and data contracts
S16 proposal: single host dispatcher, trusted transport identity separate from payload, world/session/city/request identity, exact repeat receipt for same payload, conflicting replay/stale epoch has no effect; validation and mutation on owner thread. S01 timer runs fixed interval and publishes shared immutable completed state, live local/guest commands and read-only viewer no longer step/mutate an authoritative World from WM_TIMER. S15 validated candidate swap increments epoch even on rollback, bounded asynchronous immutable snapshot writing, atomic same-volume publication leaves previous data after failure. Rule selection persists + validated before live replacement. Existing sav13/LAN11 continue only by explicit compatibility surfaces.
## 8. Dependencies and integration
M01-P2 maps game code, M01-R2 verifies APIs: SemVer == ignores build so frozen identity uses exact version; Graph input ordering must be canonical. FileSystem atomic_write is unsupported on Windows: an upstream gap issue precedes local fallback. Root integrates M01 branches; public pushes separately authorized.
## 9. Edge cases security and performance
Consider also capturing mutable UI references/exceptions, pool draining and useful equality after queue pressure, concurrent load/save identity and stale worker results, bounded journal/receipt identity/windows old files. Identify native-only checks explicitly.
## 10. Acceptance criteria
1. Prioritized READY or blockers for S19, S01 pool, and architecture for S01 runtime/S15/S16. 2. Concrete failure/ownership/test requirements and needed refinements. 3. Distinguish M01 goals from M09 public coop/1.0 packaging.
## 11. Verification commands and evidence
From game root git diff 904bdf8 --stat; rg -n 'WM_TIMER|read_save|write_save|try_submit|worker_pool_|apply_command' engine app; consult actual upstream pinned StrictJson/Semver/Graph/Crypto/FuturePool public APIs and local source as needed. No writes or builds.
## 12. Constraints and stop conditions
Send S19 and pool verdicts early; flag material decisions and applicability. No file edits, external actions, or child agents.
## 13. Authorization and decisions
The user authorized implementing the full plan with subagents, commits and pushes. Root retains integration and system approval.
## 14. Return format
Return M01-F2 priority verdicts per package, actionable severity/location/contract fix, tests required, deferred compatibility/work. Do not review your own implementation.
+48
View File
@@ -0,0 +1,48 @@
# Confirm the exact authority, failure and publication boundaries
Task ID: M01-F3
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation 8d2870a. M01-F2 identified four gaps. S01 pool and S19 running in separate worktrees. Upstream issues 3/4/5/6 are registered in Void/Library.
## 2. Objective and deliverables
Verify the root's concrete decisions below close F2's open failure/identity/order points for starting S16 dispatcher, S15 writer and dependent runtime. Design review only.
## 3. Scope and non-goals
Cover S16/s15 independent modules and next runtime ownership, preserved legacy behavior. No release or M09 network exposure.
## 4. Files to inspect
Read docs/agent-workflow/tasks/M01-F2.md, docs/plan/milestones/M01.md, S01/S15/S16, World::apply_command, worker submissions, app/viewer_win32.cpp legacy save/poll/queue cabin and LAN11.
## 5. Write ownership and coordination
Write scope: none
Root owns decisions; no child or shared mutation.
## 6. Implementation or investigation approach
S16 per active epoch: trusted transport passes known client slot separately from payload. World/session are nonnil Void UUIDs, city ID checked. Each authenticated client has monotonically contiguous request numbers starting at 1. Retain every completed result (including rejections) for the active epoch; reserve the record before mutating; check status/city/kind/entire payload equality. On capacity there is backpressure on NEW requests before effects, older cached receipts remain replayable, no eviction/reexecution. Requests behind missing/out-of-order and wrong epoch have distinct transient/nonmutating errors. Envelope ID maps to existing World next sequence only after validation, preserving legacy rejected-reusable sequence behavior. Clients choose new numbers for revised intents. Per-session ledger cap is configurable and explicit. Fresh session discards old history after successful replacement; old envelopes fenced.
## 7. Interfaces and data contracts
S15 independent FIFO bounded single-writer service accepts materialization from a held immutable snapshot, serializes in background, bounded admission returns busy, Windows same-directory exclusive temp + write/flush/close + atomic publication; distinguish before/after visibility. Queue is serialized at admission across slots, so older same-slot save cannot finish after a newer one. Each completion identifies request/tick/epoch; latest UI state checks request ID. Shutdown drains accepted work. Input prepare/validate outside owner; replace only when matching expected old epoch and most recent load request. Corrupt/superseded load changes nothing.
## 8. Dependencies and integration
S01 runtime single simulation owner processes bounded requests also during pause and publishes an immutable independent World copy tagged with world, session, tick and publication revision including changes at the same tick. Stage tasks all drained before stack unwind. On ANY tick, command or snapshot preparation failure keep previous published snapshot and discard faulted mutable candidate; no success receipts are exposed for uncommitted changes. Runtime enters faulted and rejects saves/commands until an explicitly validated load restores coherent state under a fresh epoch. UI direct queue_cabin and LAN mutations route through owner; legacy wire stays separate. S19 immutable manifest part of checkpoint compatibility. Root owns interfaces.
## 9. Edge cases security and performance
Do not silently evict exact-repeat results or claim power-loss guarantees. Check constraints for denial of access or unsupported administrative features. Long-session journal storage beyond M01 replaceable bound documented. Root will record recovery outcome and tests.
## 10. Acceptance criteria
1. Return READY or scoped correction for S16 and S15 first, followed by runtime. 2. List exact stalled/failed operation behavior. 3. Identify remaining prospective tests in rollback, queue capacity, duplicate and concurrency scopes.
## 11. Verification commands and evidence
From game root git show -s --format=%H, rg -n 'save_world_file|queue_cabin|World::apply_command|World::step' app engine, inspect referenced existing contracts; no runtime build needed.
## 12. Constraints and stop conditions
No edits, branch changes, external writes, children or duplicate investigation. Send early if S16/S15 ready.
## 13. Authorization and decisions
Full roadmap approved. Root requested this follow-up specifically to resolve M01-F2 before starting those packages.
## 14. Return format
Return M01-F3 READY/CHANGES_REQUIRED per scope with any remaining actionable failures and tests; no edits.
+48
View File
@@ -0,0 +1,48 @@
# Preflight the real Win32 client, file and LAN owner adapters
Task ID: M01-F4
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root a4cf99c contains all independently reviewed primitives. S01-04 implementation in /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 at 2224299 awaiting review; public header and 10 tests exist. Planner M01-P2 and preflight F3 defined owner; current WM_TIMER still steps mutable world, saves synchronously and LAN11 poll writes directly.
## 2. Objective and deliverables
Check precise adapter design for normal Win32 UI, asynchronous checkpoint files and existing two-slot LAN11, then give per-package green lights or bounded corrective requirements.
## 3. Scope and non-goals
Read-only M01 client wiring; existing public co-op compatibility and file use. No new public transport, encryption protocol or broad SDK. Existing S16 modern envelopes can be exercised with 2 internal clients; public network roadmap continues later.
## 4. Files to inspect
Inspect actual runtime public header + owner implementation in s01 checkout; viewer_win32.cpp WM_TIMER, start/stop/menus/new/load, local command reporters/blueprint rejection, title_screen; lan_session.hpp/.cpp protocol11 command/sequence/reconnect/send_snapshot, lan_wire; S15 checkpoint/save_service, initial rules catalog and document plan M01.
## 5. Write ownership and coordination
Write scope: none
No mutations, builds, shared Serena switches, branch/remote ops or children. Parent owns produced contracts and commits.
## 6. Implementation or investigation approach
File adapter (S15) uses one bounded Void background reader and approved SaveService (max_checkpoint_bytes). Caller obtains healthy published snapshot once; producer owns it and encodes on writer thread. Asynchronous load prepare from path/catalog only, with bounded bytes/check signatures, read one open file, legacy World::read_save migrates to new stable UUID/city+default rules; current envelope validates exact installed closure. Keep current 32x32 viewer dimension gate outside generic codec and validate before install. Futures retain immutable data, no background Win32 calls or raw runtime/viewer pointers. Shutdown drains. UI binds a runtime LoadTicket to each admitted load and rejects stale completions by epoch+latest request; report latest save/load per UI slot/request and older save completions must not overwrite newer status.
## 7. Interfaces and data contracts
LAN11 adapter (S16) keep existing poll(World&) entry/test; add preferred asynchronous host path driven by SimulationRuntime and a guest-only poll requiring no mutable authority. Maintain same exact frames/signature/2 trusted slots. Check authenticated wire request. Legacy numeration is World::next_command_sequence and ordinary domain rejections leave it live, while new envelopes use runtime published next_requests per slot including rejections. Compare incoming wire seq and use authenticated guest slot, serialize per-peer in-flight command so no stale snapshot mapping/multiple executions; return receipt only after committed outcome, current correct next wire sequence. Disconnect/generation/guest changes discard pending network completions without moving effects into new session. Never block network/UI waiting for owner. Exclude new public endpoint. Add verified real host/guest loopback via async path including wrong sequence, rejection and subsequent corrected same old number, reconnect. Keep original fixtures/binary interoperability.
## 8. Dependencies and integration
Viewer milestone adapter: one shared_ptr<const World> consistent view (hold for entire frame including nested messages), one SimulationRuntime for offline/host. Guest consumes incoming const views only, transient old host connection fenced. WM_TIMER polls completions/views/network rather than advancing world. New colony/reset creates valid UUID+selected default-compatible manifest; expose real choice where alternative installed packages materially alter game creation (no cosmetic selector). Existing host authority/pause/title/file-dialog gating via set_ticking independent of World::paused; retries when Busy and don't flood queue. Local mutations incl legacy cabin route through runtime. UI needs acknowledged result before applying accepted-only changes; queue/futures and pending metadata reinsert blueprint or report typed rejection, FIFO contiguous modern IDs, handled Busy/OutOfOrder; snapshots can lag while multiple local inputs are pending. Ensure reads and command submission never block on a long tick. Keep modern save normal UI path; legacy saves still load deliberately.
## 9. Edge cases security and performance
Pay particular attention to Win32 reentrancy, old futures crossing reset/load, modal pickers, latest load after failed reading vs superseded earlier good, rollover UI state if save job from old session finishes, in-flight bounds and trusted peer rebind. A non-default rules subset must be truly compatible with hard-coded prototype game until more rule-driven mechanics land. Avoid accepting incompatible content silently or rejecting legacy corrected retries.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per file adapter, LAN and UI. 2. Concrete interface+tests for each, required handoff order and where existing code enforces assumptions. 3. Clarify what is safe to dispatch immediately and any consequence requiring product choices.
## 11. Verification commands and evidence
git status --short --branch, scoped rg -n 'WM_TIMER|world->step|handle_save_menu|submit_command|queue_cabin|handle_host|poll\(' app, read targeted actual source. No builds needed. Existing combined 82 core+4 LAN, S01-04 adds ten. Current CLI old baseline cross-version harness /tmp/stoneheart-verify.KoZwE4o8/interop.cpp.
## 12. Constraints and stop conditions
No edits, external actions or other agents; no extension to public LAN protocol or unwanted UI. Report any ambiguous scope to parent rather than blocking independent file service.
## 13. Authorization and decisions
User authorizes all milestones, prior planner/preflight resolved ownership; this concerns concrete client integration choices within M01. Parent handles branches and git operations.
## 14. Return format
Return M01-F4 verdict per package, exact corrections and compatibility tests, optional future distinction where implementation depends on another unbuilt seam.
+48
View File
@@ -0,0 +1,48 @@
# Recheck concrete client and peer lifecycle contracts
Task ID: M01-F5
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Main at 512c9ef, previous F4 approved S15 and identified two LAN and three UI gates. Revisions are in /home/faumaray/Projects/stoneheart_at_home-worktrees/{s16,s18}/docs/agent-workflow/tasks/{S16-02,S18-01}.md. Runtime header is integrated; CheckpointFiles header is real in s15.
## 2. Objective and deliverables
Check added conditions against F4 findings for early per-package approval before implementation.
## 3. Scope and non-goals
Read-only recheck of contract adequacy, no review of future LAN/UI implementation. S15 already implementing.
## 4. Files to inspect
Read two task documents, M01-F4, normal Win32 title/timer/guest reset and LAN drop_peer lifecycle and actual runtime/CheckpointFiles headers. Match earlier evidence.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote requests/Git actions/children.
## 6. Implementation or investigation approach
Verify LAN default-only manifest gate, epoch reconnect, independent receipt tracking across peer turnover, legacy next sequence vs modern committed id and nonblocking completions. Verify viewer completion pump precedes all title returns, no old runtime joins blocking reset/new/join, one writer, receipt-driven bounded one-in-flight queue and profile guard, load supersession and safe guest/offline transition.
## 7. Interfaces and data contracts
Review exact contract not summaries. Flag any missing precondition or undefined API behavior that prevents a worker from safely implementing a nonblocking compatible host/client.
## 8. Dependencies and integration
F4 read-only reviewer pre-existing; parent will perform integration after independent implementation. Root ensures reviewed sibling dependencies available to S18.
## 9. Edge cases security and performance
Watch stale future from disconnected client, latest failed load, modal reentrancy, old/new slot file ordering and unsupported manifest advertising. Genuine alternative module selection and texture/keyboard features are independently scheduled.
## 10. Acceptance criteria
1. Separate READY/targeted correction per S16/S18. 2. Bound any remaining actual gap and verification needed. 3. No implied release or approval to merge remotely.
## 11. Verification commands and evidence
Read actual tasks including ownership, tests and stop gates and inspect relevant source from F4. git show 512c9ef --stat optional; no build required.
## 12. Constraints and stop conditions
Read only. Return LAN early if adequately scoped. Stop only for a material remaining omission.
## 13. Authorization and decisions
Root requests this F4 follow-up after exact corrections and user has authorized roadmap. No remote writes.
## 14. Return format
Return M01-F5 S16 and S18 READY/CHANGES_REQUIRED with evidence and residual concrete runtime/native checks.
+48
View File
@@ -0,0 +1,48 @@
# Map the authoritative runtime and dependent system branches
Task ID: M01-P2
Role: astra_planner
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation at M00 904bdf8, M01-C/T in progress. User extended the goal to the full plan with commits, pushes and separate milestone/system branches. Pin 7b0fea6, Windows GCC16.
## 2. Objective and deliverables
Design the next integrated M01 implementation after the deterministic reference. Give concrete separable packages, frozen APIs, branch order and runnable acceptance for S01, S15, S16, S19 and the viewer.
## 3. Scope and non-goals
Read-only plan for M01 and prospective compatibility seam for M02. No new product discovery; the approved roadmap controls. Do not replan existing serial/replay task.
## 4. Files to inspect
Inspect PLAN.md, M01/M02, S01/S15/S16/S19 and S04/S06 contracts, world.hpp/world.cpp/world_save.cpp, app/viewer_win32.cpp, app/lan_session.hpp and _win32.cpp, CMakeLists.txt and current tests incl LAN. Check actual world mutators, UI direct writes, reload/command cache hazard and exposed stores/indices.
## 5. Write ownership and coordination
Write scope: none
Shared checkout; root owns branches/builds. Do not modify files or activate a different project.
## 6. Implementation or investigation approach
Indicate exact integration for a single-owner fixed-tick runtime publishing immutable snapshots; atomic candidate load/epoch rejection; versioned, city-scoped idempotent command results/authentication; rules manifest dependency validation/fingerprints; permanent ID and custody path. Preserve old format13/protocol11 with an explicit compatibility boundary for existing programs. Propose deliverable slices which independently add executable tested features.
## 7. Interfaces and data contracts
Name specific NEW types and responsibilities separate from observed ones. Explain host identity, dedup key, conflicts with stale packets, pending versus committed epoch, queue bounds and failed save/load. Suggest a no-duplicate-serialization path, CPU cost/50ms budget and API for existing viewer reads.
## 8. Dependencies and integration
Researcher separately investigates Void/primitives. Root authorizes scope, owns CMake integration, cross-system compatibility and push. One branch per milestone or system package fits the added user direction. New worktrees may be used for independent systems.
## 9. Edge cases security and performance
Call out deadlocks, stale load/worker results, snapshot lifetime, partially applied ticks, time spent in rendering, current hardcoded two slots and generator/script state. Keep more ambitious M09 features on M09.
## 10. Acceptance criteria
1. Source-grounded M01 package graph and first precise interfaces usable for concurrent implementation. 2. Boundaries for each acceptance criterion including existing gameplay/legacy callers. 3. Concrete, short next package to dispatch plus integration strategy.
## 11. Verification commands and evidence
Use git status --short --branch, git diff 904bdf8 --stat; rg -n 'WM_TIMER|world->step|world->apply_command|read_save|write_save|lan.poll' app engine; use scoped graph with coverage/direct checks for cited source. Existing integrated check is CMake + CTest Windows on Wine. No remote writes.
## 12. Constraints and stop conditions
Send first independent work packages early when ready. Stop if evidence requires a product decision; keep useful read-only work going. Do not spawn.
## 13. Authorization and decisions
User explicitly requested the full plan, local commits, remote pushes and occasional status. This assignment is planning only.
## 14. Return format
Return M01-P2 READY/PARTIAL, package DAG, file boundaries and frozen API, behavior/risk/test matrix, what can ship first and which assumptions need owner confirmation.
+48
View File
@@ -0,0 +1,48 @@
# Map durable item custody and stable entity references into the running game
Task ID: M01-P3
Role: astra_planner
Status: READY
## 1. Context and baseline
The integrated M01 branch /home/faumaray/Projects/stoneheart_at_home is at cf0cc2f. S01-03 groups logical state in a private WorldState in s01 worktree. S15-02 introduces a versioned modern checkpoint around validated legacy body and exact rules. S16-01 scopes command receipts to session. User's next gameplay requirement in M01.2 is stable IDs and conservation.
## 2. Objective and deliverables
Specify an executable incremental implementation plan for M01 stable IDs/ownership through actual current game actions (production, resource haul, construction, inventory, demolish). Identify the first narrow end-to-end migration that can be dispatched immediately.
## 3. Scope and non-goals
Read-only S04/S06 and checkpoint/world integration architecture; distinguish current IDs from index-based fields and later M03 capabilities. No redesign of the whole roadmap, mod SDK, region/world geometry or unrequested product choices.
## 4. Files to inspect
Inspect world.hpp, world.cpp, world_save.cpp, first_colony.cpp, viewer_win32.cpp, app/d3d_scene_win32.cpp/tests, plan S04/S06, M01 and M03. Inspect s01 capture worktree actual logical representation and detached checkpoint checkout. In pinned Void inspect public IDs/typed handles/registry if relevant and cross-check already documented matrix.
## 5. Write ownership and coordination
Write scope: none
No mutations, branches, external requests or children. Parent owns root task notes and Git. Do not change shared Serena project.
## 6. Implementation or investigation approach
Map introduction, assignment, transport, consumption, split/merge, cancel/delete, HUD, serialization and load validation by actual symbols. Plan monotonic counters never reused, ownership and transitions, stable typed references with bounded lookup and ordered arbitration. If legacy format13 must keep indices on the wire, convert at codec compatibility boundary, ensuring legacy snapshots can import deterministic IDs; modern checkpoints must encode actual counters and identities so rollback/mutations never reassign values. Identify exact compatibility mode for changing demolish behavior, preserve existing tests where game design allows. Avoid double representations that can silently diverge/lose inventories.
## 7. Interfaces and data contracts
Specify NEW API and fields only after source check. Cover existing WorkJob.id, Agent.id, ResourceNode.id, Storage.id, ProductionOrder, MaterialReservation, ConstructionStop, ItemStack and private AgentInventory. Give ownership and migration sequencing for WorldState, routes, input/output codec, renderer, tests, and branches S04 vs S06. Recommend whether durable ID fields are domain-local or reusable generic Void capability needing issue; no remote writes.
## 8. Dependencies and integration
Dependencies S01 snapshot/dispatcher/S15 versioned checkpoint. Root owns integration order. Send first safe independent task early with exact symbols, lossless old-wire export boundary and hard tests before broad changes. Multi-branch CMake/World ownership must be serialised.
## 9. Edge cases security and performance
Check nonempty demolished storage (currently erases stored items), active reservations/held goods, room/floor target, duplicate/dangling IDs, counterfeit aggregate counters, overflow and million-record malicious saves. No behavior changes to LAN11 or wrong acceptance claims. Keep authoritative reconciliation deterministic for serial/parallel.
## 10. Acceptance criteria
1. Source-grounded table of stable vs positional identifiers and mutation sites. 2. First executable slice with narrowly owned files and disambiguated compatibility. 3. Subsequent DAG solves M01 reference/custody exit, tests after mid-carry load/cancel and ledger conservation. 4. Name any actual product decision needed, or bounded technical recommendation.
## 11. Verification commands and evidence
git status --short --branch, git show -s --format=%H, rg -n 'shift_index|reserved_slots|construction_delivery|MaterialReservation|production_index|stock_storage|finish_production' engine app tests; inspect actual pinned headers, current serializer/acceptance fixtures and exact removal semantics. No build needed for read-only planner.
## 12. Constraints and stop conditions
No source/code modifications, deployment or tool state changes. Stop if pinned source unavailable or a consequential design decision is truly user-owned. Return useful independent conclusions immediately.
## 13. Authorization and decisions
User approved entire plan and requested subagents. Root assigns this dependent architecture work within M01. F3 authority and failure decisions remain in force. Does not authorize a new public protocol/dependency or branch push by agent.
## 14. Return format
Return M01-P3 READY/PARTIAL, concise path/behavior, implementation contracts, ordering, tests, upstream fit, unresolved facts. No children.
+48
View File
@@ -0,0 +1,48 @@
# Map the first selectable rules to existing game behavior
Task ID: M01-P4
Role: astra_planner
Status: READY
## 1. Context and baseline
Main 4ba64f7 has frozen rules manifests, checkpoint v1, Window-independent runtime. S18 initial UI preflight correctly permits only actually supported profiles. Present World::start_scenario hardcodes staged_beds_=true, while saved legacy worlds and recipes/game commands contain both staged and simple/plank bed behavior. Builtin colony manifest has a board work_ticks field (8) different from compiled SawPlank (12), so treating that as activated configuration would change prototype behavior.
## 2. Objective and deliverables
Produce a narrow verified implementation proposal for M01 real module selection/new game/load, with an actual deterministic gameplay difference and unchanged default trajectory. Assess existing simple vs staged bed paths as the first selectable feature.
## 3. Scope and non-goals
Read-only S19 technical/product-fit plan for first actual setting, default compatibility and existing explicit script-state contract for M01. Keep new Lua runtime, complete mods SDK and public cooperations in planned later scopes.
## 4. Files to inspect
Inspect rules_manifest.{hpp,cpp}, world.{hpp,cpp}, world_save.cpp, first_colony.cpp, checkpoint.hpp/.cpp, checkpoint_files.cpp, simulation_runtime.cpp, actual title_screen_win32.hpp and viewer handlers, S19 W01–W03, master/parity/prototype fixture. Review test constructions of old v1/v2/current bed states, frozen digest fixture and handoff from S18.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote access or child agents. Parent owns root decisions and eventual branch contracts; keep shared Serena activation fixed.
## 6. Implementation or investigation approach
Trace actual recipe/placement/material/progress behaviors under World::staged_beds() false/true, inputs/stock and ability to complete both. Propose a valid optional built-in rule package with explicit behavior and data (for example opt-in classic recipe always uses simple plank). Keep frozen default 2-package digest, current normal make_first_colony behavior and v1–13 imports. Give validation path from chosen catalog → Resolved actual game options → world initialization and saved rules → preinstall compatibility. Avoid merely switching labels/fingerprints without changing executed mechanics. Do not equate any early option with complete ACE parity.
## 7. Interfaces and data contracts
Propose frozen NEW C++ APIs and file/branch ownership. Handle old scenario saves with staged_beds=false and legacy imported default manifest, custom unsupported manifests in generic readers vs retained exact viewer profile gate, default-only LAN11, authoritative rules invariant on loads, real user setting at new colony in existing Windows title flow. Identify any compatibility ambiguity requiring product decision. S04 changes raw body/current checkpoint in parallel; coordinate ownership and versioned format boundaries.
## 8. Dependencies and integration
Dependencies S19 owns package/factory behavior; S18 UI can wire selector when accessor/factory verified; S15 owns generic file prepare, S01/S16 already identity/legacy gates. Keep selectable integer state/atomic script results on M01 contract only unless actual milestone requires executing Lua now. Use existing Void facilities, flag genuinely missing upstream primitive without externally filing.
## 9. Edge cases security and performance
Risks default digest change, explicit legacy import with previously valid raw data, failing to reflect actual selected mechanics after reload, stale display code assuming staged beds, repeated loading/selection under same world seed. Need exact tests for active-world refusal on incompatible compiled profile, variant supply/bed completion, replay and v1/cross-binary.
## 10. Acceptance criteria
1. Source-grounded selected pair or better alternative with clear real effects, no cosmetic difference. 2. First implementable core task and limited follow-up UI integration. 3. Testable legacy/frozen/unchecked-catalog/canonical behavior and precise pending script contract. 4. Name any real product decisions.
## 11. Verification commands and evidence
Use git rev-parse HEAD; rg -n 'staged_beds_|start_scenario|make_first_colony|BedStage|default_rules_manifest|builtin_rule_packages' engine app tests; inspect actual pinned API when relied on. No build needed.
## 12. Constraints and stop conditions
Send first viable technical criteria early. No refactoring, remote writes, branch changes or children. If simple-bed feature is invalid by plan/source, identify a valid alternative with direct evidence instead of forcing it.
## 13. Authorization and decisions
User authorizes complete roadmap and rules selection is explicit M01 deliverable; this design reuses existing gameplay/boundaries. Root retains scope and integration choices.
## 14. Return format
Return M01-P4 READY/PARTIAL, actual source references, bounded interface/ownership design, exact verification targets, integration risks/native gaps.
+48
View File
@@ -0,0 +1,48 @@
# Verify library reuse for the first deterministic replay slice
Task ID: M01-R
Role: astra_researcher
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m00-inventory at 0deacb3. Prototype integration is 083b84e. Pin is 7b0fea6095f603f9e1904f66dfdc7752f4be4792. Pre-existing untracked .serena/ and workflow records.
## 2. Objective and deliverables
Resolve what the first M01 serial-reference/per-tick replay slice can reuse from Void, with exact upstream source/tests/Windows limitations and any genuinely missing generic contract.
## 3. Scope and non-goals
Read-only Verify. Investigate deterministic executor/reference, batching, test/replay and canonical bytes for the existing prototype. No change or new issue in this assignment.
## 4. Files to inspect
Inspect CMakeLists.txt, docs/plan/void-library.md, docs/plan/milestones/M01.md, engine/include/settlement/core/worker_pool.hpp, engine/src/worker_pool.cpp, world.cpp, world_save.cpp, tests/core_tests.cpp and the exact pin in the matching Void repository.
## 5. Write ownership and coordination
Write scope: none
Shared checkout. Root owns Git, network writes and integration.
## 6. Implementation or investigation approach
Identify and verify the actual pin and current published revision read-only. Check applicable public headers, implementations and upstream tests, including inline executor behavior, Windows dependencies and state/ordering semantics. Look up matching existing upstream issues only as needed. Use configured repo interfaces or exact git objects, no unrelated repos/credentials.
## 7. Interfaces and data contracts
Preserve old save 13 and LAN 11. Separate a game-owned reference mode or test fixture using upstream primitives from a new generic capability needing an issue. Do not prescribe an incompatible executor or assume replay tokens hash full world state.
## 8. Dependencies and integration
M00-P maps game seams. Root decides M01 scope and will link or register actual upstream gaps if a local generic capability is necessary.
## 9. Edge cases security and performance
Pay attention to partial thread start, bounded queues, zero/one-worker behavior, std::future semantics and differences from inline execution; avoid claiming untested Windows behavior.
## 10. Acceptance criteria
1. Return reuse decisions at pin with public/test evidence and actual target availability. 2. Identify alternate current upstream implementation or actual issue for gaps if relevant. 3. State runnable verification and untested contracts.
## 11. Verification commands and evidence
From game root git show HEAD:CMakeLists.txt. For matching upstream use git -C <confirmed-checkout> cat-file -e 7b0fea6095f603f9e1904f66dfdc7752f4be4792^{commit}, ls-tree and show exact header/test paths. Cite paths, commits and results. Network reads only.
## 12. Constraints and stop conditions
Stop when evidence is sufficient for the first slice. Do not fetch private data into public tools, modify deps, create issues, build a replacement library or change a branch.
## 13. Authorization and decisions
User approved milestone development and requires library-first analysis. This task is strictly evidence gathering.
## 14. Return format
Return M01-R status, decision table, exact source and tests, suggested scope/replacement checks, unknowns. Do not spawn further agents.
+48
View File
@@ -0,0 +1,48 @@
# Verify Void contracts for runtime, persistence and modules
Task ID: M01-R2
Role: astra_researcher
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home at M00 904bdf8 on milestone/m01-authoritative-simulation; initial serial/replay tranche in flight. Public Void HEAD matched CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. User wants later systems implemented as well.
## 2. Objective and deliverables
Find exact reusable Void APIs for M01 rules module/manifest dependencies and hashing, transactional saves/Windows atomic replacement, immutable snapshots/fixed clocks and idempotent command dispatch. Produce per-contract decisions so authors can begin without duplicating library code.
## 3. Scope and non-goals
Read-only evidence focused on S19/S15/S01/S16. Start by returning results for rules/manifest and atomic writes. M01-R already covered executors/replay.
## 4. Files to inspect
Inspect CMakeLists.txt, docs/plan/void-library.md, docs/plan/systems/{S01,S15,S16,S19}.md, current save codec, viewer save entry points, exact public Void pin, test and backend files and current upstream tracker. Verify source branches against pin, not co-located names.
## 5. Write ownership and coordination
Write scope: none
Root owns all network writes. Other agents own game/test files. Do not change branches or active graph.
## 6. Implementation or investigation approach
Check public API, real behavior, Windows flags and tests at pin e.g. Binary, Crypto SHA256, IO atomic replace, version/dependency graph/manifest. For each required generic gap give existing matching issue or minimal issue content, expected replacement check, local game path candidate. Distinguish domain ownership. Independently validate whether Windows build/link of candidates is feasible, no application writes.
## 7. Interfaces and data contracts
Return precise API/units, guarantees and missing pieces (including byte/string handling, version compatibility and corruption behavior). Prefer supported existing routines over new custom equivalents.
## 8. Dependencies and integration
M01-P2 handles game integration. Root decides package ownership, upstream issues and commit/push. Authenticated tool available only if needed; use read-only upstream operations.
## 9. Edge cases security and performance
Do not leak private code, real data or credentials in external queries. Treat native Windows vs cross-test explicitly. Network, sandbox and subprocess errors must be reported accurately.
## 10. Acceptance criteria
1. Runnable library reuse plan for each next M01 system. 2. Direct URLs/test paths and Windows constraints. 3. Actual tracked gaps or precise issue drafts with acceptance and migration test.
## 11. Verification commands and evidence
From game root git show HEAD:CMakeLists.txt and from confirmed pinned checkout git show 7b0fea6095f603f9e1904f66dfdc7752f4be4792:<path>. Check live git ls-remote and read-only public issues. Reference existing cross env and use source fixtures as appropriate without changing project.
## 12. Constraints and stop conditions
Do not create issues, fetch private data into public tools, or ship dependency changes. Return findings by priority, including partial early results. No children.
## 13. Authorization and decisions
User's plan requires library-first analysis, and separately authorizes authorized repository changes and branches. This task grants read-only investigation.
## 14. Return format
Return M01-R2 status, decision/evidence per feature, real gaps/practical issues and replacement criteria, current Windows evidence and unresolved questions.
+48
View File
@@ -0,0 +1,48 @@
# Replay actual colony commands and compare every tick
Task ID: M01-T
Role: sol_implementer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation based on M00 checkpoint 904bdf8. The baseline has 28 core and 4 LAN cases, reflection suites from pinned Void. Legacy task notes/.serena are untracked.
## 2. Objective and deliverables
Build an executable M01 replay regression in the normal settlement_core_tests target, exercising the explicit serial reference and normal modes on the same saved starting state.
## 3. Scope and non-goals
Own the test fixture, useful game scenarios, mode/legacy boundary assertions and minimal source registration. Keep every existing core and LAN case. No new runner or game production logic.
## 4. Files to inspect
Inspect tests/core_tests.cpp (save_contents and test_two_players_share_the_first_colony, resource/hauling and parallel job tests), tests/test_main.cpp, CMakeLists.txt, world.hpp, docs/plan/milestones/M01.md, docs/plan/void-library.md and actual game behavior.
## 5. Write ownership and coordination
Write scope: tests/replay_tests.cpp; CMakeLists.txt
You are not alone. Core owner writes only world.hpp/world.cpp/world_save.cpp. Root owns docs and Git. Do not revert their changes; serialize your new file registration in CMake yourself.
## 6. Implementation or investigation approach
Add a reflected Void Suite in NEW tests/replay_tests.cpp, register this file on existing settlement_core_tests. Mark new cases with tag replay. Use the actual write_save binary bytes as prototype oracle (no hashes or shadow codec). Record a fixed test-local set of PlayerCommand values including explicit player sequences and scheduled step attempt ordinals. Check expected receipts/rejections, tick/revision and pause/resume, then compare state bytes every attempt through meaningful colony output. See preflight requirements below.
## 7. Interfaces and data contracts
NEW frozen API settlement::ExecutionMode::{Parallel, SerialReference}; World(seed,w,h, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel); World::read_save(stream, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel). Serial requires logical count 1 and reports worker_count()==1. Parallel 2..64 and ordinary one-worker rejection remain. Invalid combinations/unknown enum throw invalid_argument. Existing PlayerCommand, CommandReceipt, make_first_colony, resource/job APIs apply.
## 8. Dependencies and integration
Core author implements the frozen API concurrently. Use an uninterrupted serial reference versus 2/6/12 from the same initial bytes. At a proven material-in-hand checkpoint resume another world per mode from bytes, keep uninterrupted reference alive and compare every subsequent tick. Use warmed path cache in the live history; report path counters and first differing tick/mode/object or byte offset if a comparison fails. Coordinate builds after both sides compile.
## 9. Edge cases security and performance
Cover empty, paused, one resident/fewer residents than workers. Include multiple competing generic jobs and an unreachable route forcing a retry to another job (all three dispatch points), and two eligible residents contending for the last item, with a specific winner and conservation after delivery/consumption. Choose meaningful positive outcomes to rule out all modes equally doing nothing. Compare bounded scenarios and avoid OS timing assertions.
## 10. Acceptance criteria
1. Reproducible command schedule advances a real colony and checks accepted and rejected commands. 2. Exact byte equality every tick for serial/2/6/12 including reload vs uninterrupted; prove in-hand stop and useful work. 3. Contention winner and unit accounting, job selection/retry, and valid/invalid configs are checked. 4. Existing tag/CTest entry points still work.
## 11. Verification commands and evidence
From game root source /tmp/stoneheart-verify.KoZwE4o8/env.sh; cmake --build /tmp/stoneheart-milestones.xprJ2SVp/windows --parallel 8 --target settlement_core_tests; wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag replay. Root built this directory from the exact clean Void pin. Report counts and time. Work with core owner if build awaits API.
## 12. Constraints and stop conditions
Do not weaken old tests, compare only hashes/final counts, edit game files, change branches, stage/commit or spawn. Investigate actual source when a fixture fails; distinguish bad setup from real divergence and inform root.
## 13. Authorization and decisions
User requested milestone implementation with subagents. This scoped M01 tranche establishes replay evidence before replacing the executor or changing the authoritative command format.
## 14. Return format
Return M01-T status, changes, fixture/expected state, counts and commands, any coverage you could not verify and integration notes. Send early if there is a real disagreement across modes.
+48
View File
@@ -0,0 +1,48 @@
# Review the serial reference and replay checkpoint
Task ID: M01-V1
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home on milestone/m01-authoritative-simulation, parent 904bdf8. User asks that reviewed milestone/system work be committed and pushed. Initial M01 tranche only. Pre-existing untracked .serena and older task files are outside the diff.
## 2. Objective and deliverables
Review the actual integrated M01-C/T source and tests; give an independent defect-oriented verdict on this checkpoint before push.
## 3. Scope and non-goals
Audit constructor/load mode, all worker dispatch paths, exact-state comparison, normal suite/CLI callers and documentation plus boundary to future work. Work on later M01 packages is planned separately.
## 4. Files to inspect
Read git diff 904bdf8 and NEW tests/replay_tests.cpp, docs/agent-workflow/tasks/M01-{C,T}.md, README and M01 plan. Check world.hpp/world.cpp/world_save.cpp, CMakeLists.txt, test_main.cpp, existing core and LAN suites against the frozen contract.
## 5. Write ownership and coordination
Write scope: none
Do not change any shared checkout files or branches. No children, push or external writes.
## 6. Implementation or investigation approach
Inspect actual worker lifetime, order, exception handling changes since baseline, empty/paused/one-resident cases, mode validation and save ingress. Review each new case for effective contention, warmed-cache checkpoint and positive useful progress. Check mode-specific reporting, new API compatibility and CMake discovery.
## 7. Interfaces and data contracts
Parallel rejects 0,1,65+ and serial admits only 1 logical lane, with zero pool threads. Preserve save13/LAN11, existing commands and parallel results. Full M01 authority/async saves belong to later packages.
## 8. Dependencies and integration
M01-C/T complete. Root observed an independent original-ABI Windows probe vs candidate serial/2/6/12, 365 attempts (361 ticks, 5 meals), 738386 bytes of saves and receipts identical bytewise. Five replay tests pass under Wine. Full CTest and build on integrated state in /tmp/stoneheart-milestones.xprJ2SVp/windows; logs m01-first-build.log and m01-first-ctest.log.
## 9. Edge cases security and performance
Check directional reference equivalence when candidates all target same work and routes retry, stable movement/jobs state and flag any newly widened lifetime risk. Native Windows/GPU remains outstanding. Do not waive failed assertions.
## 10. Acceptance criteria
1. Return verdict on first M01 execution tranche. 2. Concrete severity, affected callers, reproduction for bugs and proposed fix. 3. Report untested risks and distinguish them from observed regressions.
## 11. Verification commands and evidence
From game root git diff 904bdf8 --stat; git diff --cached --check; source /tmp/stoneheart-verify.KoZwE4o8/env.sh for any targeted read-only testing. Review /tmp/stoneheart-milestones.xprJ2SVp/{replay-tests,m01-first-ctest}.log and actual new file. Do not start a competing build.
## 12. Constraints and stop conditions
Read-only. No docs or fixes, no commit/push. Return bounded findings promptly so root can integrate and continue the active goal.
## 13. Authorization and decisions
User authorizes implementing, committing and pushing each milestone/system. This review covers the first M01 tranche and does not declare the milestone complete.
## 14. Return format
Return M01-V1 READY/CHANGES_REQUIRED/INSUFFICIENT_EVIDENCE, findings by severity/location, observed checks, unrun checks and remaining milestones.
+48
View File
@@ -0,0 +1,48 @@
# Audit the live LAN owner bridge and interactive session integration
Task ID: M01-V10
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S16-02 in isolated /home/faumaray/Projects/stoneheart_at_home-worktrees/s16 based 8c4c1fe. Contracts S16-02 and M01-F5 closed peer+epoch issues. S18-01 in sibling s18 has reviewed S15 a063894 merged, viewer in progress; LAN candidate will enter its checkout after review. One independent review per product path.
## 2. Objective and deliverables
Review actual S16 adapter now for branch integration. Later when root supplies final S18 commit/diff and evidence review normal Win32 entry for events, snapshots, async files and lifecycle, with separate verdicts.
## 3. Scope and non-goals
Only S16 compatibility host/guest integration and S18 normal client wiring. Legacy protocol remains 11. No public additional transport or deployment.
## 4. Files to inspect
Inspect s16 tracked diffs app/lan_session.hpp/.cpp, tests/lan_tests.cpp, docs S16, frozen runtime header and actual command/snapshot logic. S18 later inspect actual all new viewer_session code/tests and viewer_win32.cpp, CMake, S15 CheckpointFiles and normal entry + smoke. Read M01-F4/F5 and the assignments.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children/project switches. Other workers own code. Use direct source for isolated worktrees. Ignore their summaries until checked.
## 6. Implementation or investigation approach
S16 validate default-only authenticated legacy slot, session replacement, coalesced/wrong/rejected old sequence vs modern next_requests, pending future capacity/incarnation/peer tags, reconnect with in-flight owner mutation, truthful Wire11 receipt and first snapshots, consumer of take_result accept/reject vs prior take_rejection, correct future lifetime and no blocking poll on game work. Cross-verify old/no default rules or disconnect and correct generation in actual state transitions.
## 7. Interfaces and data contracts
S18 later validate consistent immutable world on paint/menu including nested window callbacks, pumped title/modal completions, no per-reset UI join, one file service check latest ticket + dimensions/supported rules, healthy save capture max, correct current epoch after commands, reject and retain draft, receipt routing and bounded local IDs, short locks and cleanup, actual normal new/continue/title load and LAN. No live mutable world assignment through UI.
## 8. Dependencies and integration
Root merges S16 into S18 to actually build/test full client after S16 review. S18 source is incomplete initially; do not approve unseen future work. Public test port uses loopback only. Native acceptance separate.
## 9. Edge cases security and performance
Check state across TCP rebind and network packets/receipts allowed on aborted session. Saturation/old guest fixed sequence, authoritative exceptions. UI must handle busy/faulted futures, avoid stale changes after failed newer load, process-level save ordering and bounded memory. Compare baseline behavior only within approved compatibility.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per phase with concrete sources and triggers. 2. First confirm real 5/5 lan-owner, 92/92 core, 9/9 LAN and original/new binary interop in both directions. 3. S18 after actual signoff + build/smoke logs; name any missing evidence for end-to-end status.
## 11. Verification commands and evidence
git -C s16 diff --check; inspect /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-final-{build,ctest,tag}.log and lan-owner-interop.{cpp,py,log}. For S18 compare named parents once available and logs client-* in shared temp dir. Read-only inspection only.
## 12. Constraints and stop conditions
Return S16 review early. If blocked by outstanding S18 dependency, confirm stage A and await final evidence without premature approval. Inform root immediately of a verified actionable defect.
## 13. Authorization and decisions
User authorizes complete plan and system/milestone commits/MRs accumulating on roadmap. Root owns external actions/normal integration.
## 14. Return format
Return M01-V10 separate S16/S18 findings with actual tests, changed paths and limitations. No children.
+48
View File
@@ -0,0 +1,48 @@
# Review the independent executor and rule package changes
Task ID: M01-V2
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Milestone integration root /home/faumaray/Projects/stoneheart_at_home at 8d2870a. Actual candidate worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s01,s19} both based on 8d2870a. S01-02 and S19-01 have test evidence, root owns integration.
## 2. Objective and deliverables
Independently review each actual system diff and return separate merge-ready verdicts. Include new untracked files, not only git diff or implementer summaries.
## 3. Scope and non-goals
Check correctness/regressions/compatibility and possible new test defects in the two bounded packages. Scope excludes later authoritative runtime and native release acceptance.
## 4. Files to inspect
Inspect each worktree's docs/agent-workflow/tasks/{S01-02 or S19-01}.md, CMakeLists.txt, new engine/src/rules_manifest.cpp/public header, rules_tests.cpp, worker_pool.*, world.cpp/world_save.cpp/world.hpp, tests/executor_tests.cpp and replay_tests.cpp. Use exact upstream headers at pin in /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
## 5. Write ownership and coordination
Write scope: none
No edits, branch/Serena switching, new builds, network writes or children. Worktrees are isolated; check cwd for each.
## 6. Implementation or investigation approach
S19 inspect public API and actual bounded StrictJson handling, duplicate key/definition/ID diagnostics, exact SemVer incl build, canonical SHA of simulation content, order permutations, dependency closure and conflicting providers, malformed constructs and failure diagnostic. S01 inspect task capture lifetimes and guard destruction order, reserved capacity, overload retention, stop/start/error handling, expected/future semantics, partial startup, nested dispatch assumptions, injected tests and threading on Windows.
## 7. Interfaces and data contracts
Verify original M01-C replay public default behavior and format13/LAN11; new rule identity needed by S15. User expects appropriate Void APIs and references for gaps (#4 resolver). Check public compile/link feature propagation and competing CMake edits for root.
## 8. Dependencies and integration
Evidence for S19 in /tmp/stoneheart-milestones.xprJ2SVp/rules-final-*.log (9 tagged +42 core/4 LAN). S01 build /tmp/stoneheart-milestones.xprJ2SVp/executor-build; additional capacity-one replay and throwing move case being finalized with original 5 normal replay cases. Baseline 33 core/4 LAN. Root owns final integrated CMake and each system commit.
## 9. Edge cases security and performance
Inspect actual changed and new lines before verdict. Avoid assigning unchanged historical limitations as new bugs; label native filesystem/Windows physical checks outstanding. Read-only isolation excludes shared Serena switching. Capability process notes are not test evidence.
## 10. Acceptance criteria
1. Separate S19 and S01 verdicts, P0–P3 real issues with reproduction/locations/fixes. 2. Verify evidence and exposed contracts. 3. Report integration risks and targeted regressions. Give early S19 verdict to unblock persistence integration.
## 11. Verification commands and evidence
Run git -C <actual-worktree> diff 8d2870a --stat and git -C <worktree> status --short; read the actual new files. Review each ctest log and check git diff --check. Optional existing binary smoke under known Wine env; no competing rebuild.
## 12. Constraints and stop conditions
Do not approve unseen final changes, or perform external or repo writes. Stop once bounded evidence suffices and send findings early.
## 13. Authorization and decisions
User authorized branch-per-system development, commits and pushes. Root requested independent final review.
## 14. Return format
Return M01-V2 verdict for each branch, findings with severity/observed effect, verification and anything unrun. No application edits.
+48
View File
@@ -0,0 +1,48 @@
# Recheck executor teardown and integrated system target linkage
Task ID: M01-V3
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Root at de38aff S19; s01 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 based on 8d2870a. M01-V2 accepted all production paths and S19; P2 concerned only promises and shared future destroyed before WorkerPool joined on assertion unwind.
## 2. Objective and deliverables
First re-review the one-line test lifetime repair in s01 and its rebuilt evidence. Then when root sends the staged integration, verify actual combined target graph for S01+S19 and any contemporaneous reviewed S16/S15 layers expressly identified.
## 3. Scope and non-goals
Independent read-only review of precise previously identified risk and later integration overlap. Code/design outside changed boundaries retains its separate reviews.
## 4. Files to inspect
Inspect s01/tests/executor_tests.cpp test_capacity_retains_move_only_work_and_exceptions, s01/docs/plan/systems/S01.md and M01-V2. Integrated CMakeLists.txt, test registry, system target interfaces, actual git staged merge. Root provides integration refs/results at that point.
## 5. Write ownership and coordination
Write scope: none
Do not mutate checkouts, shared Serena or Git. Others own code; report findings only.
## 6. Implementation or investigation approach
Reason through reverse destruction on early failure, ScopeExit ordering, async future captures. Consult actual targeted runner log and receipt; send READY/CHANGES_REQUIRED per component. Later verify merge parent trees and union of observed features without re-reviewing unchanged code.
## 7. Interfaces and data contracts
Core composable Windows consumers need transitive public Void::Async (cxx_std_26) and other headers' dependencies. Retain pure SHA, correct enabled modules, all sources/cases including executor/rules/replay. New S01/S19 docs report actual benchmark with Windows/Wine scope.
## 8. Dependencies and integration
Root owns merge, CMake conflict resolution, clean build and pushes. First verdict unblocks the branch commit. Remain available for integrated changes.
## 9. Edge cases security and performance
Reversed destruction must keep promises, shared_future and borrowed worker data alive through join; guard releases before join. No native Windows or performance overclaims.
## 10. Acceptance criteria
1. Live source + actual rerun validate lifetime finding. 2. For integrated stage identify any lost component or unintended changes in overlapping files and verify real aggregate suite counts. 3. Report verdict separately per stage.
## 11. Verification commands and evidence
Use git -C <s01> diff --check; read test lines 104–136 and /tmp/stoneheart-milestones.xprJ2SVp/executor-recheck.log (8 of 8), root reran CTest core and LAN PASS. At stage two use git -C <root> diff --cached --stat and inspect actual CMake vs named parents, link/test results root sends.
## 12. Constraints and stop conditions
No edits, new roles, external writes, branch changes or builds touching worker build dirs. Stop on uncovered shared behavior or missing evidence.
## 13. Authorization and decisions
Parent authorized this follow-up to M01-V2 on the specific finding; full roadmap scope permits integration after evidence.
## 14. Return format
Send first verdict immediately; second when integrated staging and results are available. Findings severity, location, impact, fix and actual evidence.
+48
View File
@@ -0,0 +1,48 @@
# Review accepted-command retention and Windows save publication
Task ID: M01-V4
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Separate isolated worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s16,s15} at 8d2870a. S16-01 and S15-01 each add a concrete service + tests. S16 build 43 core/replay/session incl ten session and four LAN, native Win32 writer verification finishing. M01-F3 accepted contracts. Root owns Git and app integration.
## 2. Objective and deliverables
Perform fresh defect-oriented independent audit of both actual diffs. Send S16 signoff/finding early and S15 when its final test run finishes. Initial review covers independent component behavior for subsequent integration.
## 3. Scope and non-goals
Read-only S16 and S15 actual code and new paths, test quality, CMake/public API, NFK Windows error semantics. Later integration review is separate. No UI, scheduler or broad networking architecture.
## 4. Files to inspect
In each isolated checkout inspect git diff + git ls-files --others --exclude-standard; source/header/tests for command_dispatcher, save_service_win32, session_tests, save_service_tests and CMakeLists. Read S15-01/S16-01 there and M01-F3 in root. Read actual World::apply_command, queue_cabin, pinned Void Async/Uuid/FuturePool, and original synchronous viewer save as needed.
## 5. Write ownership and coordination
Write scope: none
No mutations, branch actions, builds into active build dirs, shared Serena activation, external writes or children. Reviewers did not implement either change.
## 6. Implementation or investigation approach
S16 reserve before effects; exact complete payload comparison; bounded cached accepted/rejected receipts; trusted separate player, UUIDs and city; valid new request mapping, out-of-order detection and paused/prior-world exact repeats; Before/After fault observer must poison uncommitted ledger and expose previous commitments only. Confirm all domain input validities incl extreme coordinates before arithmetic. S15 inspect FIFO identity, concurrent submission reentrancy, producer ownership on acceptance/rejection/completion, no writes before validation, bounded work/bytes, OS-level staging ownership/exclusive temp, close/flush/publish point, recovery and shutdown.
## 7. Interfaces and data contracts
Independent API must give strong failure boundary, cloneable dispatcher with candidate staging and exact unchanged legacy format13/LAN11. S15 single writer, atomic same-directory replace; share denial may return prepublication failure, preserving old bytes. Requiring replace-through-held-handle across all Windows filesystems is outside game contract. For that specific error test prove visibility flags, unchanged old data and next success after closing.
## 8. Dependencies and integration
Root merges CMake with other branches preserving Void::Core public and previously reviewed Async/Rules. Later runtime consumes these primitives; no new native/cross-platform durability claims. Compare upstream actual API and latest registry before raising feature gaps.
## 9. Edge cases security and performance
Check exception surfaces, future lifetimes, retained failures, no success exposed after partial domain mutation, no unsafe catches/rolled-back state claims; UUID/session fence; Windows Unicode paths, sharing, race before/after rename, close errors, relative path rejection and whole contents for readers. Do not equate program-crash publication with durable power-loss protection.
## 10. Acceptance criteria
1. Separate scoped READY/CHANGES_REQUIRED for S16 and S15 with actual locations/impacts. 2. Compare accepted F3 contracts to implementation incl test-on-failure cleanup and producer concurrency. 3. Check real tests, counts and flags. 4. Distinguish legacy limitations from introduced bugs.
## 11. Verification commands and evidence
From each checkout git diff --check; git status --short; inspect explicit new files and matching ranges. /tmp/stoneheart-milestones.xprJ2SVp/session-final-{build,ctest,tag}.log and /tmp/stoneheart-milestones.xprJ2SVp/save-build/Testing/Temporary/LastTest.log and final save-tag/build logs when ready. All computed tests Windows x64 under Wine.
## 12. Constraints and stop conditions
Read only. Return actionable findings immediately. No external writes or blind reruns. If either component needs a repair, identify distinguishing check before re-review.
## 13. Authorization and decisions
User authorized plan, system branches and remote MRs to main. Parent retains authority to publish and rechecks merged components. Review doesn't approve main merge.
## 14. Return format
Return M01-V4 S16 and S15 independently, actual files and tests inspected, severity/code location/rationale for any defect, native and integration gaps.
+48
View File
@@ -0,0 +1,48 @@
# Audit snapshot ownership and checkpoint compatibility
Task ID: M01-V5
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S01-03 actual implementation in /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 at 68f91a2, S15-02 in ../stoneheart_at_home-worktrees/checkpoint detached de38aff. They independently implement immutable owner captures and persisted modern envelopes. Other reviewers cover writer/dispatcher and past S01/19. M01-F3 remains controlling for failure/publication.
## 2. Objective and deliverables
Read-only final independent review of both real source diffs before branch commits. Send per-branch verdicts early. Later integration will be separately verified.
## 3. Scope and non-goals
Review exact changed snapshots/logical field partitioning/lifetime and checkpoint/rule catalog extraction/format gating, tests/limits/headers/CMake. No runtime owner or future custody field required from these narrow slices.
## 4. Files to inspect
Each worktree git status, git diff (tracked changes), explicit new files. Review world.hpp/.cpp, snapshot_tests.cpp, surrounding const rendering/WorldSaveCodec, checkpoint.hpp/.cpp, checkpoint_tests.cpp, rules_manifest.hpp/.cpp, target and actual pinned Void Binary/SHA/Uuids. Read S01-03/S15-02.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children, shared Serena project stays at main game. Direct check worktree source and evidence; you are not an implementer.
## 6. Implementation or investigation approach
Snapshot: reason about every logical field vs executor/cache, copied nested state and observability, no callbacks/pool/references retained, C++ construction/copy/move/const escape/lifetime on exception, no silent public ABI caller break. Checkpoint: check endianness/checksum coverage, length/overflow/allocations before validation, bounded work/memory, no eager megabyte unbounded allocations for tiny malicious body, compare entire installed closure order-independent, identity/tick matching, unsupported versions/trailing data, SHA >16 MiB, named error, independent candidate.
## 7. Interfaces and data contracts
Existing raw save13/LAN11 APIs and exact bytes unchanged. Running captured world is read-only. Modern binary envelope has stable nonnil UUID/city/rules/tick, current body on existing serializer, no on-disk active session/ledger. CMake public types propagate Void::Core.
## 8. Dependencies and integration
Root owns CMake/Git and cross-component integration. S01 path will underpin renderer/background saves, S15 prepares candidate; do not claim they're connected in this slice. Fresh win native/physical tests unavailable here.
## 9. Edge cases security and performance
Investigate invalid input triggering count-based huge allocations despite small outer blob, default/moved-from rules objects, empty rule sets whether legal in resolver, stream consumption/trailing and portability. Catch definite problems in changed surface; distinguish historical legacy-parser behavior. Snapshot test failure-path lifetime/drain warrants attention.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. Identify file and precise trigger/consequence for defects and proposed focused regression. 3. Report current actual build/test evidence and any unverified claims.
## 11. Verification commands and evidence
git -C <wt> diff --check; inspect new files with real paths, /tmp/stoneheart-milestones.xprJ2SVp/checkpoint-{build,ctest,tag}.log (8 checkpoint, 50 core and 4 LAN). S01 capture is 4 snapshot plus full suites and benchmark in same temp folder as capture-* when available. No rebuild needed.
## 12. Constraints and stop conditions
Remain read only; send urgent actionable findings after validating reachability. No speculative redesign, external actions or other agents.
## 13. Authorization and decisions
User approved roadmap and PRs. Parent owns commits/push and review acceptance; local independent branch certification doesn't approve merging main.
## 14. Return format
Return M01-V5 S01-03 and S15-02 verdicts, actual evidence, limitations and any re-review scope. Send first ready ASAP.
+48
View File
@@ -0,0 +1,48 @@
# Verify the combined M01 systems and preflight stable storage references
Task ID: M01-V6
Role: astra_reviewer
Status: READY
## 1. Context and baseline
M01 main worktree /home/faumaray/Projects/stoneheart_at_home commit 2224299 vs earlier integrated cf0cc2f. Reviewed component tips 84a78ef S16, fd17a2f S01 capture, 3844ebb S15 writer, 15da3f4 S15 checkpoint (parent de38aff S19), combined S15 db4ac30. Reviews M01-V4/V5. Separate prospective S06 slice proposed by M01-P3 planner.
## 2. Objective and deliverables
First adversarial integration audit of 2224299 and db4ac30, including actual target union and cross-file operating limits. Second, read-only preflight for replacing runtime positional storage/node references with existing durable IDs. Separate verdicts.
## 3. Scope and non-goals
Only S01/S15/S16/rules integrated surfaces and upcoming first S06 migration. Owner/runtime not yet in integrated commit. No implementation.
## 4. Files to inspect
Inspect git diff cf0cc2f..2224299, all merge parents, s15 CMake db4ac30, primary headers checkpoint/save_service/world/command_dispatcher/rules_manifest and normal callers; logs. For S06 World::edit_object/gather/assign/finish, Agent/MaterialReservation/ConstructionStop, WorldSaveCodec::body/validate/load, viewer resident detail, tests.
## 5. Write ownership and coordination
Write scope: none
No mutations, branches, external actions, children or shared Serena switching. Other agents own future changes, compare named commits only.
## 6. Implementation or investigation approach
Audit merged code vs exact source commits for lost fields, ABI or modules, transitive flags; verify actual native-target build reports core tag counts and compatibility. Check whether max_checkpoint_bytes and SaveService limits align for explicit caller config, typed capture/dispatcher/codec work together. Record any unmet obligations to runtime instead of claiming integration already wired.
## 7. Interfaces and data contracts
First S06 proposal: stored Agent/MaterialReservation/ConstructionStop references to existing sorted Storage.id/ResourceNode.id migrate from index/sentinel to nonzero actual ID/zero none in live memory; bounded lookup via lower_bound or equivalent. Legacy byte layout retains positional fields only inside WorldSaveCodec: stage raw positions during deserialization in separate bounded temporary structures, resolve against fully parsed pools before domain validation; encode inverse mapping and reject invalid refs before writing. Existing public code/callers updated where needed; vector order/indices are transient iteration only. Stable production, transfers and item IDs follow separately. Verify there is no non-reference zero or order interaction that breaks this. Present recommendations for const accessors/source compat as needed.
## 8. Dependencies and integration
Run-time 20Hz, UI/file/lifecycle wiring and larger S04 IDs are future; new S06 can progress with disjoint package files while runtime owns separate files. Root merges/updates Gitea. F3 controls fault bounds. No branch push from reviewer.
## 9. Edge cases security and performance
Review save13/LAN11, root's complete CMake stack and old caller behavior. S06 legacy unordered/invalid data, max sentinel, moving/deleting unrelated earlier elements with active reservations; encoding cost O(N log M) not quadratic searches. M00 goal records nonempty demolition intentional confirmed by human choice; any accounting change separate.
## 10. Acceptance criteria
1. Separate integrated READY/CHANGES_REQUIRED with actual evidence 82/82 core and 4/4 LAN; S15 59/59 +4. 2. First S06 task READY/needs correction with concrete narrow stop conditions and reproducible tests preserving canonical save13. 3. No approval of unseen runtime or native acceptance.
## 11. Verification commands and evidence
git diff --check cf0cc2f..2224299 and git show --cc db4ac30; compare source blobs to each branch, inspect /tmp/stoneheart-milestones.xprJ2SVp/{m01-candidates,s15-combined}-{build,ctest}.log. For S06 inspect real world/codec/HUD paths via targeted graph + source, reachability and smoke fixture behavior.
## 12. Constraints and stop conditions
No edits/builds/Git/remote mutations. Send integrated review immediately. Stop if older valid format or dependency would force distinct migration beyond current scope. Return actionable findings, no speculation.
## 13. Authorization and decisions
User authorizes all system/milestone branches, commits/push and merge requests into main. Root alone publishes cumulative integration. This is final integrated review plus prospective S06 technical gate.
## 14. Return format
Return M01-V6 two verdicts: integrated M01+S15 and S06 preflight. Evidence, limits, actions and native gaps.
+48
View File
@@ -0,0 +1,48 @@
# Recheck S06 allocation limits and audit the simulation owner
Task ID: M01-V7
Role: astra_reviewer
Status: READY
## 1. Context and baseline
M01-V6 accepted system assembly 2224299 but required one S06 design correction. New task S06-01 is in /home/faumaray/Projects/stoneheart_at_home-worktrees/s06 at a4cf99c. Runtime S01-04 implementation is in sibling s01 worktree at 2224299. Reviewer did not implement it.
## 2. Objective and deliverables
First confirm that revised S06-01 resolves the sole preflight finding. Then independently inspect the actual integrated runtime/World/command/clock/publication contracts and new tests before its branch push.
## 3. Scope and non-goals
Stage A preflight limit/failure invariants only. Stage B actual S01-04 core changes, CMake, tests and docs. UI/transport/disk integration not yet present.
## 4. Files to inspect
Read s06/docs/agent-workflow/tasks/S06-01.md sections 6–10 and World allocation positions, S01-04 spec and new simulation_runtime.hpp/.cpp, runtime_tests.cpp, CMakeLists.txt, docs/plan/systems/S01.md. Check previous M01-F3, S16 receipt staging, load API, const captures, pinned headers with actual worker join/clock behavior.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children or shared Serena switching. Use direct actual isolated sources (outside graph). Parent owns all fixes.
## 6. Implementation or investigation approach
A. Confirm MAX terminal, allocation MAX-1 publishes successor MAX before exhaustion, use checked successor before vector/terrain effects, factory overflow vs command Busy, loaded MAX valid, include direct field/mine + add_storage/PlaceStorage. B. Critique single owner restart/load and epoch ordering, short locks, healthy/faulted snapshot read, receipt transaction, active+queued completion and shutdown, fixed deadlines across pause/suspend/exhaustion, concurrency, manual-clock tests and real worker drain.
## 7. Interfaces and data contracts
Read actual SimulationRuntime new header, RuntimeSubmission/Result, LoadTicket, commit/wakeup and scheduling code. Freeze public API only if no correctness gaps. Record how caller retries transient Busy and obtains new contiguous IDs after completed rejects; latest snapshot meta must agree with committed ledger. Check latest request vs current epoch immediately before installation and preserve old publication on failed install.
## 8. Dependencies and integration
Root owns integrations. S06 work begins on stage A verdict. S01 acceptance is limited to tested core; GUI/S15 adapter must acquire healthy immutable save capture and limit bytes. Platform is Windows x64 under Wine.
## 9. Edge cases security and performance
Look for timing regressions from owner using admission clock timestamps, unchecked overflow, transaction window with visible successes after fault, queued mutators in faulted state, settlement of pending loaders/receipts, captured aliases and mutex hold during disk/tick/owner join. Check repeated and failed calls on background owner and teardown.
## 10. Acceptance criteria
1. Return stage A feasibility verdict immediately and stage B independently. 2. Compare source+tag tests to F3 and all required observability/fault/stale boundaries. 3. Report any reachable defect with cause and precise regression. Native acceptance separate.
## 11. Verification commands and evidence
use git -C s01 diff --check; read new files, /tmp/stoneheart-milestones.xprJ2SVp/runtime-{final-build,final-ctest,final-tag}.log. Run no competing builds. For A inspect new contract plus actual world.cpp 396–425, 770–803 and world_save.cpp validation.
## 12. Constraints and stop conditions
Read only. Stop if phase evidence not ready, but return the other independent verdict first. Contact parent for code changes and bounded follow-up if needed.
## 13. Authorization and decisions
User authorizes roadmap, pushes, MRs and upstream issue tracking. Root requests corrected preflight and fresh code review before integrating core runtime. No external actions by reviewer.
## 14. Return format
Return M01-V7 A/B READY/CHANGES_REQUIRED with file/location/evidence, expected symptoms/urgent fixes, counts and residual native/UI risks.
+48
View File
@@ -0,0 +1,48 @@
# Audit the storage and resource identity migration and file adapter
Task ID: M01-V8
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S06-01 isolated worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s06 baseline a4cf99c, separate S15-03 in s15 baseline 8c4c1fe. M01-V6 and corrected V7 preflight S06. M01-F4 accepted S15-03. Both packages have single owners; this reviewer is independent.
## 2. Objective and deliverables
Verify S06 actual full migration/legacy bytes and then S15-03 actual file reader/writer adapter implementation when ready. Give independent per-branch verdicts with real evidence.
## 3. Scope and non-goals
Read-only two component reviews; do not infer viewer is wired or production/stack identity finished. Scope new code only plus changed cross-file contracts.
## 4. Files to inspect
Inspect git diff/status plus new files in both worktrees, actual WorldState/World/WorldSaveCodec/body/validate/HUD/identity_tests and S15 checkpoint_files header/source/tests, SaveService/modern envelope and project tasks. Compare against pinned Numeric/Async/UUID and actual command/loader callers.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children or shared Serena switching. Others own code. Read exact worktree files directly if outside graph.
## 6. Implementation or investigation approach
S06 exhaustively check migration sites including partial no-ref (tending, meal), erase/shift, validated sorted IDs and lower_bound, no deref absent pointers, constructor/command MAX and MAX-1 behavior before effects including mine changes/command sequence, codec preserving old positional bytes, loading malformed pool order/IDs/dangling refs before validation without out-of-bounds. Review real tests and any new allocations/complexity.
## 7. Interfaces and data contracts
S15-03 check one handle path read under bound incl growth/trailing/truncation/EOF, modern magic + bad version cannot downgrade to legacy, fresh stable legacy UUID and default compatible rules, load future and diagnostic/caller action, max_checkpoint_bytes writer, one bounded reader queue plus in-flight, concurrent shutdown, no live worker pointers, progress of writer while reader stalled, snapshots/futures release resources safely under failures.
## 8. Dependencies and integration
Root merges S06 and S15 work; UI and other packages are independent. If S15 not ready yet send S06 verdict first; parent will provide ready files/logs. Per-component review only; native Windows integration later.
## 9. Edge cases security and performance
Check actual pre/post baseline bytes and high-water exhaustion semantics; preserve intentional demolition behavior. Inspect kernel calls and archive validation handling hostile/malformed data defensively. Guard test teardown and multi-GB file size observations. Do not equate program exit with physical durability.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. Report precise reachability + fix/regression for material issues. 3. Check observed test completeness, external trajectory compatibility and tool limits. 4. Name additions needed before combined normal entry.
## 11. Verification commands and evidence
git -C each worktree diff --check; inspect /tmp/stoneheart-milestones.xprJ2SVp/identity-{build,ctest,tag}.log and identity compat/trajectory binaries using wc/sha256sum. file-adapter-{build,ctest,tag}.log when ready. Check newly added files not yet staged for whitespace if appropriate.
## 12. Constraints and stop conditions
Read only. No competing builds. Send an early confirmed finding or verdict on S06. Report S15 only against complete available implementation.
## 13. Authorization and decisions
Root requested two independent checks, user authorizes roadmap system branches/MRs and cumulative pushes. Root retains mutation authority.
## 14. Return format
Return M01-V8 two scoped reported verdicts, real files/commands/counts, untested native or integration requirements and re-review scope.
+52
View File
@@ -0,0 +1,52 @@
# Verify merged logistics references and preflight modern production identities
Task ID: M01-V9
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Main checkout milestone/m01-authoritative-simulation c2d9d8d (parents 512c9ef, S06-01 8260e09); S01-04 integrated at 8c4c1fe. Reviewed S06 and compatibility corpus M01-V8. Next owner migration M01-P3 calls for persistent production IDs in S04 while legacy format13 remains stable.
## 2. Objective and deliverables
Independently verify merged S06+runtime and preflight the concrete S04-01 modern identity + codec migration. Send integration verdict early.
## 3. Scope and non-goals
Integration of actual components only, no assumption viewer already uses runtime. Preflight production IDs only, no broad transfer registry or new region architecture.
## 4. Files to inspect
Inspect git diff 512c9ef..c2d9d8d, both parents and CMakeLists.txt, WorldState/world.hpp, world.cpp, world_save.cpp, checkpoint.hpp/.cpp, S06 identity tests, normal consumers, compat traces. S04 plan M01-P3, existing save13 and checkpoint-v1 writer/parser plus legacy import adapter in s15.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote writes/branch ops/children or shared Serena activation. Other workers continue on their own worktrees.
## 6. Implementation or investigation approach
Verify application blob equality vs reviewed S06 apart from merged CMake and actual registrations/linkage: Math for checked_add, Time public for runtime, tests identity/runtime all active. Analyze unsupported legacy boundary for next stage and identify every order insertion and caller that must reserve a whole ID batch before normal return.
## 7. Interfaces and data contracts
S04-01 proposal: ProductionId nonzero, stored ProductionOrder::id, Agent::production_id (0 absent) and copyable persistent WorldState::next_production_id_. All three insertions (queue_production + two PlaceRoom loops) and every recipe/room/cabin batch share checked allocation, sorted ID vector/lower_bound; valid MAX next terminal never wraps. No partial ordinary acceptance/rejection. Reuse Void Numeric checked operations, upstream #7. Existing raw World::write_save default still v13, exact position projection for older readers; explicit modern raw body v14 includes order IDs, next counter, durable agent refs. Checkpoint encode becomes v2 using v14; decode preserves authentic v1 + old bodies incl valid old legacy imports and rejects inconsistent v2 body / bad version/IDs. New modern canonical replay includes all durable fields; old files import IDs deterministically in vector order with next greater than all. Game session/UUID untouched. Reject duplicate/zero/dangling/current ID, invalid/exhausted batch before mutation; erasing highest then reloading modern snapshot must not reuse it. Isolated S15 file signature classifier uses shared envelope magic, keep unchanged. Legacy wire13 loss of new auxiliary ID history accepted only at its explicit export boundary.
## 8. Dependencies and integration
Root owns cross-component integration. S06 and S04 touch shared World/serializer, so sequence them. Viewer branch will update one resident production lookup during merge; avoid changing S18 normal UI design. Existing legacy public code and normal current renderer must keep working. Require exact statement if prior v1 had stricter/looser body behavior.
## 9. Edge cases security and performance
Inspect O(NlogN) lookup, checked arithmetic including batches; post-decode forward reference resolution; cache/loader behavior incl ordering. How to preserve old test fixtures while schema bumps: freeze old known bytes with successful read. No overwriting current schema fixture pretending compatibility. Watch allocation without effects vs retry/reporting in dispatcher (must preserve world when returning Busy).
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per integrated S06 and S04 preflight. 2. Concrete blockers/acceptance e.g. continued mid-carry world, removed order before unrelated active target, MAX-1 vs >=2 batch, wrong outer/inner pairing, replay serial/2/6/12. 3. Report real aggregate evidence 99/99 core+4 LAN; use old/new binary comparisons from S06.
## 11. Verification commands and evidence
git diff --check 512c9ef..c2d9d8d; git show -m --stat c2d9d8d, compare selected paths to 8260e09 and 512c9ef, inspect actual /tmp/stoneheart-milestones.xprJ2SVp/m01-identity-{build,ctest}.log and identity compat hashes, scoped source/caller reads. No builds needed.
## 12. Constraints and stop conditions
Read only. Send confirmed integration verdict promptly, then preflight scope. No speculation without source validation.
## 13. Authorization and decisions
User authorizes all milestone/system development, pushes, PRs and upstream linkage; parent retains publication/merge authority. These are final integration and design gates.
## 14. Return format
Return M01-V9 integrated and S04 preflight verdicts separately, concrete failure scenarios/test boundaries and unverified native state.
## Additional merge under review
The root subsequently merged the independently reviewed S15-03 commit `a063894` into `c2d9d8d`, producing `4ba64f7` with an automatic CMake merge. Check the added checkpoint file service, classifier, test registration and their actual blobs against the S15 parent alongside the integrated stable-reference codec. Verify `git diff --check c2d9d8d..4ba64f7` and the real `m01-files-{build,ctest}.log` under the same verification directory. The combined suite passed 106 core and 4 LAN cases. Send this bounded verdict separately under the same read-only restrictions.
+50
View File
@@ -0,0 +1,50 @@
# Adopt the pinned Void executor and drain each simulation batch
Task ID: S01-02
Role: astra_implementer
Status: READY
## 1. Context and baseline
Exclusive worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s01, system/s01-simulation at 8d2870a. Main working directory belongs to another task. Serial+replay passed at 8d2870a. Precise M01-R/R2 upstream pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. M01-F2 approved below failure tests.
## 2. Objective and deliverables
Replace the homegrown WorkerPool thread/queue implementation with pinned Void::Async::ThreadExecutor + FuturePool. Preserve existing World parallel and serial outcomes, guarantee lifetime of all admitted batch tasks across exceptions, and demonstrate useful-work/latency effects.
## 3. Scope and non-goals
Scope S01 executor migration only. No UI, scheduler, S15 persistence or gameplay redesign. Keep public submit(std callable)->std::future<Result> and thread_count() compatibility where useful; small game-specific pressure/fault seams allowed for real observations.
## 4. Files to inspect
Inspect engine/include/settlement/core/worker_pool.hpp, engine/src/{worker_pool,world}.cpp three submissions, engine/include/settlement/core/world.hpp, tests/replay_tests.cpp, benchmarks/colony.cpp, docs/plan/void-library.md. Upstream headers and tests pinned in /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
## 5. Write ownership and coordination
Write scope: engine/src/world_save.cpp; tests/replay_tests.cpp; engine/include/settlement/core/worker_pool.hpp; engine/src/worker_pool.cpp; engine/src/world.cpp; engine/include/settlement/core/world.hpp; tests/executor_tests.cpp; CMakeLists.txt
Not alone. All writes only to named branch/worktree using explicit workdir or absolute paths. Other systems have separate checkouts, root merges CMake. No change of shared Serena project, Git commits or branch switches.
## 6. Implementation or investigation approach
Use Void::Async::ThreadExecutor::create/start and FuturePool::try_submit. Preserve original count>=2 for legacy pool and zero pool in serial. Choose explicit non-dropping policy for overloaded work (e.g. synchronous invoke/future of untouched callable); stopped/error distinguishable. Use per-batch lifetime guard or equivalent that waits ALL accepted work before locals unwind for later submit/first-future exception, reserve storage before submissions. Keep stable result order, avoid extra tasks in serial and stop/join exactly once. Verify startup/queue exceptions against actual API, zero duplicate result. The public Async usage requirements must reach consumers whose headers include Void. Only add module Async and necessary transitive closure.
## 7. Interfaces and data contracts
Existing worker adapter remains game-owned translator of Void contract. NEW test fault/pressure settings should be minimal, e.g. create worker with capacity 1 and a start hook; preserve ordinary defaults. Determine actual original exception type/semantics and deterministic error behavior. Reject waiting on the same worker's own execution. Provide runner-exercised integration proof for World using migrated adapter.
## 8. Dependencies and integration
Root owns authoritative runtime and remote issue filings; use supported pinned executor, no new generic thread pool. Initial core/replay state 33 core +4 LAN. New tests are in existing core suite and tagged executor. Compile in your own system worktree.
## 9. Edge cases security and performance
Required failures: capacity saturation with retained move-only callable, propagation of callable exception, start failing after a thread already launched, destroyed pool drains admitted work, capture lifetime survives later admission/future exceptions. Avoid polling sleeps in concurrency tests; use promises/latches/barriers with bounded waits. No OS-specific perf assertions.
## 10. Acceptance criteria
1. All old and replay tests pass. 2. Fault/pressure/drain tests prove no lost work or surviving task at unwind, including world/batch paths. 3. Small/larger existing colony benchmark runs with a fixed seed compare before/after completed work and timings, clearly labeled Wine (historical native times only contextual). 4. Include any observed regression or residual failure boundary; preserve old path as historical baseline.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/executor-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. Select --tag executor and --tag replay under Wine. Use 50/500 residents 6 workers with existing benchmark.exe for measured comparisons against /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_colony_benchmark.exe; report work and 32 warmup/240 measured if used.
## 12. Constraints and stop conditions
Stop if pin backend cannot build or semantics contradict contract, report distinguishing probe. After two failed repair cycles send both results to root. No unauthorized remote actions, shared checkout edits or child agents.
Additional integration check approved by root: append defaulted WorkerPoolOptions to read_save, forward to the constructed world, and exercise the existing command/reload fixture under capacity one (tests/replay_tests.cpp). Preserve original replay coverage and the save format.
## 13. Authorization and decisions
User approved full plan and branch-per-system development. Strong implementation owner assigned for high-risk cross-thread failure/critical path. Root integrates and pushes after review.
## 14. Return format
Return S01-02 status, actual API/files, failure semantics and lifecycle checks, build/test and benchmark results with commands and baseline, residual risks and integration implications.
+48
View File
@@ -0,0 +1,48 @@
# Capture immutable world state at a completed simulation boundary
Task ID: S01-03
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01, system/s01-simulation at 68f91a2, verified S01-02. World owns complete data, execution mode/pool/caches; WorldSaveCodec reads and validates that data. M01-P2/F3 and upstream Void/Library #5 cover immutable caller-built snapshots.
## 2. Objective and deliverables
Provide NEW World::capture() const -> std::shared_ptr<const World> for const renderer/serializer/snapshot users. Held snapshots preserve all observable data after subsequent live mutations, or when live World is destroyed.
## 3. Scope and non-goals
World snapshot representation and focused tests, no coordinator, UI, checkpoint, rules or generic atomic snapshot mirror. No byte roundtrip/allocation of a worker during capture. Capture must be called by owner at finished command/tick barrier.
## 4. Files to inspect
Inspect world.hpp, world.cpp, world_save.cpp, worker_pool.*, tests/{replay,executor,core}_tests.cpp, benchmarks/colony.cpp. Identify all persistent fields, visible counters, worker and transient cache state, const views and nested paths/inventory containers.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; tests/snapshot_tests.cpp; CMakeLists.txt; docs/plan/systems/S01.md
No editing other worktrees, Git or Serena state. You are not alone and other agents own runtime, rules, persistence, dispatch. Preserve S01-02 exactly apart from necessary representation changes.
## 6. Implementation or investigation approach
Group copyable logical World data in a single copyable representation such that future gameplay fields naturally join one copy. Keep executor, worker callbacks and cache out of captures (cache independent of future behavior; if a read-only getter exposes hit or path counters, preserve its observed value). Preserve source worker_count() reporting where practical, and forbid mutable snapshot access by type. Favor private or internal state and simple direct World access; no hand-maintained second serializer, dozens of copy assignments or per-capture thread starts. Reuse existing WorldSaveCodec public behavior. Validate current construction/layout/implicit move caller compatibility.
## 7. Interfaces and data contracts
NEW public std::shared_ptr<const World> World::capture() const. Propagate normal allocation failures to the owner, source remains untouched, no mutation or pointer aliases to source vectors/agents. Existing factories, modes and format13 unchanged. Include upstream #5 link plus replacement criterion where publication is discussed.
## 8. Dependencies and integration
Root will plug capture into single-owner publication, sampled under one owner, snapshots can cross renderer/I/O/threads. This feature can compile from 68f91a2 without S16 or S19. No alternate restore API unless natural and actually required.
## 9. Edge cases security and performance
Snapshot retains owned nested inventories/routes/reservations, current pause, workshop, hidden sequence/revision/counters and profiling data needed by reads. Capture while a task is running is outside caller contract. Pools/hooks not allocated/retained by read-only view. Test held snapshot can be read on a worker while source advances without using sleeps as ordering controls. Bound benchmark scope to actually measured World/runs.
## 10. Acceptance criteria
1. compare canonical bytes immediately and after source changes/destruction incl mid-carry fixture; assert stable views/counters/pause. 2. Capture+serialize on actual const read path; callback ownership released with live world even if snapshot lives. 3. Cover 2/6 and serial or existing replay tests for legacy behavior. 4. Measure capture cost at 50/500 residents in x64 Wine and report exactly what was measured, no native claim.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/capture-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <build>/settlement_core_tests.exe --tag snapshot, git diff --check; evidence including benchmark protocol and measurements. Separate output files from S01-02 logs.
## 12. Constraints and stop conditions
Do not alter formats, owner scheduling or save/LAN fixtures. No unrequested generic server/runtime framework. Stop if renderer has mutating access disguised as const or impossible copy semantics. Escalate after two failed repairs of the same defect.
## 13. Authorization and decisions
Parent owns all commits and pushes. User approved roadmap; planner/preflight accepted independent copies at owner barrier. This is the first S01 immutable-publication component.
## 14. Return format
Return S01-03 READY/BLOCKED, exact API/files, fields/cache/executor boundary, actual tests/counts, measurements, limitations and contact on any compatibility risk. No children.
+48
View File
@@ -0,0 +1,48 @@
# Run the single-owner simulation clock and publish committed snapshots
Task ID: S01-04
Role: astra_implementer
Status: READY
## 1. Context and baseline
Exclusive s01 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 fast-forwarded to 2224299. Actual S01::World::capture, S16 CommandDispatcher+SessionIdentity and S15 WorldCheckpoint + rules exist in this tree; S01/S19/S15/S16 reviews M01-V3/V4/V5. M01-F3 defines fault, epoch, capacity, and load fencing. Pin 7b0fea6 provides Time::MonotonicClock/SystemMonotonicClock/ManualClock, Uuid::try_v4, Async executor. Public library snapshot gap https://git.faumaray.com/Void/Library/issues/5.
## 2. Objective and deliverables
Build NEW SimulationRuntime, sole mutable World owner on a background worker, 20 Hz at normal speed and real immutable publications. Provide a usable asynchronous adapter for commands, save capture and load replacement before later viewer integration.
## 3. Scope and non-goals
Core scheduler, snapshot, bounded commands, validated installs, compatibility with existing serial/parallel World, tests/docs. UI, LAN packet codec, file dialogs, disk decoding/reading, stable-ID internals and content selection UI have other owners. Keep standalone old World entry points compatible.
## 4. Files to inspect
Inspect actual engine/include/settlement/core/{world,command_dispatcher,checkpoint,save_service,rules_manifest}.hpp + implementations, app/viewer_win32.cpp timer/menu/pause/command placement, M01-F3 and relevant systems, pinned Void/Time/Clock.hpp, Void/Core/Uuid.hpp and Void/Async. Use stage barrier capture() exactly as documented.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/simulation_runtime.hpp; engine/src/simulation_runtime.cpp; tests/runtime_tests.cpp; CMakeLists.txt; docs/plan/systems/S01.md
Do not change any other worktree, Git refs, existing command/save interfaces or shared Serena activation. You are not alone; other workers own viewer, library and custody concerns.
## 6. Implementation or investigation approach
Single mutable owner, initial validated WorldCheckpoint (already contains stable world_id, city, rules) or explicit initial equivalent. Generate ephemeral session UUID for each start/install, including rollback of the same stable world. One stable PublishedSnapshot (identity/tick/publication revision, shared_ptr<const World>, shared immutable RulesManifest, command request metadata as needed). publish prepared snapshot/ledger results only after complete tick or command. Reader snapshot retrieval never waits for a tick or disk work. On any active tick/command/preparation exception: retain previous publication, drop/disable partial working world and uncommitted ledger, make observable Faulted, complete queued futures predictably, retain old exact committed receipt lookup. Ordinary domain rejection and failed install/file validation leave healthy owner alive. Keep owner responsive to queued work while paused, external presentation suspend independent from in-game pause. Target fixed logical 50 ms steps using pinned MonotonicClock; process elapsed debt deterministically bounded per pass, no starvation or time skipping; re-anchor on suspend/paused/resume so idle time cannot burst into gameplay. Provide manual-clock wake/test barrier so tests avoid arbitrary sleeps. Publish revision changes even for accepted commands at equal tick. Use atomic or short critical sections, no locks around World::step/capture, I/O or joining. Efficient ledger staging: avoid copying the ledger on each tick or replay. Unexpected post-effect failures never return success.
## 7. Interfaces and data contracts
Expose a bounded try_submit(TrustedClient, CommandEnvelope) + future/typed result with immediate admission outcomes and safe always-completed accepted requests. Allow viewer to allocate correct contiguous per-client IDs (normal local queue/order and retries). Provide trusted read-only snapshot for UI and a coherent capture_for_save that checks health at its linearization point. Expose begin_load()/install(ticket, independently validated WorldCheckpoint) or equivalent with latest requested serial and expected active epoch, rechecked immediately before publication incl concurrent newer load during preparation. Failed/superseded install keeps current publication/owner/ledger. Honor F3 even if faulted and guarantee recovery by a valid newest load. A fresh epoch discards old command history and fences stale commands/errors. Provide a simple clock notification or deterministic owner fence for tests. Communicate frozen signatures early to root; UI/transport packages depend on them.
## 8. Dependencies and integration
Root owns CMake integration, app adapters, Gitea and current ports. Runtime must be usable from Win32 WM_TIMER to poll latest view and command futures while rendering. Prefer existing Void supported primitive for generic work/time (standard condition-variable/synchronization where appropriate). Service writer owns disk background; use capture API without calling writer on the owner thread. Link #5 + replacement criterion in docs. Default config limits consistent with existing M01 subsystems.
## 9. Edge cases security and performance
Stress lifecycle races: complete all accepted work on shutdown with normal/Closed/Faulted status, no borrowed tasks after World destruction, success never races visibility. New accepted work has deterministic FIFO/admission and explicit capacity; ensure load recovery possible after fault, old work only commits in old session. Faulted current view still valid for read-only rendering. UUID/allocation failures during load leave old state unchanged. Document shared snapshot ownership memory tradeoff. Test reads return previous stable view while deliberately blocked tick is running. Determine nonfatal invalid inputs before owner mutation.
## 10. Acceptance criteria
1. Under manual time, exactly 20 ticks per second (or observe per step) with same canonical data as direct reference. Commands can pause/unpause while no ticks progress, same-tick publications update. 2. Two clients exact repeats, old session after rollback, altered payload, load supersession, capacity and orderly shutdown. 3. Inject stage failure / after command mutation / snapshot preparation, verify last publication and committed receipts survive, no fresh mutation/save silently succeeds, queue futures all settle, valid load recovers cleanly. 4. Gate real long tick and show a UI reader and immutable save capture return previous completed state. 5. Whole x64 Wine suite passes, no native claim.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/runtime-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <build>/settlement_core_tests.exe --tag runtime, full verbose CTest, git diff --check. Name logs runtime-* under /tmp/stoneheart-milestones.xprJ2SVp. Communicate before schedule/contract changes.
## 12. Constraints and stop conditions
No external services, branches/commits/push, children or template frameworks. Stop if a shared API makes F3 impossible. Two failed fixes for same problem -> distinguish failure and escalate to parent for re-diagnosis. No scheduling behavior on UI or disk paths.
## 13. Authorization and decisions
User authorizes whole roadmap, separate system branches and PRs. Planner/preflight M01-F3 and reviewed implementations freeze the conditions. Root decides integration and release separately.
## 14. Return format
Return S01-04 status, early exact public header/contract for viewer, concrete timing/fault/install/ID outcomes, files, actual compile/tests/counts, open native or integration limitations. No subagents.
+48
View File
@@ -0,0 +1,48 @@
# Resolve stored logistics references by stable storage and resource IDs
Task ID: S06-01
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s06, system/s06-logistics begins a4cf99c. M01-P3 mapped World+codec+UI references, M01-V6 requires checked exhaustion for all storage/node allocation paths. Actual WorldState groups the complete capture; modern v1 checkpoint embeds format13; legacy tests 1–13/LAN11.
## 2. Objective and deliverables
Migrate live Agent::resource_node_index and storage_index, MaterialReservation::storage_index and ConstructionStop::storage_index to the selected objects' existing nonzero IDs. Deleting an earlier unrelated element must preserve all targets and quantities. Cover restoration and ID exhaustion.
## 3. Scope and non-goals
Only S06-01 storage/resource references and checked allocation at all existing sites. Production index and next agent/job/production counters have their own later contract, stack/reservation/transfer identity comes later. Preserve deliberately confirmed stock demolition behavior. No public new network protocol, geometry, checkpoint schema or UI feature.
## 4. Files to inspect
Inspect world.hpp, world.cpp, world_save.cpp, first_colony.cpp, viewer_win32.cpp resident detail, graphics/callers including benchmarks, core/replay/snapshot/checkpoint tests. Read S06/S04, M01-P3/V6, pin Math/Numeric.hpp checked_add and Core/Counted.hpp. Use stable-vector ordering validated by WorldSaveCodec. Verify existing API users by rg.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; app/viewer_win32.cpp (existing resident-detail reference access only); tests/core_tests.cpp; tests/snapshot_tests.cpp; tests/replay_tests.cpp; tests/checkpoint_tests.cpp; tests/identity_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S06.md
Other code owners operate in isolated branches. You are not alone; do not revert others or change Git/shared Serena. Modify existing tests only for changed ref semantics, not to weaken checks.
## 6. Implementation or investigation approach
Use zero as missing typed ResourceNodeId/StorageId, remove positional fixups for these members everywhere. Expose read-only bounded ID lookup and reuse ID-ordered lower_bound or equivalent. Keep indices ephemeral inside assignment and validation count arrays. Encode ID→old positional one-based/sentinel fields exactly; decode raw positions in explicitly bounded loader temporaries then convert to IDs after referenced arrays are populated and order validated, before world domain validation/use. Reject out-of-range/missing ID before indexing. Keep production_index/no_entity_index independent. Preserve ordering, deterministic routes and complete old wire bytes. Write source comments with linked replacement test for Void/Library #7.
## 7. Interfaces and data contracts
ID exhaustion: UINT64_MAX in next_* is a legitimate terminal high-water mark, last allocatable ID is MAX-1. Precompute checked successor with pinned Void::Numeric::checked_add before world/vector/terrain effects in World::add_resource_node, World::add_storage AND direct Place{BerryField,TreePlot,FlaxField,Mine} and PlaceStorage command paths. Only commit counter after successful construction/insertion. No returning zero, wraparound or duplicate IDs. Direct factory exhaustion raises std::overflow_error, commands return non-mutating Busy without consuming legacy sequence. For MAX-1 exactly one insertion then a stable serialized exhausted world. Validate invalid refs and preserve existing stronger invariants/canonical old bytes.
## 8. Dependencies and integration
Root owns CMake merge, dependent runtime/GUI packages, Git and upstream. Void/Library #7 covers restorable checked sequences; #8 is later custody, pinned Void Numeric handles arithmetic now. Preserve current std::unique_ptr<World> factories/mode, Render const path, standalone tests. No compatibility alias which silently restores use of vector indices.
## 9. Edge cases security and performance
Mid-carry before/after erasing earlier store/node, pantry meal, site tending with no storage, construction multi-stop delivery, carpenter output reservation, active targets remain protected by existing rules. Guard lookup for none/dangling, sorted IDs and caches. Ensure fast logarithmic lookups; avoid O(N²) scans or per-agent linear scans during codec, no duplicate durable map to synchronize. Check max vs max-1 inputs, failed insertions and byte-level determinism. Use pre-migration external baseline or saved corpus to verify exact bytes when gameplay equivalent.
## 10. Acceptance criteria
1. Live references preserve meaning after erasing an earlier unrelated store/node; no shifted refs remain in runtime. 2. Capture, legacy save13, checkpoint roundtrip and serial/2/6/12 trajectories agree mid-haul. 3. MAX/MAX-1 at every allocation path, including mine blocked-cell/cache on rejection. 4. Damaged legacy indices reject candidate, no partial live mutation. 5. All tests/cross build pass incl baseline, focused identity tests and project docs.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/identity-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag identity, verbose CTest, git diff --check. Cross-baseline compare relevant old outputs; root shares /tmp/stoneheart-milestones.xprJ2SVp/trajectory.cpp & old-trajectory.bin. Report actual bytes/scenarios and time if performance measured.
## 12. Constraints and stop conditions
No side effects outside checkout/build/log temp. Stop if current wire cannot represent migrating these existing IDs without loss, or a supported caller needs out-of-scope change, or after two failed repairs of the same issue. Do not silently drop malformed/legacy data.
## 13. Authorization and decisions
User authorizes all milestone/system implementation, upstream issues, commits and PRs. M01-P3 proposed slice and M01-V6 preflight correction is incorporated here; root confirms narrow corrective re-review before dispatch.
## 14. Return format
Return S06-01 status, actual files/lookup and legacy conversion boundaries, overflow/Busy semantics, commands/counts, cross-baseline byte evidence, remaining limitations. No children/commits/push.
+48
View File
@@ -0,0 +1,48 @@
# Publish immutable save requests asynchronously on Windows
Task ID: S15-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s15 system/s15-persistence, baseline 8d2870a. Root and other authors use different checkouts. S15-W02, M01-P2/F3, Void pin 7b0fea6. Root created https://git.faumaray.com/Void/Library/issues/3 for unsupported Windows replace_file.
## 2. Objective and deliverables
Implement a bounded FIFO background Windows save service, with atomic same-volume publication of immutable request content and meaningful failure outcomes. Provide API/test surface for viewer and later checkpoint framing.
## 3. Scope and non-goals
Own independent S15 file service only. No UI/World/serialization format change. Input is a snapshot-owning producer (or shared immutable bytes) with tick, epoch and request identity; synchronous existing save helper remains until owner integration.
## 4. Files to inspect
Inspect app/viewer_win32.cpp::save_world_file, current save codec, docs/plan/systems/S15.md. In exact pin inspect Void/System/Path.hpp (ReplaceFailure, unsupported Windows), Void/Async/{ThreadExecutor,FuturePool}.hpp for a single writer and bounded admission. Existing env and library checkout are in /tmp/stoneheart-verify.KoZwE4o8.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/save_service.hpp; engine/src/save_service_win32.cpp; tests/save_service_tests.cpp; CMakeLists.txt
You are not alone. Use explicit workdir/absolute paths only in specified worktree; others own independent systems. Root handles CMake merges/Git. Do not edit main or change shared Serena project.
## 6. Implementation or investigation approach
Give each accepted save a monotonic request identity, captured tick and session UUID (reuse Void::Uuid::Uuid or consistent fixed bytes). Materialize from immutable producer on writer thread or allow shared immutable bytes, further integration must keep snapshot acquisition cheap. Bound queue including in-flight and return Busy/Closed before ownership side effects. One FIFO writer ensures older accepted saves cannot replace newer same-slot requests. Use pinned Void Async where suitable. Worker completes all accepted requests on shutdown. A failed producer/write must deliver completion and next FIFO task continues.
## 7. Interfaces and data contracts
Publish to a unique same-directory staging file created exclusively, write all bytes incl embedded NUL, handle short/error or close failure, explicitly FlushFileBuffers, atomically rename with replacement on the same volume; preserve previous slot on any prepublication failure, remove only owned staging files and distinguish postpublication visible/durability-unknown. First create, Unicode paths, sharing errors. Keep application-crash observations separate from power-loss guarantees. Local adapter + replacement criterion and upstream #3 link. Deterministic fault injection at phases for test; do not broaden external access. Communicate API early.
## 8. Dependencies and integration
S01 runtime later captures immutable snapshot/manifests, S15 checkpoint codec constructs bytes, UI will enqueue this service and poll completion. No dependency on unfinished runtime/system branch. CMake public types require actual transitive includes for callers.
## 9. Edge cases security and performance
Serialize FIFO submission ordering even if concurrent callers; expose or check order via returned IDs. No blocking UI submission, no mutex held waiting for disk/producer or while joining. Same-directory sibling preserved on failures. Use isolated temporary directory for tests, never overwrite user files. Reject missing parent/closed service; documents should make overwrite/new behavior clear.
## 10. Acceptance criteria
1. Unicode path succeeds on create/replace while readers see full contents. 2. Prepublication failures preserve old bytes, temp cleaned, postpublication failure truthful. 3. Slow earlier/newer order on a single slot, bounds, shutdown drain, producer exception followed by next success verified. 4. Tests establish immutable snapshot life & UI caller progress without sleep-only assertions; tag save-slot and run under Wine.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/save-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. Tests use new empty temp dirs, Windows/Wine results labelled. Collect native limitations. Provide specific replacement test for Void #3.
## 12. Constraints and stop conditions
Stop if Windows primitive cannot meet claimed contract or tests prove a different outcome. After two failed repairs escalate with artifacts. No external writes, further agents, branch operations, admin actions or out-of-scope edits.
## 13. Authorization and decisions
User approved entire roadmap and per-system development with commits/push from root. F3 accepted FIFO ordering and failure semantics. Upstream issue already exists.
## 14. Return format
Return S15-01 status, exact API/files, failure/visibility semantics, commands/counts, native verification still needed and integration notes. No subagents.
+48
View File
@@ -0,0 +1,48 @@
# Encode and validate versioned world checkpoints with frozen rules
Task ID: S15-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/checkpoint, detached de38aff (reviewed S19 rules + M01 replay). Parent integrates this into system/s15-persistence. Legacy World::write_save/read_save and their validations implement formats 1–13. default_rules_manifest resolves two real built-ins. Pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792.
## 2. Objective and deliverables
Implement a bounded modern checkpoint codec admitting a stable world UUID, city identity and a verified rules manifest together with the existing canonical world state. Produce a complete validated candidate without touching live state.
## 3. Scope and non-goals
Game-specific envelope, built-in installed-catalog API only if needed, tests. SaveService, asynchronous requests, session/epoch assignment, UI, new custody fields, scripting are independent packages. Existing default format13 encoding and LAN11 fixtures must still pass.
## 4. Files to inspect
Inspect engine/include/settlement/core/{world,rules_manifest}.hpp, engine/src/{world_save,rules_manifest}.cpp, tests/{rules,core,replay}_tests.cpp, CMakeLists.txt, docs/plan/systems/{S15,S19}.md. Inspect pinned Void/Binary, Crypto SHA256, Core Uuid public types/tests.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; tests/checkpoint_tests.cpp; CMakeLists.txt; engine/include/settlement/core/rules_manifest.hpp; engine/src/rules_manifest.cpp
Use last two only for extracting the actual built-in catalog behind existing default_rules_manifest. Others own writers, S01/S16 and separate checkouts. You are not alone, do not revert others or change Serena/Git.
## 6. Implementation or investigation approach
Define NEW encode_checkpoint(const World&, stable world UUID, nonzero city, const RulesManifest&) and decode_checkpoint(bytes, installed RulePackage catalog, workers/mode), or equivalent precisely typed API. Use distinct magic+schema, little endian Void Binary, SHA-256 integrity over all meaningful header+payload bytes. Persist complete selected closure with each sorted stable ID, exact version, content digest and compare recomputed manifest from installed catalog, naming missing/changed package. Serialize core once with existing World codec. Verify bounded lengths/counts and outer integrity before domain/world allocations. Reject extra bytes, unsupported version, nil identity/zero city, metadata mismatch incl tick if stored, missing/extra/conflicting rules. Candidate returns unique World, identity, matching immutable manifest. No on-disk active session/ledger. Report simple actionable diagnostics while preserving ownership; do not make persistence a signature/authentication.
## 7. Interfaces and data contracts
Use Void::Uuid::Uuid for world, uint64 city, RulesManifest and RulePackage directly. Add public installed builtin_rule_packages() returning expected catalog if needed, reuse in default_rules_manifest. Keep compiled-in fixture contents identical. Frozen rules independent of current active world. Allow later versioned state for new custody data without breaking old fixture. Match preexisting 128 MiB body cap plus separately bounded metadata before buffering. Communicate actual API early.
## 8. Dependencies and integration
No dependency on writer or runtime; immutable capture later calls encode in background, validated decoded world goes to runtime replacement. No new framework/dependency or external issue is needed for game framing using supported primitives; report a genuine missing generic capability to root.
## 9. Edge cases security and performance
Adversarial truncations, length overflow, malformed counts/input, duplicate packages, package digest/version/build mismatch, corrupted canonical body with recomputed outer checksum, lossless old bytes, world/identity/city survival. Decode allocates only from bounded data; respect existing output failure behaviors. Reading legacy file remains via World::read_save.
## 10. Acceptance criteria
1. Round-trip a live and mid-carry world, compare full canonical world bytes and continued ticks. 2. Selecting alternate installed packages round-trips and validates against a catalog in different order. 3. Corruption, incompatible/uninstalled rules, bad UUID/city, lengths/trailing data fail with usable diagnostics while original world is untouched. 4. Old save13 & LAN11 and all existing 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/checkpoint-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <build>/settlement_core_tests.exe --tag checkpoint and git diff --check. Check commands from YOUR worktree.
## 12. Constraints and stop conditions
No changes to shared checkouts or external services. Stop on ambiguous destructive format migration or incompatible real library semantics. Escalate after two failed repairs of the same defect.
## 13. Authorization and decisions
Parent owns Git. User approved milestones/systems, commits/push; plans M01, M01-F3 cover independent validation before any owner replacement. Parent will review actual diff.
## 14. Return format
Return S15-02 READY/BLOCKED, exact API, owned files, frame and limits, test results incl counts, residual limitations and later runtime integration. No subagents.
+48
View File
@@ -0,0 +1,48 @@
# Prepare checkpoint files in the background for the interactive client
Task ID: S15-03
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive s15 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s15 system/s15-persistence fast-forwarded to 8c4c1fe. Includes verified runtime PublishedSnapshot, S15 checkpoint and SaveService + builtins. M01-F4 accepted bounded background file adapter; #3 is the linked Windows atomic-write contract.
## 2. Objective and deliverables
Supply a usable persistence adapter for the real window: submit save of a held PublishedSnapshot, prepare a modern or legacy file asynchronously into a complete WorldCheckpoint; no disk or parsing on UI/owner thread.
## 3. Scope and non-goals
Only S15 file API/implementation and test/docs/target integration. Viewer itself and its load-ticket/feedback lifecycle are owned separately. Existing SaveService handles writes; existing World/checkpoint codecs handle validation.
## 4. Files to inspect
Inspect actual simulation_runtime.hpp (PublishedSnapshot immutable), checkpoint.hpp/.cpp, save_service.hpp/.cpp, rules_manifest.hpp/.cpp, world_save.cpp signature/limits/validation, viewer current dialog/select and file handling. Review Void Async ThreadExecutor/FuturePool lifetime/admission tests and pinned Windows IO coverage. M01-V6 requires max_checkpoint_bytes.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/checkpoint_files.hpp; engine/src/checkpoint_files.cpp; tests/checkpoint_file_tests.cpp; CMakeLists.txt; docs/plan/systems/S15.md; engine/include/settlement/core/checkpoint.hpp and engine/src/checkpoint.cpp only if needed to expose canonical signature recognition
No changes to other worktrees/Git/Serena/Win32 UI. You are not alone; other workers own runtime, LAN, UI, World/custody. Parent integrates CMake.
## 6. Implementation or investigation approach
Introduce NEW CheckpointFiles owning one existing SaveService configured max_checkpoint_bytes and a bounded pinned Void reader executor/FuturePool. try_save(absolute path, shared_ptr<const PublishedSnapshot>) delegates to existing queue, producer owns const world/manifest and runs encode_checkpoint on writer. Caller acquired healthy snapshot already. try_load(absolute path,... immutable installed catalog, workers/mode) returns immediately with explicit admission and accepted future/typed diagnostic or complete candidate. Provide useful error for file access, limits, legacy decode, missing package etc. For modern signature call decode_checkpoint only, never downgrade after a modern failure. For legacy signature parse validated World::read_save and attach fresh stable nonnil UUID, city1, default supported manifest. Preserve exact prior old v1–13 paths; don't invent a mutable live session. Open each path once, enforce maximum read incl growth/EOF before consuming unbounded storage. Reader/writer can run independently; hold input/catalog through work, drain on shutdown.
## 7. Interfaces and data contracts
Communicate exact header early. Constructor may own shared immutable installed catalog (default builtins) to simplify caller. Caller keeps this service for window lifetime across runtime resets; jobs never capture viewer/raw runtime or call GUI. Return SaveSubmission or precise adapter result preserving prior SaveService metadata. Reader producer can use an optional bounded observer/gate for deterministic tests following existing failure hooks if needed. No thread per file; explicit bounds & stable closed admission. Busy or invalid admission does not consume caller data. Viewer handles begin_load tickets/replacement policy, reporting and 32×32 restriction.
## 8. Dependencies and integration
Root wires UI later, receives filled result and verifies dimensions before SimulationRuntime::try_install; runtime itself rechecks epoch/ticket. Old valid file import gets a fresh stable ID on each explicit import. Default `.settlement` existing extension and title paths maintained. Store upstream #3 link where relevant; pinned Void supports asynchronous running and file codecs as documented. No external actions.
## 9. Edge cases security and performance
Check Unicode filesystem path, open-one/read-one with changing files, oversized declared/actual data (bound including growth), corruption/trailing/truncation distinctly, catalog mismatch names missing package, nil UUID generator error, concurrent submit/shutdown/read queue/in-flight count, writer retains held snapshot after source advances. Avoid throwing from worker leaving pending futures. No double-opening for format detection, no fallback rewriting files. Track native/Wine differences.
## 10. Acceptance criteria
1. Roundtrip actual immutable old snapshot through production save helper to file then load to independent candidate; live world progresses meanwhile. 2. Open true legacy fixtures and modern mismatches; invalid/oversized/trailing/frame corruption rejects. 3. Bounded and closed reader, deterministic held reader blocking test shows UI submit and writes/other work independent, shutdown drains, next read succeeds after bad file. 4. Normal cross build and old suites pass. 5. Frozen interface is usable for viewer async polls without lifetime hazards.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/file-adapter-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag checkpoint-file, full verbose CTest, git diff --check; files in new temporary Windows directories. Name logs file-adapter-*.
## 12. Constraints and stop conditions
No editing viewer/custody, raw live World access from workers, remotely written actions or new external deps. If architecture requires a new generic capability report it to root. Two failed fixes for the same issue require escalation.
## 13. Authorization and decisions
Root owns all Git; user approved roadmap and asked maintain PR/cumulative/issue tracking. F3/F4 and V6 freeze acceptance; Windows physical tests follow separately.
## 14. Return format
Return S15-03 READY/BLOCKED, early concrete signatures for viewer, owned paths, complete tests/observations and limitations. No children/commits/push.
+48
View File
@@ -0,0 +1,48 @@
# Dispatch authenticated session commands with exact retry outcomes
Task ID: S16-01
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16 system/s16-authority, 8d2870a. Main checkout is a different task. F2/F3 and M01-P2 approve this scope; pinned Void 7b0fea6, upstream gap https://git.faumaray.com/Void/Library/issues/6.
## 2. Objective and deliverables
Implement S16-W01 game command admission/dispatch in a single-owner component plus integration tests with two trusted client handles. Expose a frozen interface for S01 runtime and modern transport.
## 3. Scope and non-goals
S16 dispatcher only, no sockets/UI/clock or save format. Preserve legacy World::apply_command behavior and LAN11 decoding for existing callers.
## 4. Files to inspect
Inspect world.hpp, world.cpp World::next_command_sequence/apply_command and queue_cabin, app/lan_wire.cpp, tests/core_tests.cpp, docs/plan/systems/S16.md. Void/Core/Uuid.hpp at exact pin supplies nonnil identities/try_v4; source stubs/compile headers from known library checkout.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/command_dispatcher.hpp; engine/src/command_dispatcher.cpp; tests/session_tests.cpp; CMakeLists.txt
You are not alone. All writes only to specified worktree with explicit absolute paths/workdir. Root integrates branches and CMake; no switching shared Serena, changing others' files, committing/pushing or spawning.
## 6. Implementation or investigation approach
Use one host dispatcher per world/session and one shared city for M01 (plus disallowed city test). Authenticate caller via trusted local connection slot passed separately, never trust payload player. Envelope includes version, nonnil world+session UUID, city, uint64 request id, game action fields. Per trusted client require contiguous monotonic numbers from 1. Session/identity/version and trusted slot validated before any cached response. For full payload and city equal to an existing key, replay original outcome; reject ID reuse with a changed payload (compare all fields) without mutation. Persist accepted and completed rejected results within session until replaced. Global or per-client configurable capacity: Busy before NEW requests at capacity; honor all previously admitted receipts, no eviction/reexecution. Stale/out-of-order/busy transient errors don't consume request; completed domain rejections do. Store or reserve result before applying effect. Do not silently drop prior receipts on exceptions; runtime will retire faulted owner and session before more commands.
## 7. Interfaces and data contracts
NEW CommandEnvelope/CommandPayload, session identity (using Void::Uuid::Uuid or fixed byte-compatible game type), target city and explicit outcomes incl status, assigned tick and revision; trusted player is supplied to dispatcher, not a payload identity. Map payload to PlayerCommand using World::next_command_sequence after auth, with no change to legacy sequences on rejection. Provide bounded acceptance path for legacy queue_cabin when needed by viewer (new owner command, preserve checked prerequisite and return outcome) or report exact adaptation to root. New command and session types should be usable without event loop. Share exact API with root early.
## 8. Dependencies and integration
Consumers S01 runtime, S15 checkpoint and modern transport. Worker owns CMake additions in isolated branch; link Void::Core PUBLIC only if publicly required. Reference #6 in companion task + local source/milestone decision with replacement check. No extra generic ledger.
## 9. Edge cases security and performance
Check nonnil IDs, invalid/unsupported action, sequence zero, overflow, two clients same request numbers, different payload/city, old world/session, accepted and failed duplicates even after later requests, capacity and exception-safe reservation. Old rejection corrected under a new envelope ID must still use correct World sequence. No hidden trust from bytes.
## 10. Acceptance criteria
1. Two clients converge and repeat accepted/rejected commands without reapplication, including after newer requests. 2. Stale after rollback and wrong city/identity rejected with identical world bytes. 3. Changed payload, exhaustion, unsupported version/order bounded and tested. 4. Legacy and new tests build/run using actual World. Header communicates semantics to runtime.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/session-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. Tag new tests session, including positive effects and exact repeat receipt tick/revision. Report performance bounds by inspection.
## 12. Constraints and stop conditions
Escalate required cross-branch changes, genuine ambiguity or two failed repairs; use direct source in this worktree instead of querying the main graph as if it were the same checkout. No external actions.
## 13. Authorization and decisions
User authorized full roadmap and branches/commits/push; root owns remote actions. F3 READY for S16 dispatcher under above semantics.
## 14. Return format
Return S16-01 status, actual files and public interface early, semantics/complexity, test and build counts, gaps, runtime integration notes. No subagents.
+48
View File
@@ -0,0 +1,48 @@
# Resolve a frozen set of game rule packages from actual manifests
Task ID: S19-01
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 8d2870a. Main working directory belongs to another task. Exact Void pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. M01-P2/R2 and preflight F2 confirm the implementation seam.
## 2. Objective and deliverables
Implement S19-W01 typed game rule manifest loading, validation and reproducible identity, with real JSON inputs and CTest coverage. Supply the public interface S15/S01 will freeze into worlds.
## 3. Scope and non-goals
Only S19/M01 core support and its tests/build wiring; no Lua, UI, save codec or network yet. Plan requires diagnostics usable by a caller and frozen identity for explicit world selection.
## 4. Files to inspect
Inspect docs/plan/systems/S19.md, M01, CMakeLists.txt, exact upstream Void/Data/StrictJson.hpp, Void/Text/Semver.hpp, Void/Algorithms/Graph.hpp, Void/Crypto/Crypto.hpp and respective tests. Source root for pin is /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/rules_manifest.hpp; engine/src/rules_manifest.cpp; tests/rules_tests.cpp; CMakeLists.txt
You are not alone. Use ONLY your specified worktree with explicit workdir/absolute paths, verify root/HEAD before edits. Other systems have separate checkouts. Do not edit the main checkout, change shared Serena project, stage, commit, push or spawn. Root integrates CMake.
## 6. Implementation or investigation approach
Bound byte count and node/dependency/depth limits before/while using Void::Json::Strict. Manifest schema v1 includes namespaced package ID, exact strict SemVer, named dependencies and version constraints, exclusive providers, definitions with stable qualified IDs and references. For M01 definitions live in the JSON file (no external untrusted file paths/scripts). Resolve transitive deps from installed packages (one installed version per ID), detect duplicates/missing/range incompatibility/cycles/exclusive-provider clashes/unresolved definition refs. Use Void::Semver, Algorithms, Crypto and StrictJson. Sort sets, include definition content in SHA256, recompute digests; preserve semantically ordered data. Write diagnostics containing package/source and field. Provide usable base game package(s) for later startup via an explicit built-in loader or factory in owned code. Avoid implementing generic library alternatives.
## 7. Interfaces and data contracts
NEW public RulePackage source + immutable RulesManifest (sorted frozen package ID/exact version/SHA256 and manifest fingerprint), loading/resolution via settlement/core/rules_manifest.hpp. Expose a base default and real catalog/selection input. Keep public types independent of upstream internals where practical. Define schema, duplicate/unknown semantics and source error handling in a short header comment. Send final signatures to root ASAP for S15/runtime.
## 8. Dependencies and integration
No upstream dependency update. Validate SHA-256 pure C++ fallback on Windows; use modules Data, Text, Algorithms, Crypto and transitive deps only. Matching generic candidate issue draft for reusable resolver is root-owned; game-specific capability names and decisions use published primitives. Root handles cross-system consumers and remote tracker outcome.
## 9. Edge cases security and performance
Reject unknown schema/invalid UTF-8/duplicate fields, malformed IDs/versions, digest spoofing, large files and excessive fan-out. Range semantics need explicit prerelease policy. SemVer == ignores build metadata, so frozen exact identities compare normalized full string and 32-byte digest. Stable diagnostic path relevant to user-provided files. No third-party game content.
## 10. Acceptance criteria
1. Load and select from at least two meaningful original package documents with deps; reversing input/definition sets produces identical frozen identity. 2. Content, exact version or build change alters fingerprint. 3. Missing dependency, bad range, duplicate, cycle, exclusive conflict, dangling references and malformed/oversize JSON give actionable diagnostics. 4. Windows target/test suites pass and API ready to persist/compare a manifest.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/rules-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. Add a discoverable Void suite with tag rules. Check actual diff and log timings.
## 12. Constraints and stop conditions
Escalate any required new generic mechanism or library incompatibility. No network writes, no Git mutations, no competing branch/source edits. Stop after two unsuccessful repairs of one issue and send original failures.
## 13. Authorization and decisions
User authorized full plan, milestone/system branches and pushes. The root handles those; preflight READY for S19 under these limits.
## 14. Return format
Return S19-01 status, actual files and API, schema/canonicalization decisions, failure coverage, commands/results, unverified limits, integration notes for runtime/save. Do not spawn.
+48
View File
@@ -0,0 +1,48 @@
# Compile a selectable plank-bed package into actual colony behavior
Task ID: S19-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive s19 worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 60154bd. Prior S19 catalog/manifest reviewed, M01-P4 and F6 preflight approved both existing bed production paths. Current World::start_scenario sets staged_beds_=true unconditionally; legacy/restored worlds already execute nonstaged SawPlank + BuildBed. S18 initial UI work/other World changes in distinct checkouts.
## 2. Objective and deliverables
Allow real selection between the existing default staged bed assembly and optional one-plank bed assembly at colony creation. Freeze compatible manifest/engine configuration and provide supported-profile validation at the application boundary for creation and loading.
## 3. Scope and non-goals
S19 core package, game-profile compiler/factory, narrow World scenario initialization and runtime-neutral validation tests. No UI/transport changes in this slice. No change to generic resolver/decoder acceptance or Lua VM. Preserve all original package contents, default game output and original call signatures/behavior.
## 4. Files to inspect
Inspect rules_manifest.{hpp,cpp}, first_colony.cpp, world.hpp/.cpp start_scenario/PlaceBed/PlaceRoom/recipes, world_save.cpp staged flag/state validation, checkpoint.hpp, actual tests/rules_tests, core_tests, legacy fixtures, prime S18 viewer_session.cpp constructor/load/host gates via sibling and plans S19/F6. Pin has resolver primitives used earlier, existing issue #4. Current default SawPlank executes 12 ticks; the old manifest's sample work_ticks=8 is not activated by this feature.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/colony_profile.hpp and engine/src/colony_profile.cpp (NEW); engine/src/rules_manifest.cpp; engine/include/settlement/core/world.hpp; engine/src/world.cpp (scenario initialization only); engine/src/first_colony.cpp; tests/rules_tests.cpp; tests/profile_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S19.md
Skip all UI and unrelated caller edits. S04 changes production identity in separate worktree. You are not alone; root integrates and handles simultaneous CMake/World edits. Never revert another worker, change Git or shared Serena.
## 6. Implementation or investigation approach
Add additive optional built-in exact package settlement.plankbeds with an allowed recipe definition in its own namespace, stable dependency on settlement.colony and no conflicting exclusive construction capability. Interpret explicit typed data describing one plank/simple assembly to select the actually existing engine bed mode. Use resolver/checkpoint typed APIs, validate supported exact closure/digests and content before building a supported colony. Compute prechange default manifest canonical bytes/fingerprint using the verified baseline first, hardcode golden from it into regression (old two-package closure/content unchanged); do not recompute expected with candidate. New default=false option meaning must be clear by names. Expose concise NEW profile enum/options and a game-specific factory producing validated WorldCheckpoint (owned World, fresh stable nonnil UUID, city1, correct manifest), plus supported-profile validation taking World/manifest or candidate. Name signatures early so S18 follow-up can wire title.
## 7. Interfaces and data contracts
Keep existing World::start_scenario(sawmill), make_first_colony(workers) staged by default; add explicit creation-only mode/profile parameter or overload, no mutable post-creation toggle. When active optional package selected, actual simple path: SawPlank + one BuildBed, one plank consumed; default already uses foundation wood/stone plus cloth twice. Furnished rooms must respect same rule. Existing schemas saved real mode; loaded exact default is allowed with EITHER persisted mode, inactive legacy worlds included (historical v1 or raw-format import). Do not alter their rules/mode at load. Optional exact profile requires active scenario staged=false where applicable; reject exact simple-manifest with active staged world. Unknown package/digest/config rejected by supported-profile gate; generic decode/runtime continue to handle caller-supplied catalogs independently. Reuse shared immutable definitions/lookup as suitable; avoid catalog-size assumptions and requiring every installed unrelated package.
## 8. Dependencies and integration
Viewer later calls this public factory and canonical compatibility gate on BOTH initial and prepared worlds, and keeps immediate/deferred old LAN11 exact-default-only. Do not mix S18 UI edits on s19; communicate the trusted support check and whether a profile may host to root. New catalog optional must not automatically activate or alter existing default hashes.
## 9. Edge cases security and performance
Exercise active/inactive imported historical worlds, current resaves, no silent toggle or package rewriting. Avoid claiming all base/ACE systems implemented. Use an actual complete bed production run under both options with relevant materials/outputs (incl furnished room), mature/paused snapshots persisted and continued. Preserve wire13/old baseline normal path. An altered content package using same ID/version must not pass compiled-profile support.
## 10. Acceptance criteria
1. Old default known fingerprint/bytes and baseline gameplay preserved; selecting optional package changes material chain and completes bed with actual initial supply. 2. Compare modern canonical per tick across serial/2/6/12 for representative events; held view does not change; mid-carry save/load continues identically. 3. Exact optional mismatch, default historical raw/v1 active simple and inactive accepted without rewriting; catalog reordering and missing/changed/extra activated packages handled. 4. Correct real startup factory and no mutable rules switch. 5. All cross suites pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/profile-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag profile and tagged rules, full verbose CTest, git diff --check; source actual old baseline digest from already built branch or separate helper, log its hash. Provide exact logs profile-*.
## 12. Constraints and stop conditions
No editing S18 UI, no broad changing existing recipes to fit sample data and no rewriting old manifests, formats or resources. Stop/escalate after two failed repairs of same issue or if actual optional mode cannot complete the scenario. No children/Git/remote mutations.
## 13. Authorization and decisions
Plan explicitly requires new-world module selection. Existing bed behaviors were chosen as first reversible demonstration, preserving old defaults and P4/F6 restoration policy. User authorized commits, issues and PRs through root.
## 14. Return format
Return S19-02 status, early exact creation/validation API, source derived default golden, observed actual bed/room/canonical and legacy compatibility, counts and residual native/UI risks.
+59
View File
@@ -0,0 +1,59 @@
# Материалы демо «Дом на склоне»
Запись M00, 2 декабря 2026 года. Это производственное задание для [M03](../plan/milestones/M03.md) и контрольной сцены Q-HOME. Новые материалы ниже ещё не изготовлены и не приняты. Художественный владелец назначается перед производством каждого материала. До этого в таблицах указан владелец «не назначен». Автор, исходник, условия использования, атрибуция, инструмент и его версия заполняются по факту создания или получения. Разрешение на использование в игре, изменение и распространение подтверждается ссылкой на сохранённое свидетельство. Частная переписка и платёжные данные в публичный реестр не заносятся.
## Иконки прототипа
Все три файла добавлены в коммите `8bb448cc49e3d76a5fdd52e490bd423138cca5f7` от 1 декабря 2026 года. Автор коммита указан как `Codex`. В просмотренной истории файлов и сопутствующих записях репозитория подтверждения происхождения не найдено. [LICENSE](../../LICENSE) содержит лицензию проекта, а связь каждого изображения с его правообладателем ещё требует подтверждения.
| ID | Файл и роль в прототипе | Git blob на `083b84e` и текущем HEAD | SHA-256 файла | Автор, источник, права и решение для демо |
|---|---|---|---|---|
| LEG-01 | [doctor_house.ico](../../app/art/doctor_house.ico), кнопка шаблона «Дом врача», кровать и аптечный шкаф | `9bc0d003c5881ac1201f6735df62a19446a27f35` | `1261481f7e4c321bc172f3f9ba3183f993a2d01c67e8db7f3d38e62fd2b9df0a` | Автор и источник неизвестны, разрешение не подтверждено. Исключить из нового распространяемого демо до установления прав или заменить самостоятельным обозначением. |
| LEG-02 | [miner_house.ico](../../app/art/miner_house.ico), кнопка шаблона «Дом шахтёра», каменная кровать и стойка с инструментами | `6873e316c71ca766d3956beb9f034e4c3af85b48` | `98d04a18adfd3f33746170620fd68b487d9b32a5e5d479d935adb66f2e2f92df` | Автор и источник неизвестны, разрешение не подтверждено. Исключить из нового распространяемого демо до установления прав или заменить самостоятельным обозначением. |
| LEG-03 | [weaver_house.ico](../../app/art/weaver_house.ico), кнопка шаблона «Дом ткача», кровать и ткацкий станок | `f191e2478e023ddbb278da32c092a62202e6fa91` | `5c72453768bd5abac4e5e4d9a38eb7a809424956f2653d378be30cc4cbb3deec` | Автор и источник неизвестны, разрешение не подтверждено. Исключить из нового распространяемого демо до установления прав или заменить самостоятельным обозначением. |
Эти файлы сейчас входят в исполняемый файл прототипа. [Ресурс](../../app/house_icons.rc) объявляет три ICO, [CMake](../../CMakeLists.txt) добавляет ресурс к viewer, а [build.ps1](../../build.ps1) копирует viewer в каталог поставки. Кнопки и содержимое шаблонов определены в [viewer_win32.cpp](../../app/viewer_win32.cpp). Владелец производства демо должен убрать эти ресурсы из новой сборки или приложить доказательства прав к каждому файлу и проверить итоговый исполняемый файл. Сохранённая сборка прототипа остаётся исторической записью.
Для замены трём кнопкам нужны самостоятельные пиктограммы в едином наборе интерфейса. Название и подпись должны оставаться читаемыми без опоры на цвет. Различительные мотивы для эскиза — сумка ухода, камень с инструментом и переплетённые нити. Исходные рисунки, автор и права заносятся в UI-02 до экспорта.
## Направление сцены
Рабочее направление — небольшой дом на террасированном склоне, сложенный из ясных плоскостей дерева, камня и утрамбованной земли. Контрольный чертёж занимает 6 × 5 клеток, пересекает границу `x=32`, содержит дверь, внутреннюю лестницу и три кровати, включая одну наверху. Последняя часть верхнего перекрытия строится из особо отмеченной распиленной доски. Для неё нужен различимый знак на модели груза и на готовой секции. Повторяемый модуль задаёт один игровой воксель. Для первого макета высота жителя принимается равной двум вокселям, дверной проём и лестница подгоняются к реально допустимому проходу M02. Точка привязки жителя — центр основания, у предметов — основание или место контакта с рукой. Масштаб и экспорт проверяются вместе с границами коллизии и рабочими позициями.
Вид сверху должен показывать положение ступеней и дверного проёма при скрытом верхнем этаже. Житель читается по крупному силуэту головы и туловища, груз — отдельной массой перед телом. Рабочие действия различаются формой движения и инструментом. Геометрия дома использует крупные балки и ясные контуры перекрытий. Мелкий орнамент не должен закрывать проход, груз или маркер работы. Одна утверждаемая сцена содержит дом, жителя, рабочее место и небольшой участок земли.
Палитра эскиза включает холодный серо-синий камень `#778485`, тёплое дерево `#9B744D`, землю `#8B735B`, траву `#728B62` и светлый текстиль `#E5D9BC`. Для команд и обратной связи применяются светлый контур на тёмной подложке и подпись. Готовая деталь сохраняет материал, чертёж получает полупрозрачную заливку и контур, недоступная работа — значок и текст причины. Освещение мягкое направленное с достаточным заполнением теней, чтобы верхняя площадка и нижняя комната оставались читаемы. Это исходные художественные решения для проверки, а не утверждённые экранные замеры.
Текстуры при необходимости ограничиваются размером 256 × 256 на материал для первого набора. Разрешены однотонные материалы и повторяемые узоры. Точный движковый формат, цветовое пространство и версия экспортёра определяются при создании импорта, после чего записываются с каждым исходником. Для моделей в рабочем файле хранятся ориентация, единицы, точка привязки и названия анимаций. Экспорт должен воспроизводиться из сохранённого источника без путей конкретного компьютера.
## Бюджет производства
Количество — план уникальных базовых исходников для одной сцены Q-HOME. Это объём для оценки работы, а не оценка стоимости или сроков. Повторения дома, жителей и ресурсов используют эти исходники. Каждая строка представляет единый комплект с отдельной записью для каждого созданного или полученного файла. Владелец и автор пока не назначены. Источник, лицензия или разрешение, возможные производные, атрибуция и свидетельство для всех новых файлов пока отсутствуют. Все строки имеют статус «запланировано». Перед поставкой нужно заполнить эти поля и сохранить рабочие исходники и экспорт.
| ID | Комплект и количество | Назначение в Q-HOME | Рабочий источник и экспорт |
|---|---|---|---|
| GEO-01 | 4 материала рельефа — земля, трава, камень, открытый срез | Склон, выемка, различимый добываемый камень | Собственный файл палитры или текстур, экспорт материалов в формат импорта M02 |
| GEO-02 | 1 набор дерева и 1 набор каменного узла | Источники древесины и камня до и после добычи | Собственные модельные файлы и варианты состояния, экспорт геометрии и материалов |
| GEO-03 | 1 набор строительства из 6 частей — опора, пол, стена, дверь, лестница, крыша | Два этажа, вход, маршрут и стадии постройки | Модульные модели и материалы, экспорт с точками привязки по сетке |
| GEO-04 | 1 рабочее место и 1 склад с 3 состояниями заполнения | Изготовление детали и хранение материалов | Модельные источники, экспорт геометрии и состояний |
| GEO-05 | 1 модель кровати в трёх экземплярах и 1 простой предмет обстановки | Обставить дом и показать три назначенных спальных места, одно на верхнем этаже | Модельные источники, экспорт геометрии и привязок взаимодействия |
| GEO-06 | 1 источник еды и 1 порция пищи | Добыча или сбор еды, перенос и приём пищи | Модельные источники, экспорт геометрии и точки захвата |
| GEO-07 | 1 базовая модель жителя с 3 различимыми цветовыми вариантами одежды | Три жителя, путь и работа на этажах | Исходник модели и скелета, экспорт геометрии, материалов и привязок |
| GEO-08 | 3 модели груза — дерево, камень, изготовленная доска с отметкой | Различить перенос до склада, мастерской и стройки, отследить последнюю доску | Модельные источники, экспорт с общей точкой захвата |
| ANIM-01 | 6 действий — ожидание, ходьба, перенос, работа инструментом, еда, сон | Понятные переходы между состояниями жителя | Исходник анимаций, экспорт на скелет GEO-07 с именованными клипами |
| UI-01 | 8 значков — добыча, склад, стройка, лестница, еда, кровать, пауза, причина остановки | Команды и объяснение состояния | Собственные исходники значков, экспорт в формат интерфейса после определения импорта |
| UI-02 | 3 самостоятельных обозначения типов дома, если эти кнопки войдут в демо | Выбор шаблона, включая замену LEG-01–03 | Собственные редактируемые исходники, экспорт по размеру кнопок и масштабу UI |
| AUD-01 | 6 коротких звуков — шаг, добыча, обработка, установка, еда, подтверждение команды | События игрового маршрута | Собственные или разрешённые записи, исходный звук и экспорт в формат аудиосистемы |
| AUD-02 | 1 петля окружения склона | Фоновая среда во время партии | Исходная запись или проект, бесшовный экспорт в формат аудиосистемы |
| FONT-01 | 1 системный шрифт интерфейса Windows | Подписи команд и состояния на русском языке | Выбор установленного системного шрифта во время работы без включения файла шрифта в пакет. Проверить кириллицу и запасной `DEFAULT_GUI_FONT` на целевой Windows |
Для каждой записи звука при производстве дополнительно зафиксировать источник, приоритет, событие симуляции и правило повтора после загрузки. Контакт инструмента и звук сопровождают подтверждённое действие, момент расхода материала задаётся симуляцией. Отсутствие звукового устройства не должно мешать управлению. Музыкальное сопровождение пока не включено в бюджет первой сцены.
## Проверка готовности сцены и поставки
1. На контрольной камере M03 показать одновременно дом, склон, склад и трёх жителей. На обычной и дальней рабочих дистанциях отличить дерево от камня, груз от жителя, чертёж от построенной части и видимую причину остановки. Повторить при доступных масштабах интерфейса.
2. Проследить жителя с каждой моделью груза через дверь и по лестнице на верхнюю площадку. При скрытии этажа убедиться, что маршрут, ступени, кровать и рабочая позиция видны. Проверить переход от работы к еде и сну.
3. Сверить файлы итогового пакета с реестром, включая встроенные ресурсы viewer и выбранные шрифты. На каждом файле должны быть автор, происхождение, допустимые действия, необходимая атрибуция, подтверждение, исходник, экспорт и версия инструмента. У незаполненных записей остаётся владелец и действие до поставки.
4. Повторить экспорт одинаковых исходников с одинаковыми настройками, сравнить содержимое и записать результат. На Windows проверить кириллицу, запасной системный шрифт, читаемость кнопок и управление без звука.
[Этап M00](../plan/milestones/M00.md) · [Система материалов S20](../plan/systems/S20.md) · [Контрольные сцены S21](../plan/systems/S21.md)
+92
View File
@@ -0,0 +1,92 @@
# Проверка публичного поведения ACE
Проверка M00-A выполнена 2 декабря 2026 года для целевой серии ACE 0.9.6.22. Исходный набор содержит A01–A26 в [реестре паритета](parity.md#дополнения-и-изменения-ace). Ниже каждому пункту назначены опубликованная редакция правила, границы подтверждения и следующая проверка. A27–A40 дополняют набор самостоятельными наблюдениями. Все игровые сценарии `AT-Axx` ожидают реализации и результата на собственной сборке.
Опубликованное описание подтверждает заявленное правило. Численные коэффициенты, скрытые условия и сохранение промежуточного состояния требуют отдельных свидетельств либо явно выбранного собственного контракта. Указанные здесь тесты задают оригинальный игровой эквивалент. Полнота инвентаризации остаётся открытой до разбора каждого различимого поведения в просмотренных выпусках. [M00](milestones/M00.md)
## Обход выпусков
В пяти темах автора DaniAngione просмотрены номера и даты объявлений, заголовки изменений и исправлений. Предметно разобраны разделы, связанные с A01–A40, включая замену правил более поздними выпусками. Остальные перечисленные объявления пока служат индексом следующего прохода. Дата относится к созданию сообщения в UTC. Автор мог дополнять его несколькими исправлениями, поэтому суффиксные hotfix в одном сообщении требуют собственной даты при дальнейшей детализации.
| Период | Опубликованные редакции и проверенные сообщения | Остаток разбора |
|---|---|---|
| 24 декабря 2018 — 1 января 2019 | Начальное объявление **0.9** от [24 декабря](https://discourse.stonehearth.net/t/38843/1), затем [0.9.1](https://discourse.stonehearth.net/t/38843/44), [0.9.2](https://discourse.stonehearth.net/t/38843/137), [hotfix 1](https://discourse.stonehearth.net/t/38843/143), [hotfix 2](https://discourse.stonehearth.net/t/38843/154), [hotfix 3](https://discourse.stonehearth.net/t/38843/171). Проверены основания A01–A09. | Разложить начальную переработку кузнеца, военное снаряжение и охоту на отдельные условия и результаты. |
| 2–23 апреля 2019 | [0.9.3](https://discourse.stonehearth.net/t/39695/1), [0.9.3.1](https://discourse.stonehearth.net/t/39695/32), [0.9.3.2](https://discourse.stonehearth.net/t/39695/85), [0.9.3.3](https://discourse.stonehearth.net/t/39695/97). Проверены качество, корм, свет, требования растений и инструменты. | Выписать отдельные эффекты погоды, одежды, предпочтений еды и домашних животных. |
| 20 августа 2019 — 24 января 2020 | [0.9.4](https://discourse.stonehearth.net/t/40239/1), [0.9.4.1](https://discourse.stonehearth.net/t/40239/20), [0.9.4.2](https://discourse.stonehearth.net/t/40239/58), [0.9.4.3](https://discourse.stonehearth.net/t/40239/75), [0.9.4.4](https://discourse.stonehearth.net/t/40239/82), [0.9.4.5](https://discourse.stonehearth.net/t/40239/154), [0.9.4.6](https://discourse.stonehearth.net/t/40239/159), [0.9.4.7](https://discourse.stonehearth.net/t/40239/179). Проверены напитки, отказ от питья из обычной открытой воды, пасека и переработка вместилищ. | Отдельный проход по ловушкам, погоде, встречам и изменениям лечения. |
| 4 декабря 2020 — 6 декабря 2022 | [0.9.5](https://discourse.stonehearth.net/t/41422/1), [.1](https://discourse.stonehearth.net/t/41422/58), [.2](https://discourse.stonehearth.net/t/41422/76), [.3](https://discourse.stonehearth.net/t/41422/93), [.3b](https://discourse.stonehearth.net/t/41422/98), [.4](https://discourse.stonehearth.net/t/41422/110), [.4b](https://discourse.stonehearth.net/t/41422/119), [.5](https://discourse.stonehearth.net/t/41422/157), [.6](https://discourse.stonehearth.net/t/41422/167), [.7](https://discourse.stonehearth.net/t/41422/191), [.7c](https://discourse.stonehearth.net/t/41422/207), [.7d](https://discourse.stonehearth.net/t/41422/209), [.7e](https://discourse.stonehearth.net/t/41422/219), [.7f](https://discourse.stonehearth.net/t/41422/226), [.7g](https://discourse.stonehearth.net/t/41422/238), [.7h](https://discourse.stonehearth.net/t/41422/249). Проверены выделение пивовара, возврат семян, высотные условия полей и изменение жидкостей. | Проверить полноту вложенных суффиксных исправлений, отдельно раскрыть травы, ранения, новые культуры, животных и исходы Frostfeast. |
| 11 февраля — 3 июня 2023 | [0.9.6](https://discourse.stonehearth.net/t/43079/1), [.1](https://discourse.stonehearth.net/t/43079/4), [.2](https://discourse.stonehearth.net/t/43079/6), [.3/.3b](https://discourse.stonehearth.net/t/43079/7), [.4/.4b/.4c](https://discourse.stonehearth.net/t/43079/13), [.5/.5b/.5c](https://discourse.stonehearth.net/t/43079/20), [.6–.6e](https://discourse.stonehearth.net/t/43079/25), [.7–.7c](https://discourse.stonehearth.net/t/43079/32), [.8–.8c](https://discourse.stonehearth.net/t/43079/37), [.9–.9c](https://discourse.stonehearth.net/t/43079/47), [.10–.10c](https://discourse.stonehearth.net/t/43079/79), [.11–.11e](https://discourse.stonehearth.net/t/43079/94). Разобраны рынок и исправления доставки заданий. | Отдельный проход по каждому новому заказчику, ветвям заданий, титулам, предметам и взаимодействию модулей. |
| 31 октября 2023 — 23 января 2024 | [0.9.6.12](https://discourse.stonehearth.net/t/43079/112), [.12i–.12k](https://discourse.stonehearth.net/t/43079/115), [.13](https://discourse.stonehearth.net/t/43079/118), [.14](https://discourse.stonehearth.net/t/43079/123), [.14b/.14c](https://discourse.stonehearth.net/t/43079/125), [.14d](https://discourse.stonehearth.net/t/43079/130), [.14e](https://discourse.stonehearth.net/t/43079/134), [.15](https://discourse.stonehearth.net/t/43079/140). Разобраны мирная сезонная ветвь, стартовое окно и память о питомце. | Полный граф сезонных задач, все награды, отдельные исправления возобновления и недоступности ветвей. |
| 12 мая 2024 — 27 августа 2025 | [0.9.6.16](https://discourse.stonehearth.net/t/43079/151), [.16d](https://discourse.stonehearth.net/t/43079/158), [.16e–.16h](https://discourse.stonehearth.net/t/43079/166), [.16i](https://discourse.stonehearth.net/t/43079/168), [.17–.17e](https://discourse.stonehearth.net/t/43079/184), [.18](https://discourse.stonehearth.net/t/43079/200), [.18c](https://discourse.stonehearth.net/t/43079/207), [.18d](https://discourse.stonehearth.net/t/43079/208), [.19](https://discourse.stonehearth.net/t/43079/211), [.19c](https://discourse.stonehearth.net/t/43079/216), [.19d](https://discourse.stonehearth.net/t/43079/219), [.19e](https://discourse.stonehearth.net/t/43079/220), [.19f/.19g](https://discourse.stonehearth.net/t/43079/224). Проверены очереди ремесла и условия первого Firstbloom. | Сопоставить пересекающиеся встроенные и отдельные hotfix, затем детализировать инженерию, бои и все варианты сезонных заданий. |
| 24 декабря 2025 — 27 ноября 2026 | [0.9.6.20](https://discourse.stonehearth.net/t/43079/240), [.20b, 6 января 2026](https://discourse.stonehearth.net/t/43079/242), [.21/.21b, 1 апреля](https://discourse.stonehearth.net/t/43079/245), [.22/.22b/.22c, сообщение 27 ноября](https://discourse.stonehearth.net/t/43079/246). Предметно проверены A19–A26, повтор сезонной ветви и сохранение качества при преобразовании. Последнее просмотренное объявление — .22c внутри сообщения 246. | Определить даты встроенных .22b/.22c, разрешить четыре вымышленных пункта .21 и разложить новые боевые способности .22. |
Текущий заголовок темы меняется по мере выхода патчей. Сообщение `43079/1` описывает 0.9.6, `39695/1` — 0.9.3, `40239/1` — 0.9.4. Номер версии в заголовке всей темы не датирует ранний текст. В объявлении .21 автор прямо предупреждает о четырёх вымышленных пунктах. Утверждение из этого поста получает подтверждение другим выпуском либо остаётся открытым. [Объявление .21](https://discourse.stonehearth.net/t/43079/245)
## Проверка исходных A01–A26
Здесь «описано» означает наличие публичного утверждения автора. Столбец последующей проверки содержит требования к свидетельствам и к собственной приёмке, которые пока остаются открытыми.
| ID | Проверенное правило и редакция | Последующая проверка |
|---|---|---|
| <a id="a01"></a>[A01](parity.md#a01) | 0.9 вводит ускорение роста от близкой воды. 0.9.3 меняет измерение влажности и света, 0.9.3.2 распределяет требования по сложности культур. | `AT-A01` сравнивает одинаковые поля по одному фактору, затем сезон совместно с поливом. Уточнить границы радиуса и насыщения для каждой культуры. [0.9](https://discourse.stonehearth.net/t/38843/1), [0.9.3.2](https://discourse.stonehearth.net/t/39695/85) |
| <a id="a02"></a>[A02](parity.md#a02) | 0.9 объявляет управление потоком через затвор. | `AT-A02` проверяет закрытие и повторное открытие, загрузку в закрытом состоянии, объём воды и межчанковую границу. Геометрия проходного сечения и воздействие давления требуют отдельного свидетельства. [0.9](https://discourse.stonehearth.net/t/38843/1) |
| <a id="a03"></a>[A03](parity.md#a03) | 0.9 объявляет подъём воды насосом. Переработка 0.9.5.5 затрагивает выходящие в воздух трубы. | `AT-A03` проверяет перенос между нижней и верхней ёмкостью и сохранение объёма. Все направления установки проверить после исправлений .14, пределы дальности привязать к отдельному варианту насоса. [0.9](https://discourse.stonehearth.net/t/38843/1), [0.9.5.5](https://discourse.stonehearth.net/t/41422/157), [.14](https://discourse.stonehearth.net/t/43079/123) |
| <a id="a04"></a>[A04](parity.md#a04) | 0.9 описывает сырьё, зависящее от места добычи, включая глину на дне водоёмов. | `AT-A04` размечает одинаковые объёмы в двух местах и учитывает полученные материалы. Полный перечень месторождений и допустимых заменителей остаётся задачей S02/S07. [0.9](https://discourse.stonehearth.net/t/38843/1) |
| <a id="a05"></a>[A05](parity.md#a05) | Высокогорный биом с собственной флорой и сырьём опубликован в 0.9. | `AT-A05` обеспечивает самостоятельное снабжение оригинального биома. Необходимо выписать различия доступности каждого ресурса и его производственные последствия. [0.9](https://discourse.stonehearth.net/t/38843/1) |
| <a id="a06"></a>[A06](parity.md#a06) | 0.9 различает три класса топлива и требования конкретного производства. | `AT-A06` проверяет подходящую партию, отказ при неподходящем топливе и расход после загрузки. Уточнить требования каждого станка. [0.9](https://discourse.stonehearth.net/t/38843/1) |
| <a id="a07"></a>[A07](parity.md#a07) | 0.9 объявляет углублённую переработку металлов. | Открытый вопрос Q-A07 — какие промежуточные стадии и альтернативные входы различаются в целевой редакции? Общее объявление не закрывает цепочки. В `AT-A07` нужен отдельный маршрут каждой подтверждённой цепочки. [0.9](https://discourse.stonehearth.net/t/38843/1) |
| <a id="a08"></a>[A08](parity.md#a08) | 0.9 позволяет задавать предпочтения типов оружия и щита. | `AT-A08` меняет комплект и проверяет учёт снятых вещей. Уточнить приоритет предпочтения относительно профессии, уровня и отсутствия подходящей вещи. [0.9](https://discourse.stonehearth.net/t/38843/1) |
| <a id="a09"></a>[A09](parity.md#a09) | 0.9 публикует маршрут патруля из знамён. | `AT-A09` проверяет обход. Возобновление после тревоги в исходной строке требует отдельного свидетельства о позиции продолжения. Ограничение размера патруля вынесено в A35. [0.9](https://discourse.stonehearth.net/t/38843/1) |
| <a id="a10"></a>[A10](parity.md#a10) | 0.9.4 описывает питьё как потребность комфорта с предпочтениями и непереносимостью. 0.9.4.2 убирает питьё из обычных открытых водоёмов. | `AT-A10` проверяет настроение, допустимый напиток и доступность воды. Общая доступность любой реки относится к ранней редакции. [0.9.4](https://discourse.stonehearth.net/t/40239/1), [0.9.4.2](https://discourse.stonehearth.net/t/40239/58) |
| <a id="a11"></a>[A11](parity.md#a11) | Приготовление напитков опубликовано в 0.9.4. В 0.9.5 основные производственные обязанности переданы новой профессии пивовара. | `AT-A11` должен покрывать разные виды обработки и сохранение занятого сосуда. Состав действующих рецептов и открытие станков сверять с 0.9.5, включая последующие изменения. [0.9.4](https://discourse.stonehearth.net/t/40239/1), [0.9.5](https://discourse.stonehearth.net/t/41422/1) |
| <a id="a12"></a>[A12](parity.md#a12) | 0.9.3 связывает специальный корм с качеством продукции стада. .22 исправляет применение качества корма. | `AT-A12` различает качество и количество продукции, включает корм разных качеств и контрольный рацион. Уточнить действующую функцию бонуса и применимость к каждой продукции. [0.9.3](https://discourse.stonehearth.net/t/39695/1), [.22](https://discourse.stonehearth.net/t/43079/246) |
| <a id="a13"></a>[A13](parity.md#a13) | 0.9.4.5 меняет стоимость и привлекательность качественных вещей. 0.9.6.3 меняет округление дешёвых товаров. | `AT-A13` сохраняет качество при переноске и различает итоговую цену. Точные множители и правила округления требуют отдельной таблицы. [0.9.4.5](https://discourse.stonehearth.net/t/40239/154), [0.9.6.3](https://discourse.stonehearth.net/t/43079/7) |
| <a id="a14"></a>[A14](parity.md#a14) | .14 добавляет извещение об умершем питомце и памятную урну с его данными. | `AT-A14` проверяет однократное создание и сохранение связей. Исходный источник подтверждает именно смерть питомца, а идемпотентность после загрузки задаёт наша проверка. [.14](https://discourse.stonehearth.net/t/43079/123) |
| <a id="a15"></a>[A15](parity.md#a15) | 0.9.6 вводит физически присутствующих торговцев и занятие рыночного места. | `AT-A15` проверяет занятие и освобождение места и повторное открытие торговли в течение визита. Уточнить поведение при удалении занятого места. [0.9.6](https://discourse.stonehearth.net/t/43079/1) |
| <a id="a16"></a>[A16](parity.md#a16) | 0.9.6 ограничивает посетителей уровнями города и места. | `AT-A16` меняет эти два фактора независимо. Отдельно проверить посетителя без рыночного места и специализированные места. [0.9.6](https://discourse.stonehearth.net/t/43079/1) |
| <a id="a17"></a>[A17](parity.md#a17) | В 0.9.6 есть особые цены желаемых товаров. .2 исправляет конфликт спроса с собственным ассортиментом. | `AT-A17` сравнивает спрос и обычную продажу, исключает ценовой цикл и проверяет однократное списание оплаты и груза. [0.9.6](https://discourse.stonehearth.net/t/43079/1), [.2](https://discourse.stonehearth.net/t/43079/6) |
| <a id="a18"></a>[A18](parity.md#a18) | 0.9.6 позволяет настраивать предпочтения категорий посещения. | `AT-A18` использует одинаковую историю и меняет только одну настройку. Открытый вопрос Q-A18 — это жёсткий запрет либо изменение вероятности для каждого положения настройки? [0.9.6](https://discourse.stonehearth.net/t/43079/1) |
| <a id="a19"></a>[A19](parity.md#a19) | .22 повышает влияние прошлой торговли относительно богатства. | `AT-A19` сравнивает торговавший и контрольный города при равном богатстве. Нужна опубликованная формула либо собственная явно выбранная функция. [.22](https://discourse.stonehearth.net/t/43079/246) |
| <a id="a20"></a>[A20](parity.md#a20) | .22 связывает опыление с подходящими растениями и качеством улья. .22b уточняет последствия укрытия. | `AT-A20` отдельно считает улучшение растений, развитие и спад качества улья, повтор после задержки и производство под укрытием. Точные интервалы и пороги открыты. [.22/.22b](https://discourse.stonehearth.net/t/43079/246) |
| <a id="a21"></a>[A21](parity.md#a21) | .22 усиливает затопление и заморозки, сохраняя различия морозостойкости культур. | `AT-A21` варьирует мороз и затопление отдельно, затем совместно с поливом. Нужны пороги и исключения для каждой культуры. [.22](https://discourse.stonehearth.net/t/43079/246) |
| <a id="a22"></a>[A22](parity.md#a22) | .22 вводит сезонные вероятности новой дичи и заменяемый мясной ингредиент. | `AT-A22` проверяет появление, ловлю и замену в собственном рецепте. Требуется перечень применимых рецептов. [.22](https://discourse.stonehearth.net/t/43079/246) |
| <a id="a23"></a>[A23](parity.md#a23) | .12 разрешает пройти Candledark без боёв через выбор, доступный в Peaceful. .20b поясняет финал повторного мирного прохождения. | `AT-A23` проверяет доступность выбора по сложности. Условие выживания боевой ветви нельзя автоматически применять к мирной. Нужен отдельный проверяемый исход повторной ветви. [.12](https://discourse.stonehearth.net/t/43079/112), [.20b](https://discourse.stonehearth.net/t/43079/242) |
| <a id="a24"></a>[A24](parity.md#a24) | .14 задаёт старт Frostfeast для города уровня 2+ во временном окне и продолжение уже начатой истории после его закрытия. | `AT-A24` сохраняет историю на обеих сторонах окна. Исходную ссылку `/240` следует подписать как зимнюю .20. Условия повтора раскрывает A40. [.14](https://discourse.stonehearth.net/t/43079/123), [.20](https://discourse.stonehearth.net/t/43079/240) |
| <a id="a25"></a>[A25](parity.md#a25) | .22 переносит животных удалённого пастбища в подходящее существующее при наличии вместимости. | `AT-A25` учитывает переведённых и оставшихся животных при нулевой, частичной и достаточной вместимости. [.22](https://discourse.stonehearth.net/t/43079/246) |
| <a id="a26"></a>[A26](parity.md#a26) | .22 повышает приоритет основных потребностей относительно восстановления в кровати. | `AT-A26` проверяет голод одновременно с ранением. Порог переключения и возобновление лечения остаются открытыми вопросами. [.22](https://discourse.stonehearth.net/t/43079/246) |
## Дополнительные наблюдения
Для каждого ID действует сценарий `AT-` с тем же номером. Наблюдаемое правило и предлагаемый самостоятельный тест приведены раздельно в столбцах. Изменение количества входов, результатов либо условий открытия получает отдельный сценарий при дальнейшем разборе.
| ID | Модуль и редакция правила | Триггер и эффект | Собственный эквивалент и проверка | Система и этап |
|---|---|---|---|---|
| <a id="a27"></a>A27 | Качество, 0.9.3 | Качество ингредиентов меняет шанс качества изделия, ограниченный умением ремесленника. | Оригинальный рецепт из двух ресурсов. Проверить низкий и высокий уровни мастерства, одинаковый seed и сохранение перед выдачей изделия. [Источник](https://discourse.stonehearth.net/t/39695/1) | [S07](systems/S07.md), [M04](milestones/M04.md) |
| <a id="a28"></a>A28 | Поля, 0.9.3.2 | Требования влажности и состав показателей зависят от сложности культуры и открытых возможностей фермера. | Собственные простая и сложная культуры. Проверить информацию до и после обучения и остановку при неподходящей влажности. [Источник](https://discourse.stonehearth.net/t/39695/85) | [S10](systems/S10.md), [S18](systems/S18.md), [M05](milestones/M05.md) |
| <a id="a29"></a>A29 | Добыча, 0.9.3.3 | Улучшенный инструмент шахтёра меняет скорость и качество добычи. | Две версии собственного инструмента на одинаковой жиле. Сравнить завершённую работу и качество, проверить сохранение во время добычи. [Источник](https://discourse.stonehearth.net/t/39695/97) | [S07](systems/S07.md), [M04](milestones/M04.md) |
| <a id="a30"></a>A30 | Напитки, 0.9.4 | Время суток влияет на выбор напитка, личные предпочтения имеют более высокий приоритет. | Доступны два собственных напитка. Сравнить утро и вечер у обычного жителя и жителя с непереносимостью. [Источник](https://discourse.stonehearth.net/t/40239/1) | [S05](systems/S05.md), [M05](milestones/M05.md) |
| <a id="a31"></a>A31 | Пасека, 0.9.4.2 | Производство мёда в улье останавливается зимой. | Сохранить собственную пасеку до границы сезона, проверить остановку, возобновление и отсутствие накопления пропущенной продукции. Требуется сверка зимних исключений в целевой редакции. [Источник](https://discourse.stonehearth.net/t/40239/58) | [S09](systems/S09.md), [S10](systems/S10.md), [M05](milestones/M05.md) |
| <a id="a32"></a>A32 | Вместилища, 0.9.4.5 | Специальный чан допускает несколько жидкостей одной категории. | В собственный аналог чана загрузить два совместимых напитка, затем предложить несовместимый груз. Проверить вместимость и владельца при отказе. Исключение относится к указанному типу тары. [Источник](https://discourse.stonehearth.net/t/40239/154) | [S06](systems/S06.md), [M05](milestones/M05.md) |
| <a id="a33"></a>A33 | Профессии культур, 0.9.4 | Событие открывает обработку кости культурам без исходного доступа. | Оригинальная учебная встреча. Проверить доступ до и после финала, сохранение на развилке и однократное открытие. Позднее .20/.22 блокируют ненужный повтор при полном комплекте знаний. [0.9.4](https://discourse.stonehearth.net/t/40239/1), [.20](https://discourse.stonehearth.net/t/43079/240) | [S07](systems/S07.md), [S13](systems/S13.md), [M06](milestones/M06.md) |
| <a id="a34"></a>A34 | Травы, 0.9.5.1 | Очистка посадочного сосуда возвращает семя и удаляет растение. | Перенести собственное растение в улучшенный сосуд через возвращённое семя. Проверить единственного владельца и сохранение между действиями. [Источник](https://discourse.stonehearth.net/t/41422/58) | [S06](systems/S06.md), [S10](systems/S10.md), [M05](milestones/M05.md) |
| <a id="a35"></a>A35 | Патруль, 0.9.5.3 | Одна группа ограничивает число одновременно патрулирующих воинов. Опубликованное значение по умолчанию — шесть. | Назначить семь воинов одной группы и наблюдать участие и ротацию, затем две группы. Точный порядок отдыха и замещения требует отдельного подтверждения. [Источник](https://discourse.stonehearth.net/t/41422/93) | [S12](systems/S12.md), [M07](milestones/M07.md) |
| <a id="a36"></a>A36 | Поля, 0.9.5.3 | Высотный слой биома влияет на влажность, свет и допустимость поля. | Два поля собственного биома на разных высотах при одинаковой культуре и сезоне. Проверить граничную высоту и объяснение запрета в UI. [Источник](https://discourse.stonehearth.net/t/41422/93) | [S02](systems/S02.md), [S10](systems/S10.md), [M05](milestones/M05.md) |
| <a id="a37"></a>A37 | Доставка, 0.9.6.2 | Исправлен учёт груза задания, принесённого прямо с земли в специальный склад. | Два одинаковых собственных заказа получают груз с земли и из обычного склада. Награда выдаётся один раз, груз имеет одного владельца до и после загрузки. [Исходная ошибка](https://discourse.stonehearth.net/t/43079/1), [исправление](https://discourse.stonehearth.net/t/43079/6) | [S04](systems/S04.md), [S06](systems/S06.md), [S13](systems/S13.md), [M07](milestones/M07.md) |
| <a id="a38"></a>A38 | Кооператив, 0.9.6.3 | Игроки могут передавать друг другу эксклюзивные рыночные места, полученные развитием города. | Передать собственное специализированное место союзнику. Проверить право использования, оплату и единственного владельца при повторе сетевой команды и загрузке. [Источник](https://discourse.stonehearth.net/t/43079/7) | [S11](systems/S11.md), [S16](systems/S16.md), [M09](milestones/M09.md) |
| <a id="a39"></a>A39 | Производство, 0.9.6.16 | У ремесленника есть основная и вторичная очереди с независимым включением. Основная имеет приоритет. | Собственный разовый и поддерживающий запас заказ. Проверить приоритет, выключение одной очереди и сохранение уже зарезервированных материалов. [Источник](https://discourse.stonehearth.net/t/43079/151) | [S04](systems/S04.md), [S07](systems/S07.md), [M04](milestones/M04.md) |
| <a id="a40"></a>A40 | Повтор событий, 0.9.6.20b | Исправлен старт Frostfeast при уже открытых рецептах. Для мирного повторного Candledark дано особое объяснение завершения. | Собственная повторная сезонная история при полном комплекте знаний. `AT-A40-F` проверяет вход зимней ветви, `AT-A40-C` — мирный финал без ожидания отсутствующих вторжений. Требуется выписать точные условия финала из свидетельства. [Источник](https://discourse.stonehearth.net/t/43079/242) | [S13](systems/S13.md), [M07](milestones/M07.md) |
## Открытые вопросы и следующий проход
| Вопрос | Проверка для закрытия и владелец |
|---|---|
| Q-ACE-COVERAGE — какие самостоятельные поведения ещё не выделены из перечисленных объявлений? | M00 и владельцы S05/S07/S10/S11/S12/S13 проходят индекс по порядку, добавляют строки для каждого отличающегося результата и связывают заменённые редакции. Последняя точка нынешнего просмотра — сообщение 246, раздел .22c. До полного разбора статус инвентаризации остаётся «в работе». |
| Q-ACE-21 — какие четыре пункта .21 вымышлены? | M00 ищет опубликованное уточнение автора либо независимое подтверждение выпуска каждого спорного правила. Предположения читателей не закрывают вопрос. Новые строки этой проверки опираются на другие сообщения. |
| Q-ACE-DATES — когда появились суффиксные исправления в редактируемых сообщениях? | M00 сверяет публичную историю объявления или отдельный авторский анонс. Сохраняет дату создания и дату подтверждения для конкретного суффикса. Текущий срез включает видимые .22b/.22c без выдуманной индивидуальной даты. |
| Q-A07 — какие стадии металлургии различаются в актуальных правилах? | S07/M04 составляет цепочки из публичных описаний и требований профессий. Для каждой ветви указывает вход, открытие, выход и точку сохранения. |
| Q-A18 — как настройки влияют на категорию торговцев? | S11/M06 устанавливает смысл каждого положения настройки и исключения для специализированных мест. Вероятностный вес нельзя объявлять жёстким запретом. |
| Q-ACE-EVENTS — какие условия и исходы есть у каждой сезонной и культурной ветви? | S13/M07 описывает вход, сложность, шаги, награду, повтор и восстановление для каждой ветви отдельно. A23, A24, A33 и A40 задают первые различия. |
| Q-ACE-NUMBERS — какие численные требования доступны в публичных свидетельствах? | Владельцы систем уточняют влажность, радиусы, качество, вместимость, цены и сроки. При отсутствии описания фиксируют конкретный пробел и проверяемый собственный выбор. |
Для M01 подтверждена необходимость хранить устойчивые ссылки, владение грузом, командный прогресс и состояние отложенных действий. Приведённые сценарии требуют сравнения продолжения после загрузки и защиты от повторного применения. Выбор внутренней архитектуры выполняется по [M01](milestones/M01.md) и [правилу VoidLibrary](void-library.md). Номера будущих библиотечных issues добавляются после реального поиска и регистрации.
[Реестр паритета](parity.md) · [Мастер-план](../../PLAN.md)
+114
View File
@@ -0,0 +1,114 @@
# Свидетельства поведения базовой Stonehearth
Проверка M00-B от 2 декабря 2026 года относится к публичным описаниям базовой игры до версии 1.1 с её декабрьским исправлением. Исходный инвентарь B01–B24 сохранён в [реестре паритета](parity.md). Здесь каждому пункту назначены проверенный выпуск и конкретный остаток исследования. B25–B40 расширяют инвентарь. Все `AT-Bxx` ожидают реализации и проверки на собственной Windows-сборке.
Источники описывают наблюдаемое поведение. Собственные сценарии ниже задают условия будущей проверки. Неустановленные коэффициенты, исходы и изменения между выпусками получают открытый вопрос. Передаваемые в M01 ограничения относятся к воспроизводимому состоянию, владению и возобновлению работ. Полный обход ранних выпусков продолжается по очереди в конце документа. [M00](milestones/M00.md) · [Мастер-план](../../PLAN.md)
## Источники и пройденный диапазон
Тексты объявлений прочитаны через официальный `ISteamNews/GetNewsForApp`. Ссылки ведут к двум полученным срезам ленты с фиксированным `enddate` и полным содержимым. Текстовый фрагмент ссылки указывает заголовок. В JSON запись находят по полю `title`, дату проверяют по `date`, автора по `author` и источник по `feedname`. Дата в таблице приведена в UTC. Витрина Steam может показывать предыдущий день. Старые адреса `announcements/detail`, полученные из части записей API, при проверке перенаправляли на общую страницу событий. Запросы отдельных записей с `count=1` завершались сбросом HTTPS, поэтому здесь использованы успешно полученные срезы по 100 записей.
| Дата UTC | Выпуск и прочитанный материал | Зафиксированная граница |
|---|---|---|
| 2016-09-13 | Alpha 18, стабильный выпуск. Строительство, развитие фермера, торговля и жизнь жителей. [Alpha 18 is Here!][a18] | Объявление выпуска прочитано. Предшествующие альфы и промежуточные исправления ещё не пройдены. |
| 2016-10-28 | Alpha 19, стабильный выпуск. Развитие пустынной культуры, стройка и управление модами. [Alpha 19 Has Arrived!][a19] | Старые ветви развития сопоставить с заменившей их кампанией Alpha 24+. |
| 2017-01-24 | Alpha 20, стабильный выпуск. Настроение, спасение и восстановление жителей. [Alpha 20][a20] | Установлены выпущенные механики, ранее описанные в нестабильной сборке. |
| 2017-01-30 | Исправление Alpha 20, текст обновлён до release 701 от 31 января. [Release 701][r701] | Учтены голод, восстановление и сохранение эффектов лечения. |
| 2018-04-05 | Alpha 24.4, нестабильный выпуск. Погода, прогресс города и торговцы. [Alpha 24.4][a244] | Сам по себе не подтверждает поставку в стабильной ветке. |
| 2018-04-12 | Alpha 24.5, нестабильный выпуск. Workshop и изменение урона погоды в мирном режиме. [Alpha 24.5][a245] | Для точного исключения урона в 1.1 открыт B31. |
| 2018-05-03 | Alpha 24.8, нестабильный выпуск. Кооператив, шаблоны, доступ работников и интерфейс стройки. [Alpha 24.8][a248] | Стабильное подтверждение основной поверхности кооператива получено в Alpha 24+. |
| 2018-06-08 | Alpha 24+, стабильное объединение изменений нового строителя, кооператива, погоды, развития города, модов и растений. [Alpha 24+][a24] | Прочитано объявление целиком. Подробные журналы каждого промежуточного 24.x ещё требуют отдельного обхода. |
| 2018-07-18 | Beta r876, нестабильный выпуск. Перемещение дверей и окон, исправления размещения, торговли и повторной отправки жителей. [r876][r876] | Стабильная Beta перечисляет r876 среди включённых выпусков. |
| 2018-07-18 | Beta на стабильной ветке. Культура, достопримечательности, сотрудничество, специальность, сезоны и финальное событие. [Beta on Steam Stable][beta] | Встроенная сводка прямо названа неполной. Ссылки на r862–r875 перечислены, их полные тексты ещё не проверены. |
| 2018-07-25 | Выпуск 1.0. [Stonehearth is Now 1.0][v10] | Подтверждена поставка 1.0. Обещание будущей работы над 1.1 не служит свидетельством её механик. |
| 2018-09-19 | r898, нестабильный выпуск. Путешественники и исправления торговли. [r898][r898] | Механика визитов повторно подтверждена в 1.1. |
| 2018-11-16 | 1.05, стабильный выпуск. [Stonehearth 1.05][v105] | Подтверждён перенос r898 и r905 с исправлениями на стабильную ветку. Полные тексты r905 и его исправления остаются в очереди. |
| 2018-12-12 | 1.1, стабильный выпуск. Путешественники, новые встречи, выход из застревания, ремесло и моды. [Stonehearth 1.1][v11] | Последнее крупное обновление по объявлению разработчика. Прочитаны все игровые разделы. |
| 2018-12-20 | Исправление 1.1. [Hotfix for Stonehearth 1.1][v11fix] | Последний просмотренный патч базовой игры. Прочитаны все шесть исправлений, включая сортировку владельца кровати, список шаблонов и закрытие окна загрузки. |
Также прочитано актуальное описание игры на витрине. Оно подтверждает общие возможности, а вопросы о точных правилах версии 1.1 требуют датированного свидетельства. [Описание игры][store]
## Проверка первоначальных B01–B24
Ссылка в ID ведёт к собственному сценарию в основном реестре. Здесь «подтверждено» относится к указанной части поведения в указанном выпуске. Остаток проверки входит в соответствующий `AT-Bxx`.
| ID | Проверенное поведение и версия | Открытый вопрос и продолжение проверки |
|---|---|---|
| <a id="b01"></a>[B01](parity.md#b01) | Новый старт использует процедурный рельеф. [Витрина][store] | Гарантирует ли 1.1 одинаковое размещение ресурсов при одинаковом seed и настройках? `AT-B01` повторяет генерацию и сравнивает доступные залежи. |
| <a id="b02"></a>[B02](parity.md#b02) | Перекрывающиеся комнаты образуют общий план. Alpha 24+. [Новый строитель][a24] | Как пересечение комнат определяет смету и общие блоки? `AT-B02` считает материалы и объём пересечения до начала работ и после. |
| <a id="b03"></a>[B03](parity.md#b03) | Комнату можно поставить поверх другой. Alpha 24+. [Новый строитель][a24] | Объявление не определяет правила постоянной лестницы. `AT-B03` требует доступной кровати наверху и проверяет маршрут после снятия временного доступа. |
| <a id="b04"></a>[B04](parity.md#b04) | Отдельный воксель настила редактируется вытягиванием или вдавливанием. Alpha 24+. [Новый строитель][a24] | Какая часть уже начатой стройки допускает такую правку в 1.1? `AT-B04` начинает с чертежа, продолжение после выдачи работ остаётся отдельной проверкой. |
| <a id="b05"></a>[B05](parity.md#b05) | Застой стройки вызывает поиск недоступных частей и их подсветку. Alpha 24+. [Новый строитель][a24] | В исходном объявлении задержка около 30 секунд. Точное значение 1.1 открыто. `AT-B05` возвращает доступ лестницей и проверяет продолжение того же заказа. |
| <a id="b06"></a>[B06](parity.md#b06) | После окончания здания убираются временные леса и лестницы. Alpha 24+. [Новый строитель][a24] | Как очистка ведёт себя при отмене или неполной стройке? `AT-B06` отдельно проверяет завершение, отмену и сохранение перед разборкой. |
| <a id="b07"></a>[B07](parity.md#b07) | Мысли о еде, безопасности, постели и пространстве влияют на настроение. Alpha 20 stable. [Настроение][a20] | Полный перечень мыслей, сроков и сочетаний в 1.1 открыт. `AT-B07` меняет по одному условию и связывает сводку с причиной изменения. |
| <a id="b08"></a>[B08](parity.md#b08) | Снабжение едой и развитие поселения входят в основной игровой цикл. [Витрина][store] | Формулы иммиграции 1.1 не установлены. Alpha 24.4 меняет требования еды и богатства. `AT-B08` фиксирует население, пороги и принятие жителя. [Alpha 24.4][a244] |
| <a id="b09"></a>[B09](parity.md#b09) | Третья культура опирается на охоту и каменное ремесло. Beta stable. [Культуры][beta] | Каковы все различимые открытия профессий и стартовые предметы трёх культур? `AT-B09` получает отдельную матрицу культур до M06. |
| <a id="b10"></a>[B10](parity.md#b10) | В штатных биомах при старте встречаются достопримечательности. Beta stable. [Генерация][beta] | Какие объекты размещаются условно и как переживают редактирование? `AT-B10` проверяет собственную руину до и после сохранения. |
| <a id="b11"></a>[B11](parity.md#b11) | При создании партии выбирается сезон, который меняет распределение погоды. Beta stable. [Сезоны][beta] | Список разрешённых стартовых сочетаний и длительности сезонов по биомам открыт. `AT-B11` сравнивает один биом с двумя стартами. |
| <a id="b12"></a>[B12](parity.md#b12) | В предпочтительный сезон рост культуры ускоряется вдвое. Beta stable. [Земледелие][beta] | Как взаимодействуют сезон, погода и прочие модификаторы в 1.1? `AT-B12` сначала измеряет изолированное правило, затем сочетания. |
| <a id="b13"></a>[B13](parity.md#b13) | После цепочки развития доступен перенос до трёх жителей и десяти предметов в новую партию. Alpha 24+. [Повторное заселение][a24] | Объявление допускает перенос городского бонуса с особым предметом. Как учитываются ограничения профессий и расход стека? `AT-B13` сверяет отправление и прибытие. |
| <a id="b14"></a>[B14](parity.md#b14) | Цепочка сотрудничества открывается после второго уровня города и может дать новую специальность. Beta stable. [Сотрудничество][beta] | «Мало боя» в описании не устанавливает полную доступность при мирной сложности. `AT-B14` отдельно проверяет этот режим и состав каждого исхода. |
| <a id="b15"></a>[B15](parity.md#b15) | Специалист размещает участки земли, источники воды, залежи и достопримечательности. Beta stable. [Специальность][beta] | Какие затраты, ограничения и рабочие позиции имеет каждый тип изменения? `AT-B15` делится по типам и сверяет доступность после правки. |
| <a id="b16"></a>[B16](parity.md#b16) | Необязательное финальное событие открывается после одной из двух кампаний. Beta stable. [Финал][beta] | Возможность отказа, мирный режим, поражение и награды каждого пути требуют отдельных свидетельств. `AT-B16` проверяет оба входа и сохранение до запуска. |
| <a id="b17"></a>[B17](parity.md#b17) | Упавшего в бою жителя можно спасти, перенести в постель и восстановить, ускоряя уходом специалиста. Alpha 20 stable. [Спасение][a20] | Условия смерти, таймер спасения и возврата к службе в 1.1 открыты. `AT-B17` сохраняет во время переноски и восстановления. |
| <a id="b18"></a>[B18](parity.md#b18) | Зарезервированная гостевая кровать допускает визиты. Обстановка и постель влияют на удовлетворённость и подарок. 1.1. [Путешественники][v11] | Условие визита проверяется по доступной кровати. `AT-B18` варьирует кровать, привлекательность и уровень города отдельно, проверяет покупку и единственную выдачу подарка. |
| <a id="b19"></a>[B19](parity.md#b19) | До восьми игроков размещают поселения на общей карте у хозяина. Alpha 24+ stable. [Кооператив][a24] | Какими правами защищены чужие объекты при каждом действии? `AT-B19` фиксирует разрешённые и отклонённые команды двух владельцев. |
| <a id="b20"></a>[B20](parity.md#b20) | Между городами доступна торговля товарами и золотом. Alpha 24.8 и Alpha 24+ stable. [Торговля][a248] · [Стабильный выпуск][a24] | Поведение незавершённой сделки при отключении не описано. `AT-B20` проверяет подтверждение, разрыв связи и отсутствие повторного расхода. |
| <a id="b21"></a>[B21](parity.md#b21) | Отряды игроков помогают отражать нападения друг на друга. Alpha 24.8. [Совместная оборона][a248] | Какие команды требуют разрешения владельца? Точное правило остаётся вопросом для `AT-B21` и таблицы прав M09. |
| <a id="b22"></a>[B22](parity.md#b22) | Хозяин и клиент сохраняют и загружают шаблоны нового строителя. Alpha 24.8. [Шаблоны][a248] | Является ли шаблон локальным, какова область доступа и сохраняется ли смещение по высоте? `AT-B22` переносит шаблон между участками и ролями. |
| <a id="b23"></a>[B23](parity.md#b23) | Определения контента и сценарии допускают расширение модами. [Витрина][store] · [Моды в Alpha 24+][a24] | Полный набор поддерживаемых точек расширения 1.1 открыт. `AT-B23` использует собственные предмет, встречу и API, проверяет восстановление набора правил. |
| <a id="b24"></a>[B24](parity.md#b24) | Специалист создаёт помощников для повторяемых работ. Beta stable. [Помощники][beta] | Полный набор поручений и взаимодействие с резервами жителей в 1.1 открыт. `AT-B24` проверяет один результат совместно выбранного задания. |
## Дополнительные наблюдения B25–B40
Каждая строка задаёт новый `AT-Bxx`. Предполагаемые названия предметов и событий новой игры определяются её собственным контентом. Версия указывает источник проверенной части контракта. Условия продолжения исследования записаны в последнем столбце.
| ID и модуль | Триггер и наблюдаемый эффект | Собственный сценарий и ожидаемый результат | Системы, этап и проверенное свидетельство | Оставшийся вопрос |
|---|---|---|---|---|
| <a id="b25"></a>B25. Профессии | Житель получает опыт работой. Условие развития и инструмент позволяют сменить профессию. | `AT-B25`. Создать собственную пару профессий, проверить отказ без инструмента и переход после открытия. Сохранить опыт и инструмент. | [S07](systems/S07.md) · [M04](milestones/M04.md). [Описание развития жителей][store] | Датированный полный перечень условий 1.1 по каждой культуре открыт. |
| <a id="b26"></a>B26. Земледелие | Уровень фермера открывает культуры. Мастер допускает торговые предложения с чужими семенами. | `AT-B26`. Перейти через одно открытие, затем получить собственную инокультурную посадку через торговца. До открытия она недоступна. | [S07](systems/S07.md) · [S10](systems/S10.md) · [M06](milestones/M06.md). [Alpha 18][a18] | Конкретные уровни культур и изменённые условия 1.1 проверить по отдельности. |
| <a id="b27"></a>B27. Торговля | Продажа ограничена запасом золота торговца. | `AT-B27`. Продать партию на границе наличности, повторить запрос и сверить остатки товара и денег обеих сторон после загрузки. | [S11](systems/S11.md) · [M06](milestones/M06.md). [Alpha 18][a18] | Правило частичного принятия партии и пополнения наличности 1.1 открыто. |
| <a id="b28"></a>B28. Пища | Пища портится и исчезает после полного гниения. | `AT-B28`. Поместить две собственные партии разных сроков в склад. Пройти границу порчи с сохранением, проверить единственный расход и доступную еду. | [S05](systems/S05.md) · [S06](systems/S06.md) · [M04](milestones/M04.md). [Alpha 18][a18] | Все сроки и влияние типа хранилища в 1.1 ещё не установлены. |
| <a id="b29"></a>B29. Развитие города | Выбор пути городского развития меняет испытание и награды культуры. | `AT-B29`. Сохраниться перед выбором двух собственных путей, завершить каждый отдельно и сравнить открытия и бонусы. | [S11](systems/S11.md) · [S13](systems/S13.md) · [M06](milestones/M06.md). [Alpha 19][a19] · [Замена кампании в Alpha 24+][a24] | Старые требования Alpha 19 сопоставить с заменившими их путями 1.1. Каждый различимый финал требует отдельного случая. |
| <a id="b30"></a>B30. Погода | Прогноз охватывает текущий и два следующих дня. Укрытие меняет воздействие суровой погоды на жителей. | `AT-B30`. Сравнить двух жителей под крышей и снаружи в заданной погоде. Прогноз и эффекты продолжаются после загрузки. | [S09](systems/S09.md) · [S05](systems/S05.md) · [M05](milestones/M05.md). [Alpha 24.4][a244] · [Стабильный выпуск][a24] | Для каждого типа 1.1 установить длительность, повреждения и защиту животных/растений. |
| <a id="b31"></a>B31. Мирный режим | В нестабильной Alpha 24.5 отключён урон песчаных и грозовых бурь в мирной сложности. | `AT-B31`. Запустить одинаковую собственную бурю в двух сложностях. В мирной партии проверить отсутствие соответствующего урона и сохранить остальные предусмотренные эффекты. | [S09](systems/S09.md) · [S13](systems/S13.md) · [M05](milestones/M05.md). [Alpha 24.5][a245] | Подтверждение точного исключения в стабильной 1.1 и граница между уроном и эффектами комфорта остаются открыты. |
| <a id="b32"></a>B32. Настроение | Пять состояний настроения меняют темп работы и выражаются в поведении и интерфейсе. | `AT-B32`. В одинаковом задании менять только мысли. Измерить полезную работу и сверить состояние в карточке и сводке города. | [S05](systems/S05.md) · [M04](milestones/M04.md). [Alpha 20 stable][a20] | Коэффициенты и пороги 1.1 ещё не подтверждены. |
| <a id="b33"></a>B33. Здоровье | При голодании здоровье не восстанавливается. | `AT-B33`. Ранить собственного жителя и сравнить восстановление до и после кормления. Загрузка на границе не добавляет лишнего лечения. | [S05](systems/S05.md) · [S12](systems/S12.md) · [M07](milestones/M07.md). [Исправление Alpha 20 до 701][r701] | Установить порог голода 1.1 и приоритет лечения относительно еды. |
| <a id="b34"></a>B34. Кооперативный труд | Игрок может разрешить жителям работать на другого игрока. | `AT-B34`. Два города. Выдать работу союзнику, отозвать разрешение во время рейса и проверить работника, груз и незавершённую работу. | [S04](systems/S04.md) · [S16](systems/S16.md) · [M09](milestones/M09.md). [Alpha 24.8][a248] · [Стабильный выпуск][a24] | Область делегирования и момент отзыва в 1.1 открыты. |
| <a id="b35"></a>B35. Добыча | Новая зона добычи может создаваться приостановленной. Выбор задаётся отдельно для каждого игрока. | `AT-B35`. Один игрок создаёт активную зону, другой приостановленную. Проверить отсутствие работ во второй до запуска и сохранение владельца. | [S02](systems/S02.md) · [S04](systems/S04.md) · [M03](milestones/M03.md). [Alpha 24+ stable][a24] | Настройки старта зоны и приостановка уже выданной работы требуют отдельных проверок. |
| <a id="b36"></a>B36. Модули правил | Набор модов связан с партией, подключение согласуется с модами хозяина. | `AT-B36`. Открыть две партии с разными собственными модулями. Проверить их восстановление и понятный отказ гостю с несовместимым набором. | [S19](systems/S19.md) · [S16](systems/S16.md) · [M10](milestones/M10.md). [Alpha 24+ stable][a24] | Исторические гарантии версий и обновления сохранения не установлены. Контрольные суммы заданы контрактом нового проекта. |
| <a id="b37"></a>B37. Строительство | Двери и окна можно снять и переместить. | `AT-B37`. Перенести собственную дверь в другой проём. Проверить наличие одного предмета, коллизию старого и нового прохода, сохранение во время переноски. | [S08](systems/S08.md) · [S03](systems/S03.md) · [M03](milestones/M03.md). [r876][r876] · [Включён в stable Beta][beta] | Ограничения для стройки в процессе и владельца другого города открыты. |
| <a id="b38"></a>B38. Ремесло | Потеря ингредиентов текущего рецепта перестала навсегда блокировать ремесленника. | `AT-B38`. Убрать последний вход собственного заказа. Ремесленник завершает допустимую работу, а исходный заказ возобновляется после снабжения. | [S04](systems/S04.md) · [S07](systems/S07.md) · [M04](milestones/M04.md). [1.1][v11] | Точный порядок отложения и возврата заказа 1.1 открыт. |
| <a id="b39"></a>B39. Выход из застревания | Для бездействующего жителя доступен перенос через карточку с суточным ограничением. Об угрозе голода в изоляции приходит уведомление. | `AT-B39`. Изолировать собственного жителя. Проверить уведомление, доступность действия по состоянию и сохранение срока повторного применения после загрузки. | [S18](systems/S18.md) · [S03](systems/S03.md) · [M03](milestones/M03.md). [1.1][v11] | Разрешённая точка назначения и взаимодействие с грузом 1.1 не описаны. |
| <a id="b40"></a>B40. Модули правил | Объявленная зависимость мода влияет на порядок загрузки. | `AT-B40`. Два собственных модуля с явной зависимостью. Проверить порядок, отсутствие зависимости и цикл, затем восстановление того же набора из сохранения. | [S19](systems/S19.md) · [M10](milestones/M10.md). [1.1][v11] | Поведение исторического загрузчика при цикле или отсутствии зависимости открыто. Явный отказ закреплён контрактом нового проекта. |
## Продолжение обхода источников
| Открытый участок | Точное продолжение и условие закрытия | Владелец и этап |
|---|---|---|
| Выпуски до Alpha 18 | Пройти датированные объявления ранних альф по порядку, начиная с первого доступного первичного журнала. У каждого правила записать введение, изменение или отмену. Витрина сама по себе не закрывает этот участок. | M00 и владельцы всех затронутых систем. |
| Промежутки Alpha 18–24+ | Проверить промежуточные исправления 18/19/20, Alpha 21–23, Alpha 24 и каждый 24.x. Последовательность названий из API даёт очередь, прочитанными считаются только строки таблицы выше. | M00. |
| Beta r862–r875 и RC–1.0 | Пройти перечисленные в stable Beta журналы r862, r864, r866, r868, r869, r870, r874, r875, затем RC1–RC5 и исправления 1.0. Сопоставить изменения с каждой строкой Bxx. | M00, [S07](systems/S07.md), [S13](systems/S13.md). |
| 1.0–1.1 | r898 и 1.05 просмотрены. Пройти полностью r898-hotfix, r905/hotfix, r909, r915, r923, r927. Объявление 1.1 и его финальное исправление просмотрены. Проверить наличие иных более поздних патчей базовой игры к отсечке. | M00. |
| Культуры и профессии | Для каждой культуры выписать дерево инструментов, уровни, входы, выходы, доступные мастерские и открываемые рецепты. B09/B25/B26 задают начало матрицы. | [S07](systems/S07.md) · [S11](systems/S11.md), M04–M06. |
| События и мирная сложность | Для обеих входных кампаний финального события, сотрудничества, городских выборов и двух редких встреч из 1.1 установить все различные ветви. Для каждого пути указать режим, условия запуска, отказ, исход и повторяемость. B14/B16/B29/B31 остаются открытыми по перечисленным вопросам. | [S13](systems/S13.md), M07. |
| Потребности, животные, торговля и UI | Разложить общие B07/B08/B17/B18 на разные триггеры и эффекты. Проверить недостачу еды, лечение, владение постелью, подарки и торговые покупки отдельно. Для UI финального патча воспроизвести сортировку кровати, наличие штатных шаблонов и закрытие загрузки клавишей Escape. | [S05](systems/S05.md) · [S10](systems/S10.md) · [S11](systems/S11.md) · [S18](systems/S18.md), M04–M10. |
Статус этого прохода — инвентарь с проверенными опорными выпусками и явной очередью. Полнота всех выпущенных поведений принимается после закрытия этой очереди и проверки исходов. Последний просмотренный выпуск — исправление 1.1 от 20 декабря 2018 года UTC. Для собственной реализации каждую строку закрывает результат `AT-Bxx` с коммитом, seed, модулями и наблюдаемым состоянием. [Приёмка M00](milestones/M00.md) · [Основной реестр](parity.md)
[store]: https://store.steampowered.com/app/253250/Stonehearth/
[a18]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1485907022#:~:text=Alpha%2018%20is%20Here%21
[a19]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1485907022#:~:text=Alpha%2019%20Has%20Arrived%21
[a20]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1485907022#:~:text=Alpha%2020%3A%20In%20Which%20We%20Put%20the%20Heart%20in%20Hearthlings
[r701]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1485907022#:~:text=Alpha%2020%20Updated%20to%20release%20701
[a244]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Alpha%2024.4%20Now%20on%20Steam%20Unstable
[a245]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Alpha%2024.5%20Now%20on%20Steam%20Unstable
[a248]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Alpha%2024.8%20Now%20on%20Steam%20Unstable
[a24]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Alpha%2024%2B%3A%20The%20Alpha%20to%20End%20All%20Alphas
[r876]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Beta%20r876%20Now%20on%20Steam%20Unstable
[beta]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Stonehearth%20Beta%20on%20Steam%20Stable
[v10]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Stonehearth%20is%20Now%201.0
[r898]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Release%20r898%20Now%20on%20Steam%20Unstable
[v105]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Stonehearth%201.05%20on%20Steam%20Stable
[v11]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Stonehearth%201.1%3A%20Once%20Moar%2C%20With%20Feeling
[v11fix]: https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=253250&count=100&maxlength=0&feeds=steam_community_announcements&enddate=1546300800#:~:text=Hotfix%20for%20Stonehearth%201.1%20now%20on%20Steam
+9
View File
@@ -6,6 +6,15 @@
Исходный прототип содержит добычу, доставку, строительство, потребности и кооператив на двоих. Существующий план P0–P5 и [архитектурные записи](../../architecture.md) описывают его текущие соглашения. В сборке закреплена VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, где проект уже использует Binary, Core и Testing. Для следующих задач действует [порядок использования VoidLibrary](../void-library.md).
## Материалы этапа
| Для работы | Где лежит результат |
|---|---|
| Проверить исходное описание, применимый выпуск и открытые вопросы для конкретной механики | [Базовая игра](../base-evidence.md) · [ACE](../ace-evidence.md) · [Исходные идентификаторы](../parity.md) |
| Опознать старую сборку, повторить проверки, подготовить контрольную карту и три сохранения на стройке | [Прототип и маршрут Q-HOME](../prototype-handoff.md) |
| Найти исходные файлы иконок, решение по правам и задание художнику на каждую группу материалов | [Реестр и художественное направление M03](../../art/demo-inventory.md) |
| Выбрать механизм для последовательного эталона и поточного прогона | [Проверка закреплённой VoidLibrary](../void-library.md) · [Контракт M01](M01.md) |
## Пакеты работ
1. Сохранить сведения о проверенной сборке прототипа, тестах, форматах сохранения и сетевого обмена. Показать, какие исторические решения меняет воксельный мир и почему старый исполняемый файл остаётся доступен для старых колоний.
+14
View File
@@ -15,6 +15,20 @@
## Первый переход с текущего клиента
### Потактный эталон прототипа
Для контрольного прогона мир создаётся с одним логическим исполнителем и `settlement::ExecutionMode::SerialReference`. Этот режим выполняет расчёт выбора работ, поиск пути и движение в вызывающем потоке. Сначала все свободные жители выбирают задание по одному состоянию, затем мир разбирает совпадающие заявки в порядке жителей. Обычный конструктор и загрузчик по умолчанию используют пул с 2–64 рабочими потоками. Конфигурацию исполнения выбирает клиент при создании или чтении мира. Один файл сохранения подходит для обоих вариантов. [Интерфейс мира](../../../engine/include/settlement/core/world.hpp)
Из корня репозитория после сборки Windows запустить `build\settlement_core_tests.exe --tag replay`. Журнал теста задаёт номера команд и попытки шага, поэтому может снять паузу даже тогда, когда номер такта остановился. Проверка сравнивает квитанции команд и полные байты сохранения по мере продвижения мира. Непрерывная партия задаёт ожидаемый результат для загруженной копии. [Исполняемые сценарии](../../../tests/replay_tests.cpp)
Этот срез открывает разработку M01. Фиксированный такт вне окна, неизменяемые снимки для клиентов, инкарнация после загрузки и идемпотентный результат повтора требуют отдельных изменений. Для замены пула остаются проверки переполнения, частичного запуска, времени жизни захваченных данных при отказе и стоимости работы на малом и нагруженном мире. [Проверка VoidLibrary](../void-library.md)
### Переход к авторитетному такту
Ядро выполняет такты по 50 мс в отдельном потоке. На каждой завершённой границе `SimulationRuntime` публикует независимый снимок и квитанции приказов. Пока идёт новый такт, читатели могут продолжать работу с прежней версией. Остановка игрового времени сохраняет возможность отдать приказ. Результат загрузки заменяет мир после повторной проверки номера запроса и инкарнации, в том числе при откате того же сохранения. [Интерфейс владельца](../../../engine/include/settlement/core/simulation_runtime.hpp) · [Тесты такта и отказов](../../../tests/runtime_tests.cpp)
Селектор `--tag runtime` под Wine выполнил десять проверок. Среди них — 20 тактов за секунду ручных часов, чтение предыдущего снимка при задержанном рабочем задании и возврат к управляемой партии после отказа публикации. Независимая проверка и общая сборка охватили 92 случая ядра и 4 LAN. Дальнейшая приёмка M01 проверяет действия игрока через окно, обмен со старым LAN-клиентом и постоянные ссылки при удалении объектов. [Техническая проверка](../../agent-workflow/tasks/M01-V7.md)
Выделить одну воспроизводимую партию прототипа и записать последовательность приказов. Сначала пропустить её через очередь авторитетного мира и дать окну читать последний завершённый снимок. Далее заменить один участок независимого расчёта, сверить результат каждого такта, затем подключить следующий. Так первое расхождение привязано к конкретной стадии. Для суммы запасов, состояния задания и номера команды выводить в отчёт также идентификатор первого отличающегося объекта.
Проверить для нынешнего `WorkerPool` исполнителя `Void::Async::ThreadExecutor` с `FuturePool`. На частичном отказе запуска уже созданные потоки должны штатно завершиться. При заполненной очереди логическая работа остаётся в такте до исполнения. При одновременных заявках на предмет ожидаемый победитель определяется правилами арбитража. Доступность API и управляемое воспроизведение отказов записать до удаления прежнего пути. Эталонный последовательный исполнитель — новый тестовый режим. Исторический тест, отклоняющий конфигурацию с одним рабочим потоком, остаётся свидетельством поведения прототипа.
+2
View File
@@ -17,6 +17,8 @@
## Сценарий «Дом на склоне»
В [постановке Q-HOME](../prototype-handoff.md) закреплены seed, припасы, положение дома относительно стыка чанков и проверка владельца последней детали. [Производственная ведомость](../../art/demo-inventory.md) задаёт модели, материалы, движения, звуки и обозначения для этого маршрута.
На контрольной карте `Q-HOME` отметить источник древесины, добываемый камень, временный склад, место первого этажа и площадку второго. Зафиксировать seed, объём начальных припасов и состав чертежа. В смете должна быть хотя бы одна деталь, для которой обязательны добыча, доставка в мастерскую и последующая доставка на стройку. По пути от старта до сна в собственном доме игрок самостоятельно назначает участок и исправляет хотя бы одну видимую причину остановки.
Снять три контрольных сохранения. В первом строитель уже взял последнюю нужную деталь со склада. Во втором он несёт её к верхней площадке. В третьем работа по установке уже началась. Для каждого продолжения сверить число таких деталей, их владельца, стадию чертежа и свободный проход к кровати. Повторить один рейс с отменой и последующей выдачей работы. Первую публичную сборку запускать на Windows из поставляемого пакета. В отчёте демо разделить время реализации движка, правил, интерфейса и изготовления собственных материалов.
+53 -66
View File
@@ -2,67 +2,69 @@
Реестр нужен, чтобы утверждение о паритете можно было проверить в работающей игре. Базовая версия и изменения ACE учитываются раздельно, даже если они описывают один промысел. Модуль правил определяет, какая механика активна в конкретной партии. Настройки мира фиксируются при создании.
Ниже — **начальный инвентарь из 24 наблюдений базовой игры и 26 наблюдений ACE** по публичным материалам до 2 декабря 2026 года. Метка строки задаёт постоянный идентификатор требования и его приёмочного сценария, например `AT-B03` для `B03`. Во всех строках исходное состояние разработки — **запланировано**. Сценарий описывает собственную будущую проверку. Для принятой строки добавить ссылку на результат с коммитом, seed, набором модулей и наблюдаемым исходом.
Исходные 24 наблюдения базовой игры и 26 наблюдений ACE сохраняют свои номера. Для каждого пункта последняя колонка ведёт к проверенному выпуску или конкретному вопросу. Продолжение реестра, просмотренные выпуски и ещё открытые диапазоны приведены в [сверке базовой игры](base-evidence.md) и [сверке ACE](ace-evidence.md). Дата отсечения — 2 декабря 2026 года. Метка строки задаёт постоянный идентификатор требования и его приёмочного сценария, например `AT-B03` для `B03`. Во всех строках исходное состояние разработки — **запланировано**. Сценарий описывает собственную будущую проверку. Для принятой строки добавить ссылку на результат с коммитом, seed, набором модулей и наблюдаемым исходом.
Всего в первом проходе 80 идентификаторов. Новые строки — [B25–B40](base-evidence.md#b25) и [A27–A40](ace-evidence.md#a27). Все 80 требуют приёмки на собственной игре.
## Базовая игра
| ID | Модуль правил | Наблюдаемое поведение | Собственный сценарий и ожидаемый результат | Система и этап | Свидетельство |
|---|---|---|---|---|---|
| <a id="b01"></a>B01 | Мир | Процедурный рельеф | Заданный seed повторяет расположение доступных ресурсов при новом старте. | [S02](systems/S02.md) · [M02](milestones/M02.md) | [Описание игры][base] |
| <a id="b02"></a>B02 | Строительство | Комнаты объединяются в сложный план | Соединить два крыла своего дома и проверить, что общая часть пола строится один раз. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Строительство и повторное заселение][build] |
| <a id="b03"></a>B03 | Строительство | Вертикальная сборка дома | Построить верхний этаж с кроватью и пройти к ней по лестнице. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Строительство и повторное заселение][build] |
| <a id="b04"></a>B04 | Строительство | Редактирование отдельных вокселей | Изменить выступ настила и пересчитать смету и занятое пространство. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Строительство и повторное заселение][build] |
| <a id="b05"></a>B05 | Строительство | Доступность места работы | Убрать доступ к секции крыши. Игрок видит причину и продолжает ту же стройку после установки лестницы. | [S03](systems/S03.md) · [M03](milestones/M03.md) | [Строительство и повторное заселение][build] |
| <a id="b06"></a>B06 | Строительство | Временные леса | Пройти строительство высокой секции, затем проверить освобождение клеток временного доступа. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Строительство и повторное заселение][build] |
| <a id="b07"></a>B07 | Общество | Изменение настроения от условий жизни | Обеспечить едой и жильём две группы с разным исходным состоянием. Сводка объясняет изменение настроения. | [S05](systems/S05.md) · [M04](milestones/M04.md) | [Заметки разработчиков о настроении][mood] |
| <a id="b08"></a>B08 | Экономика | Пропитание и рост поселения | Перейти от лагерных запасов к своему снабжению и разместить нового жителя в рабочем городе. | [S11](systems/S11.md) · [M04](milestones/M04.md) | [Описание игры][base] |
| <a id="b09"></a>B09 | Профессии | Различия стартовых культур | Проверить оригинальную культуру, начинающую с охоты и камня, и культуру с другим путём снабжения. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b10"></a>B10 | Мир | Достопримечательности при генерации | Найти собственную руину в контрольном сиде. После загрузки сохраняются её положение и изменения. | [S02](systems/S02.md) · [M06](milestones/M06.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b11"></a>B11 | Климат | Выбор начального сезона | Запустить один биом в двух сезонах и наблюдать разные стартовые погодные условия. | [S09](systems/S09.md) · [M05](milestones/M05.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b12"></a>B12 | Земледелие | Сезон влияет на развитие культуры | Сравнить два урожая одинаковой посадки в предпочитаемый и другой сезон. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b13"></a>B13 | Общество | Перенос группы в новую колонию | После развития поселения выбрать отправляющихся жителей и груз. Проверить состав прибывшей группы в следующей партии. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Строительство и повторное заселение][build] |
| <a id="b14"></a>B14 | Кампании | Сотрудничество открывает новую ветвь | Договориться с собственной соседней общиной поставками. После выполнения открывается профессия. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b15"></a>B15 | Профессии | Специалист изменяет землю | После открытия специальности создать доступный участок рельефа и проверить новые пути к нему. | [S07](systems/S07.md) · [M07](milestones/M07.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b16"></a>B16 | Кампании | Необязательное финальное столкновение | Две допустимые цепочки дают доступ к собственному финалу. Отложить его, затем пройти с участием работников и отряда. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b17"></a>B17 | Оборона | Охрана города | Организовать защиту поселения. Раненый участник восстанавливается и возвращается к службе. | [S12](systems/S12.md) · [M07](milestones/M07.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b18"></a>B18 | Путешественники | Посещение и оценка поселения | Посетитель оценивает обстановку и место ночлега. Вариант гостевого дома влияет на результат визита. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Stonehearth 1.1][final] |
| <a id="b19"></a>B19 | Кооператив | Отдельные поселения у общего хозяина | Два игрока основывают соседние города и видят разрешённые объекты одного мира. | [S16](systems/S16.md) · [M09](milestones/M09.md) | [Многопользовательская игра][coop] |
| <a id="b20"></a>B20 | Кооператив | Обмен между городами | Обменять товар и деньги, переподключить покупателя и проверить обе стороны операции. | [S11](systems/S11.md) · [M09](milestones/M09.md) | [Многопользовательская игра][coop] |
| <a id="b21"></a>B21 | Кооператив | Совместная помощь при нападении | Гость поддерживает оборону союзного города с разрешения владельца. | [S12](systems/S12.md) · [M09](milestones/M09.md) | [Многопользовательская игра][coop] |
| <a id="b22"></a>B22 | Инструменты | Сохранение и повторное применение чертежа | Сохранить собственный шаблон, разместить его в другом месте и проверить проходимость входов. | [S08](systems/S08.md) · [M10](milestones/M10.md) | [Многопользовательская игра][coop] |
| <a id="b23"></a>B23 | Моды | Настраиваемые предметы и события | Независимо созданный пакет добавляет предмет и встречу через новый API. Набор остаётся узнаваемым после загрузки. | [S19](systems/S19.md) · [M10](milestones/M10.md) | [Описание игры][base] |
| <a id="b24"></a>B24 | Профессии | Ремесленник создаёт помощника для повторяемой работы | Создать собственного помощника и передать ему повторяемое поручение. Проверить, что житель и помощник не выдают два результата одного задания. | [S04](systems/S04.md) · [M07](milestones/M07.md) | [Июльский выпуск перед 1.0][beta] |
| <a id="b01"></a>B01 | Мир | Процедурный рельеф | Заданный seed повторяет расположение доступных ресурсов при новом старте. | [S02](systems/S02.md) · [M02](milestones/M02.md) | [Сверка B01](base-evidence.md#b01) |
| <a id="b02"></a>B02 | Строительство | Комнаты объединяются в сложный план | Соединить два крыла своего дома и проверить, что общая часть пола строится один раз. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Сверка B02](base-evidence.md#b02) |
| <a id="b03"></a>B03 | Строительство | Вертикальная сборка дома | Построить верхний этаж с кроватью и пройти к ней по лестнице. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Сверка B03](base-evidence.md#b03) |
| <a id="b04"></a>B04 | Строительство | Редактирование отдельных вокселей | Изменить выступ настила и пересчитать смету и занятое пространство. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Сверка B04](base-evidence.md#b04) |
| <a id="b05"></a>B05 | Строительство | Доступность места работы | Убрать доступ к секции крыши. Игрок видит причину и продолжает ту же стройку после установки лестницы. | [S03](systems/S03.md) · [M03](milestones/M03.md) | [Сверка B05](base-evidence.md#b05) |
| <a id="b06"></a>B06 | Строительство | Временные леса | Пройти строительство высокой секции, затем проверить освобождение клеток временного доступа. | [S08](systems/S08.md) · [M03](milestones/M03.md) | [Сверка B06](base-evidence.md#b06) |
| <a id="b07"></a>B07 | Общество | Изменение настроения от условий жизни | Обеспечить едой и жильём две группы с разным исходным состоянием. Сводка объясняет изменение настроения. | [S05](systems/S05.md) · [M04](milestones/M04.md) | [Сверка B07](base-evidence.md#b07) |
| <a id="b08"></a>B08 | Экономика | Пропитание и рост поселения | Перейти от лагерных запасов к своему снабжению и разместить нового жителя в рабочем городе. | [S11](systems/S11.md) · [M04](milestones/M04.md) | [Сверка B08](base-evidence.md#b08) |
| <a id="b09"></a>B09 | Профессии | Различия стартовых культур | Проверить оригинальную культуру, начинающую с охоты и камня, и культуру с другим путём снабжения. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка B09](base-evidence.md#b09) |
| <a id="b10"></a>B10 | Мир | Достопримечательности при генерации | Найти собственную руину в контрольном сиде. После загрузки сохраняются её положение и изменения. | [S02](systems/S02.md) · [M06](milestones/M06.md) | [Сверка B10](base-evidence.md#b10) |
| <a id="b11"></a>B11 | Климат | Выбор начального сезона | Запустить один биом в двух сезонах и наблюдать разные стартовые погодные условия. | [S09](systems/S09.md) · [M05](milestones/M05.md) | [Сверка B11](base-evidence.md#b11) |
| <a id="b12"></a>B12 | Земледелие | Сезон влияет на развитие культуры | Сравнить два урожая одинаковой посадки в предпочитаемый и другой сезон. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка B12](base-evidence.md#b12) |
| <a id="b13"></a>B13 | Общество | Перенос группы в новую колонию | После развития поселения выбрать отправляющихся жителей и груз. Проверить состав прибывшей группы в следующей партии. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка B13](base-evidence.md#b13) |
| <a id="b14"></a>B14 | Кампании | Сотрудничество открывает новую ветвь | Договориться с собственной соседней общиной поставками. После выполнения открывается профессия. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Сверка B14](base-evidence.md#b14) |
| <a id="b15"></a>B15 | Профессии | Специалист изменяет землю | После открытия специальности создать доступный участок рельефа и проверить новые пути к нему. | [S07](systems/S07.md) · [M07](milestones/M07.md) | [Сверка B15](base-evidence.md#b15) |
| <a id="b16"></a>B16 | Кампании | Необязательное финальное столкновение | Две допустимые цепочки дают доступ к собственному финалу. Отложить его, затем пройти с участием работников и отряда. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Сверка B16](base-evidence.md#b16) |
| <a id="b17"></a>B17 | Оборона | Спасение раненого | Доставить упавшего жителя к постели и продолжить уход после загрузки. Условия его возвращения к службе остаются открытыми. | [S12](systems/S12.md) · [M07](milestones/M07.md) | [Сверка B17](base-evidence.md#b17) |
| <a id="b18"></a>B18 | Путешественники | Посещение и оценка поселения | Предоставить гостевую кровать и сравнить визиты в двух условиях обстановки. Проверить оценку и однократное получение подарка. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка B18](base-evidence.md#b18) |
| <a id="b19"></a>B19 | Кооператив | Отдельные поселения у общего хозяина | Два игрока основывают соседние города и видят разрешённые объекты одного мира. | [S16](systems/S16.md) · [M09](milestones/M09.md) | [Сверка B19](base-evidence.md#b19) |
| <a id="b20"></a>B20 | Кооператив | Обмен между городами | Обменять товар и деньги, переподключить покупателя и проверить обе стороны операции. | [S11](systems/S11.md) · [M09](milestones/M09.md) | [Сверка B20](base-evidence.md#b20) |
| <a id="b21"></a>B21 | Кооператив | Совместная помощь при нападении | Гость поддерживает оборону союзного города с разрешения владельца. | [S12](systems/S12.md) · [M09](milestones/M09.md) | [Сверка B21](base-evidence.md#b21) |
| <a id="b22"></a>B22 | Инструменты | Сохранение и повторное применение чертежа | Сохранить собственный шаблон, разместить его в другом месте и проверить проходимость входов. | [S08](systems/S08.md) · [M10](milestones/M10.md) | [Сверка B22](base-evidence.md#b22) |
| <a id="b23"></a>B23 | Моды | Настраиваемые предметы и события | Независимо созданный пакет добавляет предмет и встречу через новый API. Набор остаётся узнаваемым после загрузки. | [S19](systems/S19.md) · [M10](milestones/M10.md) | [Сверка B23](base-evidence.md#b23) |
| <a id="b24"></a>B24 | Профессии | Ремесленник создаёт помощника для повторяемой работы | Создать собственного помощника и передать ему повторяемое поручение. Проверить, что житель и помощник не выдают два результата одного задания. | [S04](systems/S04.md) · [M07](milestones/M07.md) | [Сверка B24](base-evidence.md#b24) |
## Дополнения и изменения ACE
| ID | Модуль правил | Наблюдаемое поведение | Собственный сценарий и ожидаемый результат | Система и этап | Свидетельство |
|---|---|---|---|---|---|
| <a id="a01"></a>A01 | Земледелие | Ирригация меняет урожай | Разделить поле канавой, подать воду только на одну сторону и сравнить рост. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сводка ACE от авторов][ace] |
| <a id="a02"></a>A02 | Вода | Регулируемая подача через затвор | Закрыть затвор, дождаться перераспределения воды, сохранить и вновь открыть. | [S09](systems/S09.md) · [M05](milestones/M05.md) | [Сводка ACE от авторов][ace] |
| <a id="a03"></a>A03 | Вода | Подъём воды насосом | Заполнить верхнюю ёмкость из нижней. Учесть объём на обеих сторонах границы чанка. | [S09](systems/S09.md) · [M05](milestones/M05.md) | [Сводка ACE от авторов][ace] |
| <a id="a04"></a>A04 | Добыча | Ресурс зависит от места добычи | Добыть разные материалы на берегу и под водой. Проверить результаты при одинаковой разметке. | [S02](systems/S02.md) · [M05](milestones/M05.md) | [Сводка ACE от авторов][ace] |
| <a id="a05"></a>A05 | Биомы | Особая флора и ресурсы нагорья | Освоить оригинальный высокогорный биом, выстроив снабжение из его локальных ресурсов. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сводка ACE от авторов][ace] |
| <a id="a06"></a>A06 | Ремесло | Градации топлива | Задать топку с требованием к качеству топлива. Проверить выбор подходящей партии и расход. | [S07](systems/S07.md) · [M04](milestones/M04.md) | [Сводка ACE от авторов][ace] |
| <a id="a07"></a>A07 | Ремесло | Многостадийное производство металла | Довести заказ от добытого материала через промежуточные стадии до готового изделия, сохранив работу на середине. | [S07](systems/S07.md) · [M04](milestones/M04.md) | [Сводка ACE от авторов][ace] |
| <a id="a08"></a>A08 | Оборона | Предпочтения экипировки отряда | Изменить разрешённый комплект, дождаться переоснащения и проверить возврат прежних вещей. | [S12](systems/S12.md) · [M07](milestones/M07.md) | [Сводка ACE от авторов][ace] |
| <a id="a09"></a>A09 | Оборона | Маршрут патруля | Назначить точки обхода, прервать тревогой и проверить возобновление после отбоя. | [S12](systems/S12.md) · [M07](milestones/M07.md) | [Сводка ACE от авторов][ace] |
| <a id="a10"></a>A10 | Жители | Питьё как потребность комфорта | Предложить приемлемый и непереносимый напитки. Отсутствие напитка влияет на самочувствие без смерти от жажды. | [S05](systems/S05.md) · [M05](milestones/M05.md) | [Уточнения правил напитков и топлива][drinkfix] |
| <a id="a11"></a>A11 | Ремесло | Приготовление напитков | Довести производство собственного напитка от сырья до потребления, сохранить загрузку станции. | [S07](systems/S07.md) · [M05](milestones/M05.md) | [Выпуск ACE о напитках][drink] |
| <a id="a12"></a>A12 | Качество | Рацион влияет на продукцию стада | Сравнить обычный и специализированный корм в одинаковом стаде по результату сбора продукции. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Выпуск ACE о качестве][quality] |
| <a id="a13"></a>A13 | Качество | Качество изделия влияет на ценность | Изготовить два экземпляра разных качеств, сравнить цену и сохранить различие при переноске. | [S06](systems/S06.md) · [M06](milestones/M06.md) | [Уточнения правил напитков и топлива][drinkfix] |
| <a id="a14"></a>A14 | Питомцы | Память об умершем питомце | Проверить собственный памятный объект после утраты питомца и отсутствие второй выдачи при загрузке. | [S10](systems/S10.md) · [M07](milestones/M07.md) | [Обновление ухода и питомцев][pet] |
| <a id="a15"></a>A15 | Торговля | Торговец занимает место на рынке | Подготовить подходящее торговое место. Посетитель занимает его, обслуживает покупателя и освобождает при уходе. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Выпуск ACE о торговле][market] |
| <a id="a16"></a>A16 | Торговля | Уровни города и рынка ограничивают торговцев | Повысить только уровень места, затем города. Проверить доступные категории торговцев до и после. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Выпуск ACE о торговле][market] |
| <a id="a17"></a>A17 | Торговля | Запрашиваемый товар получает особую цену | Продать одинаковые изделия двум разным торговцам и объяснить разницу спросом. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Выпуск ACE о торговле][market] |
| <a id="a18"></a>A18 | Торговля | Предпочтения категорий посещения | Ограничить одну категорию, повторить одинаковую последовательность рыночных дней и проверить состав посетителей. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Выпуск ACE о торговле][market] |
| <a id="a19"></a>A19 | Торговля | История сделок влияет на будущие посещения | При сопоставимом богатстве сравнить город с торговой историей и без неё. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Обновления до 0.9.6.22 включительно][latest] |
| <a id="a20"></a>A20 | Пасека | Результат опыления зависит от окружения | Сравнить ульи у подходящих и неподходящих растений, сохранить на границе цикла. Урожай учитывается однократно. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Обновления до 0.9.6.22 включительно][latest] |
| <a id="a21"></a>A21 | Погода | Затопление и заморозки влияют на посевы | Сопоставить защищённую гряду, затопленную и морозостойкую посадки. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Обновления до 0.9.6.22 включительно][latest] |
| <a id="a22"></a>A22 | Животные | Сезонное появление и ловля дичи | Повторить сезонное наблюдение по заданным сидам. Проверить добычу и заменяемый ингредиент в рецепте. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Обновления до 0.9.6.22 включительно][latest] |
| <a id="a23"></a>A23 | События | Мирный путь сезонной кампании | Пройти собственное сезонное событие без рейдов, сохранить перед наградой и восстановить правильный финал. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Обновления до 0.9.6.22 включительно][latest] |
| <a id="a24"></a>A24 | События | Сезонное окно и продолжение события | Начать собственный зимний сюжет в окне запуска. Зафиксировать открытые рецепты и правила продолжения в сохранении. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Зимняя кампания][winter] |
| <a id="a25"></a>A25 | Логистика | Смена пастбища переселяет животных | Удалить одно пастбище при разной свободной вместимости другого. Посчитать переведённых и оставшихся животных. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Обновления до 0.9.6.22 включительно][latest] |
| <a id="a26"></a>A26 | Потребности | Раненый выбирает между лечением и едой | Довести жителя до одновременно критического голода и потребности в отдыхе. Проверить выбранное действие и лечение после еды. | [S05](systems/S05.md) · [M07](milestones/M07.md) | [Обновления до 0.9.6.22 включительно][latest] |
| <a id="a01"></a>A01 | Земледелие | Ирригация меняет урожай | Разделить поле канавой, подать воду только на одну сторону и сравнить рост. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка A01](ace-evidence.md#a01) |
| <a id="a02"></a>A02 | Вода | Регулируемая подача через затвор | Закрыть затвор, дождаться перераспределения воды, сохранить и вновь открыть. | [S09](systems/S09.md) · [M05](milestones/M05.md) | [Сверка A02](ace-evidence.md#a02) |
| <a id="a03"></a>A03 | Вода | Подъём воды насосом | Заполнить верхнюю ёмкость из нижней. Учесть объём на обеих сторонах границы чанка. | [S09](systems/S09.md) · [M05](milestones/M05.md) | [Сверка A03](ace-evidence.md#a03) |
| <a id="a04"></a>A04 | Добыча | Ресурс зависит от места добычи | Добыть разные материалы на берегу и под водой. Проверить результаты при одинаковой разметке. | [S02](systems/S02.md) · [M05](milestones/M05.md) | [Сверка A04](ace-evidence.md#a04) |
| <a id="a05"></a>A05 | Биомы | Особая флора и ресурсы нагорья | Освоить оригинальный высокогорный биом, выстроив снабжение из его локальных ресурсов. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка A05](ace-evidence.md#a05) |
| <a id="a06"></a>A06 | Ремесло | Градации топлива | Задать топку с требованием к качеству топлива. Проверить выбор подходящей партии и расход. | [S07](systems/S07.md) · [M04](milestones/M04.md) | [Сверка A06](ace-evidence.md#a06) |
| <a id="a07"></a>A07 | Ремесло | Многостадийное производство металла | Довести заказ от добытого материала через промежуточные стадии до готового изделия, сохранив работу на середине. | [S07](systems/S07.md) · [M04](milestones/M04.md) | [Сверка A07](ace-evidence.md#a07) |
| <a id="a08"></a>A08 | Оборона | Предпочтения экипировки отряда | Изменить разрешённый комплект, дождаться переоснащения и проверить возврат прежних вещей. | [S12](systems/S12.md) · [M07](milestones/M07.md) | [Сверка A08](ace-evidence.md#a08) |
| <a id="a09"></a>A09 | Оборона | Маршрут патруля | Назначить точки обхода, прервать тревогой и проверить возобновление после отбоя. | [S12](systems/S12.md) · [M07](milestones/M07.md) | [Сверка A09](ace-evidence.md#a09) |
| <a id="a10"></a>A10 | Жители | Питьё как потребность комфорта | Предложить приемлемый и непереносимый напитки. Отсутствие напитка влияет на самочувствие без смерти от жажды. | [S05](systems/S05.md) · [M05](milestones/M05.md) | [Сверка A10](ace-evidence.md#a10) |
| <a id="a11"></a>A11 | Ремесло | Приготовление напитков | Довести производство собственного напитка от сырья до потребления, сохранить загрузку станции. | [S07](systems/S07.md) · [M05](milestones/M05.md) | [Сверка A11](ace-evidence.md#a11) |
| <a id="a12"></a>A12 | Качество | Рацион влияет на продукцию стада | Сравнить обычный и специализированный корм в одинаковом стаде по результату сбора продукции. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка A12](ace-evidence.md#a12) |
| <a id="a13"></a>A13 | Качество | Качество изделия влияет на ценность | Изготовить два экземпляра разных качеств, сравнить цену и сохранить различие при переноске. | [S06](systems/S06.md) · [M06](milestones/M06.md) | [Сверка A13](ace-evidence.md#a13) |
| <a id="a14"></a>A14 | Питомцы | Память об умершем питомце | Проверить собственный памятный объект после утраты питомца и отсутствие второй выдачи при загрузке. | [S10](systems/S10.md) · [M07](milestones/M07.md) | [Сверка A14](ace-evidence.md#a14) |
| <a id="a15"></a>A15 | Торговля | Торговец занимает место на рынке | Подготовить подходящее торговое место. Посетитель занимает его, обслуживает покупателя и освобождает при уходе. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка A15](ace-evidence.md#a15) |
| <a id="a16"></a>A16 | Торговля | Уровни города и рынка ограничивают торговцев | Повысить только уровень места, затем города. Проверить доступные категории торговцев до и после. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка A16](ace-evidence.md#a16) |
| <a id="a17"></a>A17 | Торговля | Запрашиваемый товар получает особую цену | Продать одинаковые изделия двум разным торговцам и объяснить разницу спросом. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка A17](ace-evidence.md#a17) |
| <a id="a18"></a>A18 | Торговля | Предпочтения категорий посещения | Ограничить одну категорию, повторить одинаковую последовательность рыночных дней и проверить состав посетителей. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка A18](ace-evidence.md#a18) |
| <a id="a19"></a>A19 | Торговля | История сделок влияет на будущие посещения | При сопоставимом богатстве сравнить город с торговой историей и без неё. | [S11](systems/S11.md) · [M06](milestones/M06.md) | [Сверка A19](ace-evidence.md#a19) |
| <a id="a20"></a>A20 | Пасека | Результат опыления зависит от окружения | Сравнить ульи у подходящих и неподходящих растений, сохранить на границе цикла. Урожай учитывается однократно. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка A20](ace-evidence.md#a20) |
| <a id="a21"></a>A21 | Погода | Затопление и заморозки влияют на посевы | Сопоставить защищённую гряду, затопленную и морозостойкую посадки. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка A21](ace-evidence.md#a21) |
| <a id="a22"></a>A22 | Животные | Сезонное появление и ловля дичи | Повторить сезонное наблюдение по заданным сидам. Проверить добычу и заменяемый ингредиент в рецепте. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка A22](ace-evidence.md#a22) |
| <a id="a23"></a>A23 | События | Мирный путь сезонной кампании | На мирной сложности выбрать путь без боёв, сохранить перед наградой и проверить исход при первом и повторном прохождении. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Сверка A23](ace-evidence.md#a23) |
| <a id="a24"></a>A24 | События | Сезонное окно и продолжение события | Довести город до второго уровня и запустить зимнюю историю в её календарном окне. Загрузить уже начатую историю после закрытия окна и проверить продолжение. | [S13](systems/S13.md) · [M07](milestones/M07.md) | [Сверка A24](ace-evidence.md#a24) |
| <a id="a25"></a>A25 | Логистика | Смена пастбища переселяет животных | Удалить одно пастбище при разной свободной вместимости другого. Посчитать переведённых и оставшихся животных. | [S10](systems/S10.md) · [M05](milestones/M05.md) | [Сверка A25](ace-evidence.md#a25) |
| <a id="a26"></a>A26 | Потребности | Раненый выбирает между лечением и едой | Довести жителя, который восстанавливается после ранения, до критического голода. Проверить выбранное действие и лечение после еды. | [S05](systems/S05.md) · [M07](milestones/M07.md) | [Сверка A26](ace-evidence.md#a26) |
## Как довести инвентарь до полного покрытия
@@ -80,18 +82,3 @@
Собственный фронтир, связанные регионы, управление общим поселением и целевая нагрузка 500 жителей определены решениями этого проекта. Их принимают [M08](milestones/M08.md), [M09](milestones/M09.md) и [S21](systems/S21.md). Для заимствования кода или материалов реестр не используется. Происхождение собственной реализации и каждого поставляемого материала ведут по [M00](milestones/M00.md) и [S20](systems/S20.md).
[Мастер-план](../../PLAN.md)
[base]: https://store.steampowered.com/app/253250/
[build]: https://store.steampowered.com/news/posts/?appids=253250&enddate=1526001051
[beta]: https://store.steampowered.com/news/posts/?appids=253250&enddate=1532462538&feed=steam_community_announcements
[mood]: https://store.steampowered.com/news/posts/?appids=253250&enddate=1484876676
[coop]: https://store.steampowered.com/news/posts/?appids=253250&enddate=1525802303
[final]: https://store.steampowered.com/oldnews/?appgroupname=Stonehearth&appids=253250&enddate=1735718400&feed=steam_community_announcements
[ace]: https://steamcommunity.com/workshop/filedetails/?id=1577375188
[quality]: https://discourse.stonehearth.net/t/ace-pre-release-0-9-3-3-the-quality-update/39695/1
[drink]: https://discourse.stonehearth.net/t/ace-pre-release-0-9-4-7-the-drinking-update/40239
[drinkfix]: https://discourse.stonehearth.net/t/ace-pre-release-0-9-4-7-the-drinking-update/40239/154
[market]: https://discourse.stonehearth.net/t/ace-pre-release-0-9-6-22/43079
[latest]: https://discourse.stonehearth.net/t/ace-pre-release-0-9-6-22/43079?page=12
[winter]: https://discourse.stonehearth.net/t/ace-pre-release-0-9-6-21-firstbloom/43079/240
[pet]: https://discourse.stonehearth.net/t/ace-pre-release-0-9-6-21-firstbloom/43079/123
+35
View File
@@ -0,0 +1,35 @@
# От сохранения прототипа до «Дома на склоне»
## Как открыть старую колонию
Последняя исходная сборка прототипа — `083b84e11ad113259400a0eeb6a4047cf2df8110`. У начала работ над M00 (`0deacb3`) те же игровые исходники, CMake и тесты. Для старого файла `.settlement` запустить `settlement_viewer.exe` этой сборки и в главном меню выбрать «Открыть файл…». Для игры вдвоём оба участника используют LAN 11. Архив P0–P5 и исходный коммит позволяют воспроизвести исполняемые файлы. У будущего воксельного мира своё поколение формата и протокола. [Инструкция для Windows](../../README.md) · [Меню и файлы](../viewer.md) · [История P0–P5](history/prototype-p0-p5.md)
| Что проверено 2 декабря 2026 года | Как повторить и сопоставить результат |
|---|---|
| Windows x64 Release, CMake 4.5.0, GCC 16.2.0 UCRT, закреплённая VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. В кросс-сборке под Wine 11 прошли 28 тестов ядра и 4 LAN, включая обмен с гостем через loopback. | В настроенной сборке выполнить `cmake --build <build-dir> --parallel` и `ctest --test-dir <build-dir> -V --output-on-failure`. Сверить число **отдельных тестов** в выводе обеих CTest-сюит. Нативный прогон Windows на двух ПК остаётся отдельной проверкой. [Команды и среда](../agent-workflow/STATE.md) |
| Запись использует версию 13. Чтение поддерживает 1–13. Версия сетевого протокола — 11. | В исходном коммите сверить `save_version` и диапазон `read_save`, а также `protocol_version`. Сохранение старой колонии открывается старым клиентом независимо от разработки нового ядра. [Кодек](../../engine/src/world_save.cpp) · [Сообщения LAN](../../app/lan_wire.hpp) |
| Локальный архив прототипа `build/settlement-windows-x64.zip` содержит viewer, симулятор, benchmark, обе тестовые программы и три DLL. SHA-256 проверенного архива — `36bd1ca012247a1b9c563dabf866d077b3125a47b079c2d0cf2cef0cffa46f16`. | Хеш опознаёт конкретный архив. Исходная ревизия доступна в Git. Для повторной сборки в отдельном каталоге извлечь этот коммит и выполнить его `build.ps1`. При подготовке публичного демо проверить права на ресурсы внутри самого viewer. [Материалы демо](../art/demo-inventory.md) |
### Какие нагрузки сравнимы
В экономической сцене Windows Release на Ryzen 9 9950X3D мир 80×80 с seed 2026 обслуживает фермеров, лесорубов, шахтёров и строителей. После 32 тактов прогрева измеряли 240 тактов ядра, медиана трёх прогонов. При 500 жителях p95 составил 268,7 мкс на шести потоках и 279,7 мкс на двенадцати. Отрисовка, сохранение и сеть в этот интервал не входят. [Состав экономики и исходные измерения](../../benchmarks/colony-performance.md)
В синтетической сцене seed 42, поле 512×512, 8% закрытых клеток, 10 000 общих работ и 2 500 жителей. 250 тактов включают первоначальное назначение и поиск пути. На восьми потоках завершено 2 520 работ, p95 — 5,49 мс. В сравнении на двенадцати потоках p95 — 4,25 мс. Модель процессора в этой записи не указана. [Параметры и команды](../../benchmarks/scale-50-vs-2500.md) · [Сравнение потоков](../../benchmarks/parallel-workers.md)
Для нового мира `Q-TOWN500` задаёт 500 жителей в одном регионе, `Q-REGIONS500` распределяет тех же 500 по четырём, `Q-STRESS2500` проверяет пределы и сохранность. Перед каждым сравнением фиксируются версия игры и правил, исходный мир, команды, камера и контрольная сумма. Приёмка на Windows x64 включает кадры 1080p, полную симуляцию и пики во время сохранения. Состав мира, эталонный ПК, длительности и бюджеты заданы в [протоколе S21](systems/S21.md).
## Маршрут Q-HOME
Это контрольная постановка для M02–M03. Seed — `20261202`, один регион, трое жителей, девять порций еды, пустой склад материалов и ноль готовых строительных деталей. Версия генератора и определения правил будут приложены к первому воспроизводимому миру. Для маршрута используются целые координаты `(x,y,z)`, высота — `z`. Контрольные точки фиксируют требования к площадке, включая стык чанков 32³. [Координаты мира](systems/S02.md) · [Сценарий M03](milestones/M03.md)
1. Начать лагерь на ровной полосе около `(23,16,8)`. Разметить склад у `(25,16,8)`, рабочее место у `(26,13,8)` и выемку в склоне под дом. Пометить дерево к западу от лагеря и добываемый камень в выемке. Участки обязаны обеспечивать смету дома и мебели. Число добытых и израсходованных единиц снять из утверждённых игровых рецептов при создании фикстуры.
2. Разместить дом с основанием 6×5 по `x=29..34, y=15..19`, входом с западной стороны, нижним настилом на `z=8` и верхней площадкой на `z=12`. В чертеже есть опоры, дверь, внутренняя лестница с проёмом, верхний настил и три кровати, одна из них наверху. Убрать доступ к верхней площадке, дождаться объяснения причины в интерфейсе, восстановить лестницу и продолжить тот же заказ.
3. Для последней секции верхнего настила нужна одна специально учтённая пилёная деталь. Получить её из добытого дерева в мастерской и положить на склад. Сделать отдельные сохранения после выдачи детали со склада, на подходе к месту установки наверху и во время самой установки. Для каждого записать такт, ID заказа и строителя, текущего владельца детали, остаток в хранилищах и прогресс секции.
4. Открыть каждое сохранение отдельно и повторить оставшиеся команды непрерывной партии. Деталь находится ровно у одного владельца до использования, секция получает её один раз. В отдельном прогоне отменить доставку после получения груза, вновь назначить работу и проверить тот же баланс. Для повреждённой копии сохранения проверить сообщение и возможность продолжить открытую партию.
5. Завершить дом, приготовить или собрать еду, назначить кровати, дождаться еды и сна всех троих. Верхняя кровать достижима через дверь и лестницу при снятии крыши камерой и после загрузки. У каждого контрольного исхода хранить исходный файл, последовательность команд, такт и наблюдаемый результат. Выполнение этого маршрута относится к приёмке демо.
## Что получает M01
Авторитетный мир принимает команду и владеет единственными экземплярами груза, заказа и резерва. Клиент читает завершённый такт. Для нового поколения сохраняются постоянные ID, состояние случайности, резервы, запланированные события, версии и контрольные суммы правил. Успешная загрузка меняет инкарнацию сеанса. При ошибке открытый мир продолжает работу. Реализация этих гарантий проверяется поэтапно. [Такт](systems/S01.md) · [Сохранение](systems/S15.md) · [Права и сеанс](systems/S16.md) · [Правила](systems/S19.md)
Первый исполняемый тест M01 использует доступное каноническое представление прототипа — байты сохранения 13 после каждого такта, включая маршрут, логические счётчики и команды игроков. Из одного начального состояния журнал проходит в последовательном эталоне и на 2, 6 и 12 рабочих потоках. Непрерывная партия задаёт ожидаемое продолжение после загрузки. Порядок применения предложений и судьбу последнего доступного предмета проверяют игровыми утверждениями. Перед изменением исполнителя действует [проверка API VoidLibrary](void-library.md).
+22
View File
@@ -57,8 +57,30 @@
Первый пакет имеет одного владельца контрактов времени, ID и публикации. После закрепления интерфейсов отдельные исполнители берут адаптацию навигации, экономики и клиента с раздельными файлами. Интеграционный тест проверяет целый такт.
## Неизменяемый снимок M01
`World::capture() const` возвращает `std::shared_ptr<const World>`. Владелец вызывает его после завершения всех заданий стадии. Логические поля мира и доступные читателю счётчики находятся в едином копируемом `detail::WorldState`. Снимок владеет отдельными контейнерами жителей, запасов, маршрутов, работ и резервов. Конфигурация числа исполнителей остаётся доступной читателю. Пул, обратные вызовы исполнителя и восстанавливаемый кэш маршрутов принадлежат рабочему миру. Ошибка выделения памяти передаётся владельцу. [Интерфейс и данные](../../../engine/include/settlement/core/world.hpp) · [Копирование](../../../engine/src/world.cpp)
Четыре проверки `settlement_core_tests.exe --tag snapshot` прошли в Windows x64 Release под Wine. Они проверяют копии в эталоне и на 2/6 потоках, удержание данных при дальнейшем развитии и уничтожении исходного мира, паузу с материалом в руках, вложенные маршруты и резервы, чтение из второго потока и освобождение обратных вызовов вместе с рабочим миром. Полный прогон дал 46 случаев ядра и 4 LAN, включая формат сохранения 13 и протокол 11. [Проверки снимков](../../../tests/snapshot_tests.cpp)
Для сцены из существующего `benchmarks/colony.cpp` на карте 80 × 80 с шестью потоками выполнены три прогона для 50 и 500 жителей. После 32 тактов прогрева снимок создавался после каждого из 240 тактов. Измерение охватывает выделение и копирование в `capture()`. Чтение снимка и освобождение ссылки выполнялись за пределами интервала. Медианы трёх p50/p95 составили 2/4 мкс для 50 жителей и 23/68 мкс для 500. Отдельные p95 составили 4, 7 и 4 мкс, затем 68, 81 и 67 мкс. Это измерение кросс-сборки GCC 16.2.0 под Wine 11.
Общая библиотечная публикация неизменяемого состояния отслеживается в Void/Library. Переход на неё требует проверок удержания старой версии, независимости от изменяемого источника, согласованной версии и освобождения читателей при остановке. Игровое копирование выполняет `World::capture()`. [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5)
## Приёмка
В срезе S01-04 `SimulationRuntime` владеет изменяемым миром в отдельном потоке Void. Шаг соответствует 50 мс монотонных часов. Очередь допускает по умолчанию 256 операций вместе с исполняемой, а перегрузка возвращает `Busy`. После каждой операции владелец может выполнить один просроченный такт, сохраняя обслуживание команд. Пауза мира и остановка тактов из-за меню имеют отдельные состояния. При продолжении отсчёт начинается заново. [Интерфейс владельца](../../../engine/include/settlement/core/simulation_runtime.hpp)
Публикация содержит UUID мира и инкарнации, ревизию, неизменяемые мир и правила, следующие номера запросов двух клиентов. `latest()` возвращает последний завершённый снимок, а `snapshot_for_save()` дополнительно проверяет рабочее состояние владельца. Читатель может удерживать предыдущие поколения, поэтому потребление памяти зависит от числа таких ссылок. Новая команда подготавливает копию журнала квитанций. Потактное продвижение и точные повторы используют уже опубликованный журнал.
Исключение при такте, команде или подготовке публикации переводит владельца в `Faulted`. Предыдущий снимок и завершённые квитанции доступны для чтения, новые изменения получают ошибку. Восстановление требует подходящего кандидата загрузки. `begin_load()` фиксирует текущую инкарнацию и номер запроса, который проверяется повторно непосредственно при переключении мира. Более новый запрос отменяет публикацию старого кандидата. Каждая успешная загрузка создаёт новую инкарнацию, в том числе при откате того же мира.
Регрессии `--tag runtime` проверяют 20 тактов в секунду с управляемыми часами и эталон на 1/2/6/12 исполнителях, команды на паузе, чтение во время заблокированной задачи, отказы и восстановление, порядок загрузок, переполнение очереди и завершение принятых операций при выходе. Подключение окна к этому интерфейсу выполняется отдельным срезом. [Проверки владельца](../../../tests/runtime_tests.cpp)
На ветке `system/s01-simulation` три параллельные стадии мира используют закреплённые `Void::Async::ThreadExecutor` и `FuturePool`. При заполнении лимита координатор выполняет задание сам. Стадия дожидается ранее принятых заданий и при исключении. Последовательный эталон вызывает те же игровые операции. На журнале из 750 тактов канонические сохранения после каждого такта совпали у эталона и вариантов с 2, 6 и 12 потоками, в том числе при лимите одного задания и после загрузки в процессе переноски. [Исполнитель](../../../engine/include/settlement/core/worker_pool.hpp) · [Проверки отказов](../../../tests/executor_tests.cpp) · [Воспроизведение](../../../tests/replay_tests.cpp)
В Windows x64-сборках под Wine при шести потоках медиана измерений p95 такта при переходе на Void изменилась с 86 до 96 мкс для 50 жителей и с 407 до 333 мкс для 500. Нативные замеры Windows, неизменяемая публикация завершённого такта и восстановление после ошибки остаются отдельными проверками.
- Сравнить хеш каждого такта на последовательном эталоне и 2/6/12 потоках, включая одинаковые команды и сохранение внутри стройки.
- Задержать выбранные задачи, завершить их в обратном порядке, отменить мир во время расчёта. Новое поколение принимает только свои результаты.
- Инъецировать ошибку в середину стадии. Опубликованное состояние остаётся последним завершённым тактом, предметы и резервы согласованы.
+6
View File
@@ -60,6 +60,12 @@ S06 владеет фактическими количествами, содер
## VoidLibrary и приёмка
Первый срез M01 хранит в жителях, требованиях материалов и остановках доставки постоянные `ResourceNodeId` и `StorageId`. Ноль означает отсутствие ссылки. Удаление более раннего склада или узла сохраняет цель активной работы. Списки объектов упорядочены по ID, чтение использует двоичный поиск. Формат 13 продолжает хранить прежние позиции. Загрузчик удерживает их во временном буфере, проверяет порядок ID и переводит в постоянные ссылки до проверки состояния мира. [Модель](../../../engine/include/settlement/core/world.hpp) · [Кодек](../../../engine/src/world_save.cpp)
Счётчик со значением `UINT64_MAX` обозначает исчерпание. Последний выдаваемый ID равен `UINT64_MAX - 1`. Фабрики и команды проверяют следующий ID через закреплённый `Void::Numeric::checked_add` до изменения объектов и геометрии. Фабрика сообщает `overflow_error`, команда возвращает `Busy` и сохраняет номер следующей команды. Общая возможность восстанавливаемого счётчика предложена в [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Переход на неё проверяется независимыми мирами, сохранением после удаления объектов и отказом у верхней границы.
Семь проверок `--tag identity` под Wine покрывают удаление более ранних объектов при переноске, доставку с двух складов, кладовую, засев без склада, готовую продукцию плотника, границы счётчиков и недопустимые старые ссылки. Загруженные копии продолжают совпадать потактно в последовательном режиме и на 2/6/12 потоках, включая контрольную точку с правилами и удерживаемый снимок. Постоянные ID производственных заказов, стеков, резервов и передач входят в последующие срезы. Для общего резервирования и переноса количеств зарегистрирован [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). [Исполняемые проверки](../../../tests/identity_tests.cpp)
Применять существующие подходящие средства контейнеров, проверяемой арифметики, сериализации и результатов из [VoidLibrary](../void-library.md). Для отсутствующей возможности перед локальной реализацией найти либо создать issue в `Void/Library` и указать ссылку в задаче и коде.
- Два заказа запрашивают последнюю единицу ресурса. Только один получает резерв, свободный запас остаётся неотрицательным.
+12
View File
@@ -25,6 +25,14 @@
## Границы интерфейсов
`CheckpointFiles` обслуживает файлы вне потока окна. `try_save` удерживает опубликованный снимок и передаёт формирование контрольной точки единственному писателю с лимитом `max_checkpoint_bytes`. `try_load` возвращает номер запроса и future отдельного кандидата. Один ограниченный исполнитель чтения открывает файл один раз, проверяет размер и читает до конца под общим лимитом, включая рост файла после открытия. Ошибка современного формата сохраняет диагностику кодека. Импорт прежнего сохранения получает новый постоянный UUID и точный поддерживаемый набор правил из установленного каталога. [Интерфейс файлов](../../../engine/include/settlement/core/checkpoint_files.hpp) · [Проверки адаптера](../../../tests/checkpoint_file_tests.cpp)
Служба живёт до закрытия окна и завершает принятые чтения и записи при остановке. Окно связывает подготовку с `LoadTicket`, проверяет размеры карты и передаёт кандидат владельцу симуляции. Этот же владелец сверяет инкарнацию и последний запрос перед публикацией. Сценарии `--tag checkpoint-file` проверяют удерживаемый снимок при продвижении партии, прежние версии 1/8/9/13, диагностику несовместимых правил, рост файла, переполнение очереди, независимость писателя от задержанного чтения и завершение очереди при выходе.
Windows-адаптер чтения связан с [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). Условие перехода на библиотечную операцию — проверки чтения одним дескриптором до конца файла, путей Unicode, исходного размера и роста сверх лимита. Служба продолжает задавать ограничение приёма и владение запросом.
Контрольная точка версии 1 содержит постоянный UUID мира, город, такт, полный выбранный набор пакетов с точными версиями и SHA-256, а также состояние мира в формате 13. Декодер проверяет внешнюю контрольную сумму, заново разрешает набор правил по установленному каталогу и создаёт кандидат мира существующим проверенным загрузчиком. Клиенту доступны имя несовместимого пакета и поле ошибки. Восемь проверок под Wine охватывают переноску материалов, продолжение расчёта, перестановку каталога, обрезанные файлы, недопустимое состояние и тело размером более 16 МиБ. [Кодек контрольной точки](../../../engine/include/settlement/core/checkpoint.hpp) · [Проверки](../../../tests/checkpoint_tests.cpp)
`SaveRequest`, `SaveSnapshot`, `SaveManifest` и `LoadCandidate` — предлагаемые новые интерфейсы. Запрос содержит слот и желаемую операцию. Снимок привязан к одному завершённому такту. Манифест описывает все необходимые блоки и контрольные суммы. Кандидат загрузки предоставляет результат проверки до замены мира. Завершение операции возвращает идентификатор запроса, состояние и диагностическую причину ошибки.
При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md)
@@ -46,6 +54,10 @@
## Приёмка
Первый Windows-срез службы сохранений ставит в ограниченную очередь запись с удерживаемым снимком, тактом и инкарнацией. Единственный исполнитель формирует байты, создаёт временный файл рядом со слотом, записывает и сбрасывает данные, закрывает дескриптор и публикует замену. Результат отдельно сообщает о видимости нового файла и об ошибке очистки. Принятые записи завершаются в порядке приёма, включая несколько запросов в один слот. [Интерфейс](../../../engine/include/settlement/core/save_service.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/3)
Девять проверок `--tag save-slot` прошли в Windows x64 под Wine. Если во время замены читатель удерживал дескриптор с разрешением удаления, Wine вернул ошибку доступа 5. Служба сохранила прежние байты и удалила временный файл. Следующая запись после закрытия читателя успешно заменила слот. Нативная Windows и сохранность после потери питания требуют отдельной проверки. [Исполняемые проверки](../../../tests/save_service_tests.cpp)
- **S15-A01.** Сохранить демо при доставке на второй этаж. После загрузки сравнить сумки, склад, резервы и детали стройки, затем завершить дом без повторной оплаты материала.
- **S15-A02.** Прервать запись после каждого блока и перед публикацией. Каждый запуск открывает целую предыдущую либо целую новую генерацию.
- **S15-A03.** Воспроизвести один журнал в последовательном режиме и на 2, 6 и 12 потоках с задержанным чтением чанков. Канонические хеши совпадают на каждом такте.
+4
View File
@@ -47,6 +47,10 @@
## Приёмка
Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6)
Селектор `--tag session` под Wine выполнил десять проверок, включая двух клиентов, конфликт данных повтора, откат с новой инкарнацией и отказ до/после изменения. Сценарий из 700 тактов сверяет эталон и 2/6/12 потоков. Подключение окна и сетевого транспорта к владельцу мира входит в следующий срез M01. [Сценарии](../../../tests/session_tests.cpp)
- **S16-A01.** Два клиента общего города одновременно заказывают последний доступный предмет. Выполняется один расход, второй запрос получает объяснимый результат.
- **S16-A02.** Передать чужой `player`, чужой город, просроченный экземпляр сессии и повтор команды. Проверить авторизацию и устойчивые квитанции.
- **S16-A03.** Разорвать соединение между принятием сделки и получением квитанции. После возврата предметы и деньги совпадают со снимком хозяина.
+20
View File
@@ -4,6 +4,24 @@
Статус — план реализации. Игрок выбирает совместимый набор механик при создании мира. Собственные материалы и моды подключаются через документированный формат, а состояние этой конфигурации сохраняется вместе с колонией. Основа вводится в [M01](../milestones/M01.md), используется игровыми системами и публикуется для авторов в [M10](../milestones/M10.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Первый исполняемый срез M01
`load_rule_package` читает ограниченный по размеру JSON с версией схемы, определениями, ссылками и зависимостями. `resolve_rules` для выбранных модулей вычисляет транзитивный состав, проверяет конфликты и возвращает точные версии с SHA-256. Порядок обхода файлов не меняет идентичность. Для проверки запустить `settlement_core_tests.exe --tag rules`. [Публичный интерфейс](../../../engine/include/settlement/core/rules_manifest.hpp) · [Реализация](../../../engine/src/rules_manifest.cpp) · [Проверки](../../../tests/rules_tests.cpp)
На 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)
@@ -22,6 +40,8 @@
Долговременное состояние обработчика представляет собой проверяемые сериализуемые значения с явной схемой. Продолжение события хранит идентификатор шага, данные и запланированный такт. Персистентные coroutine-стеки, нативные замыкания и произвольная память интерпретатора в формат сохранения не входят. Сам обработчик выполняется с фиксированным входом и возвращает предлагаемые изменения.
Состояние обработчика получает ключ пакета, обработчика и версии схемы. Продолжение имеет постоянный идентификатор, детерминированные данные и назначенный такт. Предложения связываются с исходной ревизией снимка и инкарнацией. Владелец проверяет их в устойчивом порядке и одной операцией применяет новое состояние, продвижение генератора случайности, расписание и игровые изменения. Отказ либо устаревшая инкарнация отбрасывают весь этот результат. Исполнение Lua вводится в S19-W03.
Игровой API задаёт детерминированный порядок коллекций, отдельные потоки случайных чисел и правила числовых значений. Авторитетные решения используют разрешённые целочисленные либо явно квантованные величины. Прикладное API запрещает неупорядоченную итерацию для последовательности игровых изменений. Время берётся из номера такта. Вызовы системы, сети, произвольных файлов и нативных расширений недоступны исполняемому игровому скрипту.
Каждый обработчик ограничен по инструкциям, памяти, размеру результата и стоимости вызванных функций хоста. Счётчик Lua-инструкций дополняется ограничением работы C++-функций, поскольку эта работа выполняется вне счётчика интерпретатора. Состояние обработчика и предложения применяются атомарно. Ошибка отбрасывает его незавершённый результат и ставит авторитетное продвижение на безопасную границу с диагностикой. Состав правил мира сохраняется. [Стадии симуляции](S01.md)
+14
View File
@@ -33,6 +33,20 @@
## Первое применение правила в M01
| Пробел в проверенном pin | Локальная задача и условие перехода на Void |
|---|---|
| [Атомарная замена файлов на Windows, #3](https://git.faumaray.com/Void/Library/issues/3) | S15, `save_service_win32.cpp`. Заменить адаптер после проверок первой записи, замены слота и отказов до и после публикации, включая пути Unicode. |
| [Ограниченное чтение одного файла на Windows, #9](https://git.faumaray.com/Void/Library/issues/9) | S15, `checkpoint_files.cpp`. Закреплённая `FileSystem::read_file_bounded` возвращает `unsupported` в Windows. Проверки замены охватывают Unicode, точную границу размера, увеличение уже открытого файла сверх лимита и отказ без возврата частичных данных. [API](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/System/Path.hpp) |
| [Разрешение набора пакетов, #4](https://git.faumaray.com/Void/Library/issues/4) | S19, `rules_manifest.cpp`. Проверить транзитивный набор, конфликты, циклы, диагностику и одинаковый отпечаток при перестановке входа. Игровая схема остаётся у S19. |
| [Публикация неизменяемого состояния с ревизией, #5](https://git.faumaray.com/Void/Library/issues/5) | S01, `simulation_runtime.cpp`. Читатели удерживают старую ревизию, пока владелец публикует следующую. При замене мира проверяются инкарнация и сохранность снимка после отказа. |
| [Идемпотентные результаты и конфликт повторов, #6](https://git.faumaray.com/Void/Library/issues/6) | S16, `command_dispatcher.cpp`. Готовый примитив должен вернуть первоначальные принятые и отклонённые результаты, распознать другой запрос под тем же номером и отсечь старую инкарнацию. |
| [Восстанавливаемый счётчик ID с проверкой исчерпания, #7](https://git.faumaray.com/Void/Library/issues/7) | [S06](systems/S06.md) и [S04](systems/S04.md), счётчики в `WorldState` и операции выделения в `world.cpp`. Переход проверяется на двух независимых мирах, сохранении после удаления наибольшего ID и атомарном отказе у верхней границы. В проверенном pin `SeqId<Tag>` использует общий счётчик для тега. [API](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Core/Counted.hpp) |
| [Условное резервирование и перенос количеств в памяти, #8](https://git.faumaray.com/Void/Library/issues/8) | Для реестра резервов [S04](systems/S04.md) и передачи между владельцами [S06](systems/S06.md). Проверка замены должна покрыть конкуренцию за последнюю единицу, полный откат отказа, отмену с грузом и однократное применение повторной доставки после загрузки. Закреплённая `Storage::Batch` применяет условия к ключам и значениям движка хранения. Правила собственности и рецепты определяет игра. [API пакетных операций](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Storage/Batch.hpp) |
При подготовке последовательного эталона 2 декабря 2026 года публичный `main` указывал на закреплённый `7b0fea6`. Для сравнения прототипа доступны `World::write_save` поверх Void Binary/Core и проверки Void Testing. Игровая ветка эталона может прямо вызвать тот же расчёт назначения, маршрута и движения без создания исполнителя. Она сохраняет тот же порядок применения результатов. Журнал приказов и сравнение состояния конкретной колонии принадлежат тесту игры. Новый универсальный исполнитель для этого не требуется. [Кодек игры](../../engine/src/world_save.cpp) · [Набор проверок игры](../../tests/core_tests.cpp)
Для будущей замены пула `FuturePool::try_submit` принимает работу через `ThreadExecutor` и возвращает future. Занятые исполнением задачи входят в предел допуска. При отказе вызываемая функция остаётся у отправителя. Остановка закрывает допуск и завершает принятые задачи. Режим после `join()` не обслуживает новые отправки в `FuturePool`. При замене игрового пула проверить повтор или исполнение каждой отклонённой работы, завершение уже принятых задач до разрушения их данных, исключения и частичный запуск на Windows. [Публичный FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/FuturePool.hpp) · [Контракт ThreadExecutor](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/ThreadExecutor.hpp)
У текущего `settlement::WorkerPool` есть отправка функции, получение future, число потоков и ожидание принятых работ при завершении. Сверить эти четыре операции с `ThreadExecutor + FuturePool`. Начать перенос с эталонной партии, затем испытать переполнение, частичный запуск и остановку. При переполнении симуляция должна выполнить тот же набор логических работ с тем же результатом. Выбранный вариант измерить на малой партии и на нагруженном городе. Существующие тесты Void проверяют поведение утилит, игровые тесты должны дополнительно сравнить хеши мира. [Текущий пул](../../engine/src/worker_pool.cpp) · [Проверки FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/FuturePool.cpp) · [Проверки запуска потоков](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/ThreadExecutor.cpp)
[Мастер-план](../../PLAN.md)
@@ -0,0 +1,66 @@
#pragma once
#include "settlement/core/rules_manifest.hpp"
#include "settlement/core/world.hpp"
#include <Void/Core/Uuid.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <span>
#include <string>
#include <string_view>
namespace settlement {
inline constexpr std::uint32_t checkpoint_version = 1;
inline constexpr std::string_view checkpoint_signature = "STHCHKPT";
inline constexpr std::size_t max_checkpoint_body_bytes = 128 * 1024 * 1024;
inline constexpr std::size_t max_checkpoint_metadata_bytes = 64 * 1024;
inline constexpr std::size_t max_checkpoint_bytes =
24 + max_checkpoint_metadata_bytes + max_checkpoint_body_bytes + 32;
enum class CheckpointError : std::uint8_t {
InvalidFrame,
UnsupportedVersion,
LimitExceeded,
IntegrityMismatch,
InvalidIdentity,
RulesMismatch,
InvalidWorld,
ResourceFailure
};
struct CheckpointDiagnostic {
CheckpointError code;
std::string field;
std::string package;
std::string message;
};
struct WorldCheckpoint {
std::unique_ptr<World> world;
Void::Uuid::Uuid world_id;
std::uint64_t city;
RulesManifest rules;
};
// Version 1 stores magic, schema, metadata length and body length, then world UUID,
// city, tick, rules fingerprint and the sorted complete package closure. Each
// package stores its ID, exact version and SHA-256. The body uses World's save
// codec. A final SHA-256 covers every preceding byte. Integers are little-endian.
// The caller holds a stable World for the entire synchronous encode operation.
[[nodiscard]] std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city,
const RulesManifest& rules);
// Input is bounded and integrity checked before package or World decoding.
// Rules are resolved from the installed catalog and must match the complete
// saved closure exactly. The returned candidate is independent of any live world.
[[nodiscard]] std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
std::string_view bytes, std::span<const RulePackage> installed,
std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel);
} // namespace settlement
@@ -0,0 +1,77 @@
#pragma once
#include "settlement/core/save_service.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <expected>
#include <functional>
#include <vector>
namespace settlement {
enum class CheckpointFileError {
Io, TooLarge, UnsupportedFormat, InvalidCheckpoint, InvalidLegacy,
IdentityGeneration, ResourceFailure, ReaderFailure,
};
struct CheckpointFileDiagnostic {
CheckpointFileError code;
std::string message;
std::uint32_t native_error = 0;
// Present for a modern codec failure, including the exact incompatible package.
std::optional<CheckpointDiagnostic> checkpoint;
};
using CheckpointLoadResult = std::expected<WorldCheckpoint, CheckpointFileDiagnostic>;
enum class CheckpointLoadAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
struct CheckpointLoadSubmission {
CheckpointLoadAdmission admission = CheckpointLoadAdmission::InvalidRequest;
std::uint64_t request_id = 0;
std::future<CheckpointLoadResult> completion;
};
enum class CheckpointReadPhase { Opened, BeforeRead };
struct CheckpointFilesOptions {
std::size_t load_capacity = 4; // Includes the running read.
std::size_t save_capacity = 8;
std::size_t max_load_bytes = max_checkpoint_bytes;
// Diagnostic/test seam on the reader. Captures must outlive shutdown.
// Calling shutdown from this observer throws logic_error.
std::function<void(CheckpointReadPhase)> read_observer;
};
// Keep one instance for the window lifetime so accepted saves retain FIFO order
// across world/session replacements. Workers own their paths, catalog and held
// snapshots. The caller owns load-ticket fencing and UI completion handling.
class CheckpointFiles {
public:
explicit CheckpointFiles(CheckpointFilesOptions options = {});
explicit CheckpointFiles(std::vector<RulePackage> installed, CheckpointFilesOptions options = {});
~CheckpointFiles();
CheckpointFiles(const CheckpointFiles&) = delete;
CheckpointFiles& operator=(const CheckpointFiles&) = delete;
// Obtain a healthy immutable view with SimulationRuntime::snapshot_for_save().
// Materialization runs on the existing SaveService writer, bounded to
// max_checkpoint_bytes. Rejected calls do not retain the snapshot.
[[nodiscard]] SaveSubmission try_save(
const std::filesystem::path& destination,
const std::shared_ptr<const PublishedSnapshot>& snapshot);
// Opens once and checks actual size/EOF under the byte limit. Modern failures
// retain their diagnostics. Legacy imports receive a fresh stable world UUID
// and the exact supported default manifest from this instance's catalog.
[[nodiscard]] CheckpointLoadSubmission try_load(
const std::filesystem::path& source, std::size_t workers = min_worker_count,
ExecutionMode mode = ExecutionMode::Parallel);
// Closes admission and drains both services, without holding the admission
// mutex while joining. Destruction requires callers to stop using this object.
void shutdown();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace settlement
@@ -0,0 +1,38 @@
#pragma once
#include "settlement/core/checkpoint.hpp"
namespace settlement {
enum class ColonyProfile { Default, PlankBeds };
// Constructed only after the selected packages match an implemented profile.
class ColonyRules {
public:
[[nodiscard]] ColonyProfile profile() const noexcept { return profile_; }
[[nodiscard]] BedConstructionMode bed_mode() const noexcept { return bed_mode_; }
[[nodiscard]] const RulesManifest& manifest() const noexcept { return manifest_; }
private:
ColonyRules(ColonyProfile profile, BedConstructionMode beds, RulesManifest manifest);
ColonyProfile profile_;
BedConstructionMode bed_mode_;
RulesManifest manifest_;
friend std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest&);
};
[[nodiscard]] std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest&);
[[nodiscard]] std::expected<ColonyRules, RulesDiagnostic> colony_rules(ColonyProfile);
// Initializes both the enacted mechanics and their frozen package identities.
[[nodiscard]] std::expected<WorldCheckpoint, CheckpointDiagnostic> make_colony_checkpoint(
ColonyProfile profile, std::size_t workers = min_worker_count,
ExecutionMode mode = ExecutionMode::Parallel);
// Default rules preserve historical saved bed modes, including inactive worlds.
// The optional plank-bed profile requires a saved nonstaged mode. This gate is
// game-specific; generic codecs and SimulationRuntime accept caller-owned catalogs.
[[nodiscard]] std::expected<void, CheckpointDiagnostic> validate_colony_checkpoint(
const WorldCheckpoint&);
} // namespace settlement
@@ -0,0 +1,133 @@
#pragma once
#include "settlement/core/world.hpp"
#include <Void/Core/Uuid.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <variant>
#include <vector>
namespace settlement {
inline constexpr std::uint32_t command_envelope_version = 1;
struct SessionIdentity {
Void::Uuid::Uuid world;
Void::Uuid::Uuid session;
std::uint64_t city = 1;
bool operator==(const SessionIdentity&) const = default;
};
// Created by the trusted transport/local adapter, never decoded from payload data.
// Reconnected clients keep their assigned slot within the same session.
struct TrustedClient {
std::uint8_t player;
};
struct CommandPayload {
CommandKind kind = CommandKind::PlaceBed;
GridPosition cell{};
std::uint8_t value = 0;
GridPosition destination{};
AgentId resident = 0;
bool operator==(const CommandPayload&) const = default;
};
struct LegacyCabinPayload {
GridPosition cell;
GridPosition sawmill;
GridPosition stonecutter;
bool operator==(const LegacyCabinPayload&) const = default;
};
using SessionPayload = std::variant<CommandPayload, LegacyCabinPayload>;
struct CommandEnvelope {
std::uint32_t version = command_envelope_version;
Void::Uuid::Uuid world;
Void::Uuid::Uuid session;
std::uint64_t city = 1;
std::uint64_t request = 0;
SessionPayload payload;
};
enum class DispatchStatus : std::uint8_t {
Completed,
UnsupportedVersion,
WrongWorld,
StaleSession,
UnauthorizedClient,
InvalidRequest,
OutOfOrder,
Conflict,
Busy,
Faulted
};
struct DispatchReceipt {
DispatchStatus status;
// Meaningful for Completed. Revision counts successful dispatcher mutations
// in this session, including legacy cabin placement, independently of ticks.
CommandStatus command_status = CommandStatus::Unavailable;
std::uint64_t tick = 0;
std::uint64_t revision = 0;
bool operator==(const DispatchReceipt&) const = default;
};
enum class CommandMutationPhase : std::uint8_t { BeforeMutation, AfterMutation };
struct CommandDispatcherOptions {
std::size_t max_receipts_per_client = 65'536;
// Optional failure observer around authoritative application. An exception
// fences the staged dispatcher, so the owner must discard its candidate.
void (*mutation_observer)(CommandMutationPhase) = nullptr;
};
// Single-owner component. The caller must pass the session's authoritative World.
// Exact repeats retain their original result for the entire session. At capacity,
// new requests receive Busy and stored receipts remain available. No eviction.
// Domain rejections consume a request number; transient dispatch errors do not.
// Copies may be staged with a candidate World and committed only after publication.
// Any mutation exception poisons this instance. Old completed receipts remain
// readable, while further effects require a newly constructed session/dispatcher.
// Upstream replacement contract and tests: Void/Library#6
// https://git.faumaray.com/Void/Library/issues/6
class CommandDispatcher {
public:
explicit CommandDispatcher(SessionIdentity identity, CommandDispatcherOptions options = {});
[[nodiscard]] const SessionIdentity& identity() const noexcept { return identity_; }
[[nodiscard]] std::uint64_t revision() const noexcept { return revision_; }
[[nodiscard]] bool faulted() const noexcept { return faulted_; }
[[nodiscard]] std::size_t receipt_count(TrustedClient client) const noexcept;
[[nodiscard]] std::uint64_t next_request(TrustedClient client) const noexcept;
[[nodiscard]] DispatchReceipt dispatch(World& world, TrustedClient client, const CommandEnvelope& command);
// Invalid context/conflicting reuse returns its dispatch error. An otherwise
// valid request without a retained receipt returns nullopt without side effects.
[[nodiscard]] std::optional<DispatchReceipt> lookup(TrustedClient client, const CommandEnvelope& command) const;
private:
struct Record {
std::uint64_t city;
SessionPayload payload;
DispatchReceipt receipt{DispatchStatus::Faulted};
bool completed = false;
};
[[nodiscard]] std::optional<DispatchStatus> validate_context(
TrustedClient client, const CommandEnvelope& command) const noexcept;
[[nodiscard]] CommandStatus apply(World& world, TrustedClient client, const CommandEnvelope& command);
SessionIdentity identity_;
CommandDispatcherOptions options_;
std::array<std::vector<Record>, colony_player_slots> records_;
std::uint64_t revision_ = 0;
bool faulted_ = false;
};
} // namespace settlement
@@ -0,0 +1,104 @@
#pragma once
#include <array>
#include <cstddef>
#include <expected>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace settlement {
using RulesDigest = std::array<std::byte, 32>;
struct RulesDiagnostic {
std::string package;
std::string source;
std::string field;
std::string message;
std::size_t byte_offset = 0;
};
struct RulesLimits {
std::size_t package_bytes = 256 * 1024;
std::size_t catalog_bytes = 4 * 1024 * 1024;
std::size_t packages = 128;
std::size_t definitions = 1024;
std::size_t dependencies = 64;
std::size_t references = 64;
std::size_t json_depth = 24;
std::size_t json_nodes = 16384;
};
struct RuleDefinition {
std::string id;
std::string kind;
std::string canonical_data;
std::vector<std::string> references;
};
struct FrozenRulePackage {
std::string id;
std::string exact_version;
RulesDigest content_sha256{};
bool operator==(const FrozenRulePackage&) const = default;
};
class RulesManifest;
struct RulePackageData;
// Schema 1 requires schema/id/version/dependencies/exclusive_capabilities/definitions.
// Package IDs use lower-case dot-separated segments. Definition IDs and capabilities
// use package:local-name. Each definition has id/kind/data/references, where data is
// integer-valued strict JSON. Unknown metadata fields are errors. Set-like arrays are
// sorted; arrays inside data retain order. Sources are diagnostic labels, never paths
// to execute or open. Only one installed version of each package ID is allowed.
class RulePackage {
public:
[[nodiscard]] const FrozenRulePackage& identity() const noexcept;
[[nodiscard]] std::span<const RuleDefinition> definitions() const noexcept;
[[nodiscard]] std::string_view canonical_json() const noexcept;
private:
explicit RulePackage(std::shared_ptr<const RulePackageData> data);
std::shared_ptr<const RulePackageData> data_;
friend std::expected<RulePackage, RulesDiagnostic> load_rule_package(
std::string_view, std::string_view, const RulesLimits&);
friend std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
std::span<const RulePackage>, std::span<const std::string>, const RulesLimits&);
};
class RulesManifest {
public:
[[nodiscard]] std::span<const FrozenRulePackage> packages() const noexcept { return packages_; }
[[nodiscard]] const RulesDigest& fingerprint() const noexcept { return fingerprint_; }
// Schema-tagged canonical UTF-8 bytes shared by persistence and handshake callers.
[[nodiscard]] std::string_view canonical_json() const noexcept { return canonical_json_; }
bool operator==(const RulesManifest&) const = default;
private:
RulesManifest(std::vector<FrozenRulePackage>, RulesDigest, std::string);
std::vector<FrozenRulePackage> packages_;
RulesDigest fingerprint_{};
std::string canonical_json_;
friend std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
std::span<const RulePackage>, std::span<const std::string>, const RulesLimits&);
};
[[nodiscard]] std::expected<RulePackage, RulesDiagnostic> load_rule_package(
std::string_view source, std::string_view json, const RulesLimits& limits = {});
// Resolves selected IDs and their transitive dependencies. Prerelease dependencies
// require an exact constraint equal to that full version, optionally prefixed by '='.
// Content digests are computed from the parsed content and never trusted from input.
[[nodiscard]] std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
std::span<const RulePackage> available, std::span<const std::string> selected,
const RulesLimits& limits = {});
[[nodiscard]] std::expected<std::vector<RulePackage>, RulesDiagnostic> builtin_rule_packages();
[[nodiscard]] std::expected<RulesManifest, RulesDiagnostic> default_rules_manifest();
[[nodiscard]] std::string rules_digest_hex(const RulesDigest& digest);
} // namespace settlement
@@ -0,0 +1,103 @@
#pragma once
#include <Void/Core/Uuid.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <future>
#include <memory>
#include <string>
namespace settlement {
enum class SavePhase {
Materialize, CreateStage, WriteStage, FlushStage, CloseStage, Publish, Published,
};
enum class SaveError {
None, ProducerFailed, TooLarge, Io, Internal, Injected,
};
struct SaveRequest {
// Absolute filesystem path. The parent must exist. Both creation and
// replacement are supported; acceptance does not imply the path is writable.
// Open readers may make Windows reject replacement, even with delete
// sharing (observed ERROR_ACCESS_DENIED on Wine 11). Such failures preserve
// the old slot; they never trigger a delete/truncate publication fallback.
std::filesystem::path destination;
std::uint64_t tick{};
Void::Uuid::Uuid session{};
// Capture an immutable snapshot/shared byte buffer by value. Invoked exactly
// once, on the writer. Never capture live mutable World/UI state by reference.
// Copies must be cheap; materialization and its memory budget belong here.
std::function<std::string()> produce;
};
struct SaveResult {
std::uint64_t request_id{};
std::uint64_t tick{};
Void::Uuid::Uuid session{};
SaveError error{SaveError::None};
SavePhase phase{SavePhase::Materialize};
std::uint32_t native_error{};
bool visible_on_disk{false};
// True for an error after publication: the new file is visible and must not
// be reported as rolled back. Success promises flushed bytes and atomic
// visibility, not resilience to power loss on every filesystem/device.
bool durability_unknown{false};
std::uint32_t cleanup_error{};
// Set only if removal of this request's staging file failed.
std::filesystem::path retained_staging_file;
[[nodiscard]] bool succeeded() const noexcept { return error == SaveError::None; }
};
enum class SaveAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
struct SaveSubmission {
SaveAdmission admission{SaveAdmission::InvalidRequest};
// Zero and an invalid future on rejection. Accepted IDs start at one and
// increase in FIFO publication order, including for concurrent submitters.
std::uint64_t request_id{};
std::future<SaveResult> completion;
};
struct SaveServiceOptions {
std::size_t capacity{8}; // Includes the running request.
std::size_t max_bytes{64 * 1024 * 1024}; // Checked after materialization.
// Test seam, executed on the writer before each phase (each write chunk).
// Nonzero injects a native error. Published runs after the rename.
std::function<std::uint32_t(SavePhase)> fault_hook;
};
// One bounded Void::Async FIFO writer per service. Use one service for all
// requests to a slot; separate services/processes are independent writers.
// Windows adapter tracked by https://git.faumaray.com/Void/Library/issues/3.
// Replace it when Void::FileSystem::replace_file supports Windows and passes
// the save-slot create/replace, reader, phase-failure and sibling-preservation
// tests with the same visibility and cleanup reporting.
class SaveService {
public:
explicit SaveService(SaveServiceOptions options = {});
~SaveService(); // Drains accepted work; never destroy on its writer thread.
SaveService(const SaveService&) = delete;
SaveService& operator=(const SaveService&) = delete;
// Does no file IO or producer invocation and never waits for a slot, disk,
// or another submitter. Contention is Busy. Rejection does not copy/move the
// producer. Allocation/copy failures throw before accepting the request.
[[nodiscard]] SaveSubmission try_submit(const SaveRequest& request);
// Closes admission and drains every accepted request. Safe concurrently
// with submissions and other shutdown calls, but not object destruction.
// Throws logic_error if called from this service's producer/fault hook.
void shutdown();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace settlement
@@ -0,0 +1,100 @@
#pragma once
#include "settlement/core/checkpoint.hpp"
#include "settlement/core/command_dispatcher.hpp"
#include <Void/Time/Clock.hpp>
#include <array>
#include <exception>
#include <expected>
#include <functional>
#include <future>
#include <memory>
#include <optional>
namespace settlement {
enum class RuntimeState { Running, Faulted, Closed };
enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
enum class RuntimeOutcome { Completed, Faulted, Closed, Superseded, InvalidCandidate };
enum class RuntimePhase { BeforeTick, BeforeCapture, BeforeInstallCapture };
struct PublishedSnapshot {
SessionIdentity identity;
std::uint64_t revision;
std::shared_ptr<const World> world;
std::shared_ptr<const RulesManifest> rules;
std::array<std::uint64_t, colony_player_slots> next_requests;
};
struct RuntimeView {
RuntimeState state;
std::shared_ptr<const PublishedSnapshot> snapshot;
std::exception_ptr failure;
};
struct RuntimeResult {
RuntimeOutcome outcome;
std::optional<DispatchReceipt> receipt;
std::shared_ptr<const PublishedSnapshot> snapshot;
};
struct RuntimeSubmission {
RuntimeAdmission admission;
std::future<RuntimeResult> completion;
};
struct LoadTicket {
std::uint64_t request;
Void::Uuid::Uuid expected_session;
};
struct RuntimeOptions {
std::size_t capacity = 256; // Accepted operations, including the active operation.
bool ticking = true; // Presentation suspension is separate from World's pause.
std::shared_ptr<const Void::Time::MonotonicClock> clock;
CommandDispatcherOptions dispatcher;
// Runs on the owner thread. May block or throw for diagnostics/tests.
// Captures must outlive shutdown. Calling shutdown here throws logic_error.
std::function<void(RuntimePhase)> observer;
};
// A single background owner advances 50 ms logical steps and publishes independent
// immutable views. Supply a validated decoded checkpoint or an owned newly built
// world with a resolved manifest. No caller may retain mutable aliases to that world.
// Upstream publication replacement contract: https://git.faumaray.com/Void/Library/issues/5
class SimulationRuntime {
public:
explicit SimulationRuntime(WorldCheckpoint initial, RuntimeOptions options = {});
~SimulationRuntime();
SimulationRuntime(const SimulationRuntime&) = delete;
SimulationRuntime& operator=(const SimulationRuntime&) = delete;
[[nodiscard]] std::shared_ptr<const PublishedSnapshot> latest() const;
[[nodiscard]] RuntimeView view() const;
[[nodiscard]] std::expected<std::shared_ptr<const PublishedSnapshot>, RuntimeState> snapshot_for_save() const;
// Reads only the committed ledger, also available after a fault.
[[nodiscard]] std::optional<DispatchReceipt> lookup(
TrustedClient client, const CommandEnvelope& command) const;
[[nodiscard]] RuntimeSubmission try_submit(TrustedClient client, const CommandEnvelope& command);
[[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().
[[nodiscard]] RuntimeSubmission synchronize();
void notify_clock();
[[nodiscard]] std::expected<LoadTicket, RuntimeAdmission> begin_load();
// Moves candidate only on Accepted. Latest ticket and epoch are checked again
// at publication. Invalid/superseded candidates leave the live party intact.
[[nodiscard]] RuntimeSubmission try_install(LoadTicket ticket, WorldCheckpoint& candidate);
// Closes admission, settles queued futures as Closed, and joins the active
// operation. Safe concurrently with submissions and other shutdown calls.
// Object destruction itself requires callers to have stopped using the object.
void shutdown();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace settlement
+47 -24
View File
@@ -1,55 +1,78 @@
#pragma once
#include <condition_variable>
#include <Void/Async/FuturePool.hpp>
#include <atomic>
#include <cstddef>
#include <exception>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
namespace settlement {
// Limits and optional fault hooks are execution settings and are never saved.
// Hooks use zero-based worker/submission indices and may throw. Execution
// hooks can run concurrently on workers or on the coordinator during overload.
struct WorkerPoolOptions {
std::size_t max_admitted = 4096;
std::function<void(std::size_t)> before_worker_start;
std::function<void(std::size_t)> before_submit;
std::function<void(std::size_t)> before_execute;
};
class WorkerPool {
public:
explicit WorkerPool(std::size_t thread_count);
explicit WorkerPool(std::size_t thread_count, WorkerPoolOptions options = {});
~WorkerPool();
WorkerPool(const WorkerPool&) = delete;
WorkerPool& operator=(const WorkerPool&) = delete;
// World submits from its coordinator. Nested submission from a worker is
// rejected before admission, preventing a worker from waiting on its own pool.
template <typename Function>
auto submit(Function&& function) -> std::future<std::invoke_result_t<Function>> {
using Result = std::invoke_result_t<Function>;
auto task = std::make_shared<std::packaged_task<Result()>>(std::forward<Function>(function));
std::future<Result> result = task->get_future();
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) {
throw std::runtime_error("cannot submit work to a stopped worker pool");
}
tasks_.emplace([task]() { (*task)(); });
if (executor_->is_executor_thread()) {
throw std::logic_error("cannot submit nested work to the same worker pool");
}
work_available_.notify_one();
return result;
if (options_.before_submit || options_.before_execute) {
const auto index = submission_index_.fetch_add(1, std::memory_order_relaxed);
if (options_.before_submit) options_.before_submit(index);
return admit([this, index, function = std::forward<Function>(function)]() mutable -> decltype(auto) {
if (options_.before_execute) options_.before_execute(index);
return std::invoke(function);
});
}
return admit(std::forward<Function>(function));
}
[[nodiscard]] std::size_t thread_count() const noexcept;
private:
void worker_loop();
template <typename Function>
auto admit(Function&& function) -> std::future<std::invoke_result_t<Function>> {
auto submitted = futures_.try_submit(std::forward<Function>(function));
if (submitted) return std::move(*submitted);
if (submitted.error() != Void::Async::AdmissionError::overloaded) {
throw std::runtime_error("cannot submit work to a stopped worker pool");
}
// Failed admission leaves the callable untouched. Running it on the
// coordinator retains the same logical work and stores exceptions in its future.
using Result = std::invoke_result_t<Function>;
std::packaged_task<Result()> task(std::forward<Function>(function));
auto result = task.get_future();
task();
return result;
}
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::mutex mutex_;
std::condition_variable work_available_;
bool stopping_ = false;
std::size_t thread_count_;
WorkerPoolOptions options_;
std::atomic<std::size_t> submission_index_{0};
std::unique_ptr<Void::Async::ThreadExecutor> executor_;
Void::Async::FuturePool futures_;
};
} // namespace settlement
+72 -39
View File
@@ -17,6 +17,8 @@ namespace settlement {
using AgentId = std::uint64_t;
using JobId = std::uint64_t;
using ResourceNodeId = std::uint64_t;
using StorageId = std::uint64_t;
struct GridPosition {
std::int32_t x = 0;
@@ -103,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;
@@ -172,6 +175,7 @@ enum class CommandKind : std::uint8_t {
CraftDoor = 14, CraftFurniture = 15
};
enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy };
enum class ExecutionMode : std::uint8_t { Parallel, SerialReference };
inline constexpr std::uint8_t colony_host = 1;
inline constexpr std::size_t colony_player_slots = 2;
@@ -236,8 +240,8 @@ struct Agent {
std::vector<GridPosition> route;
std::size_t route_cursor = 0;
std::uint32_t work_remaining = 0;
std::size_t resource_node_index = no_entity_index;
std::size_t storage_index = no_entity_index;
ResourceNodeId resource_node_id = 0;
StorageId storage_id = 0;
Inventory inventory;
std::vector<GridPosition> haul_route;
std::size_t production_index = no_entity_index;
@@ -259,7 +263,7 @@ struct WorkJob {
};
struct ResourceNode {
std::uint64_t id = 0;
ResourceNodeId id = 0;
GridPosition position;
ItemType type = ItemType::None;
std::uint32_t quantity = 0;
@@ -281,7 +285,7 @@ struct ItemStack {
};
struct Storage {
std::uint64_t id = 0;
StorageId id = 0;
GridPosition position;
std::uint32_t capacity = 0;
std::uint32_t reserved_slots = 0;
@@ -316,13 +320,13 @@ struct Storage {
};
struct MaterialReservation {
std::size_t storage_index;
StorageId storage_id;
ItemType type;
std::uint32_t count;
};
struct ConstructionStop {
std::size_t storage_index;
StorageId storage_id;
std::vector<GridPosition> route_to_next;
};
@@ -344,10 +348,52 @@ struct ProductionOrder {
}
};
class World {
namespace detail {
// Logical data and observable counters share one copy operation at publication.
// Execution resources and rebuildable caches belong to World.
struct WorldState {
WorldState(std::uint64_t seed, std::int32_t width, std::int32_t height) noexcept
: seed_(seed), width_(width), height_(height) {}
std::uint64_t seed_;
std::uint64_t tick_ = 0;
std::uint64_t path_searches_ = 0;
std::uint64_t path_nodes_visited_ = 0;
std::uint64_t assignment_path_cache_hits_ = 0;
std::uint64_t jobs_completed_ = 0;
std::uint64_t meals_eaten_ = 0;
bool hunger_enabled_ = false;
std::int32_t width_;
std::int32_t height_;
AgentId next_agent_id_ = 1;
JobId next_job_id_ = 1;
std::uint64_t next_resource_node_id_ = 1;
std::uint64_t next_storage_id_ = 1;
std::vector<std::uint8_t> blocked_;
std::vector<Agent> agents_;
std::vector<WorkJob> jobs_;
std::vector<ResourceNode> resource_nodes_;
std::vector<Storage> storages_;
std::vector<ProductionOrder> production_orders_;
bool scenario_active_ = false;
bool staged_beds_ = false;
bool paused_ = false;
bool scenario_completed_ = false;
WorkPriority work_priority_ = WorkPriority::Balanced;
GridPosition scenario_sawmill_;
std::array<std::uint64_t, colony_player_slots> player_sequences_{};
std::uint64_t command_revision_ = 0;
};
} // namespace detail
class World : private detail::WorldState {
public:
// SerialReference uses one logical worker and executes on the calling thread.
World(std::uint64_t seed, std::int32_t width, std::int32_t height,
std::size_t workers = min_worker_count);
std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel,
WorkerPoolOptions worker_options = {});
void set_blocked(GridPosition position, bool blocked = true);
[[nodiscard]] bool is_walkable(GridPosition position) const noexcept;
@@ -370,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;
@@ -385,7 +431,12 @@ public:
void step(TickProfile* profile = nullptr);
void write_svg(const std::string& path) const;
void write_save(std::ostream& stream) const;
[[nodiscard]] static std::unique_ptr<World> read_save(std::istream& stream, std::size_t workers = min_worker_count);
// Called by the owner after every stage has drained. The independent copy
// can be retained by readers on other threads while the owner advances.
[[nodiscard]] std::shared_ptr<const World> capture() const;
[[nodiscard]] static std::unique_ptr<World> read_save(
std::istream& stream, std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel,
WorkerPoolOptions worker_options = {});
[[nodiscard]] std::uint64_t tick() const noexcept;
[[nodiscard]] std::uint64_t seed() const noexcept;
@@ -395,6 +446,8 @@ public:
[[nodiscard]] const std::vector<WorkJob>& jobs() const noexcept;
[[nodiscard]] const std::vector<ResourceNode>& resource_nodes() const noexcept;
[[nodiscard]] const std::vector<Storage>& storages() const noexcept;
[[nodiscard]] const Storage* find_storage(StorageId id) const noexcept;
[[nodiscard]] const ResourceNode* find_resource_node(ResourceNodeId id) const noexcept;
[[nodiscard]] const std::vector<ProductionOrder>& production_orders() const noexcept;
[[nodiscard]] const ProductionOrder* assigned_bed(AgentId agent) const noexcept;
[[nodiscard]] bool is_bed_cell(GridPosition position) const noexcept;
@@ -407,12 +460,16 @@ public:
private:
friend struct WorldSaveCodec;
struct CaptureTag {};
World(CaptureTag, const World& source);
struct PathResult {
std::vector<GridPosition> positions;
std::uint64_t nodes_visited = 0;
bool reachable = false;
};
[[nodiscard]] Storage& storage_by_id(StorageId id);
[[nodiscard]] ResourceNode& resource_node_by_id(ResourceNodeId id);
[[nodiscard]] std::size_t cell_index(GridPosition position) const noexcept;
[[nodiscard]] PathResult find_path(GridPosition start, GridPosition goal) const;
[[nodiscard]] PathResult assignment_path(GridPosition start, GridPosition goal);
@@ -434,40 +491,16 @@ private:
void grow_sites();
[[nodiscard]] bool can_reach_object_cell(GridPosition position) const;
std::uint64_t seed_;
std::uint64_t tick_ = 0;
std::uint64_t path_searches_ = 0;
std::uint64_t path_nodes_visited_ = 0;
std::uint64_t assignment_path_cache_hits_ = 0;
std::uint64_t jobs_completed_ = 0;
std::uint64_t meals_eaten_ = 0;
bool hunger_enabled_ = false;
std::int32_t width_;
std::int32_t height_;
std::size_t worker_count_;
ExecutionMode execution_mode_;
WorkerPoolOptions worker_options_;
std::unique_ptr<WorkerPool> worker_pool_;
AgentId next_agent_id_ = 1;
JobId next_job_id_ = 1;
std::uint64_t next_resource_node_id_ = 1;
std::uint64_t next_storage_id_ = 1;
std::vector<std::uint8_t> blocked_;
std::unordered_map<std::uint64_t, PathResult> assignment_path_cache_;
std::vector<Agent> agents_;
std::vector<WorkJob> jobs_;
std::vector<ResourceNode> resource_nodes_;
std::vector<Storage> storages_;
std::vector<ProductionOrder> production_orders_;
bool scenario_active_ = false;
bool staged_beds_ = false;
bool paused_ = false;
bool scenario_completed_ = false;
WorkPriority work_priority_ = WorkPriority::Balanced;
GridPosition scenario_sawmill_;
std::array<std::uint64_t, colony_player_slots> player_sequences_{};
std::uint64_t command_revision_ = 0;
};
inline constexpr std::int32_t first_colony_map_size = 32;
[[nodiscard]] std::unique_ptr<World> make_first_colony(std::size_t workers);
[[nodiscard]] std::unique_ptr<World> make_first_colony(
std::size_t workers, BedConstructionMode beds = BedConstructionMode::Staged,
ExecutionMode mode = ExecutionMode::Parallel);
} // namespace settlement
+281
View File
@@ -0,0 +1,281 @@
#include "settlement/core/checkpoint.hpp"
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <algorithm>
#include <array>
#include <new>
#include <spanstream>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <vector>
namespace settlement {
namespace {
constexpr std::size_t header_size = 24;
constexpr std::size_t digest_size = 32;
constexpr std::size_t fixed_metadata_size = 68;
constexpr std::size_t max_packages = 128;
constexpr std::size_t max_package_id_bytes = 128;
constexpr std::size_t max_version_bytes = 256;
struct InvalidCheckpoint {
CheckpointDiagnostic diagnostic;
};
[[noreturn]] void fail(CheckpointError code, std::string field, std::string message,
std::string package = {}) {
throw InvalidCheckpoint{{code, std::move(field), std::move(package), std::move(message)}};
}
std::span<const std::byte> wire_bytes(std::string_view text) {
return std::as_bytes(std::span{text.data(), text.size()});
}
RulesDigest digest(std::span<const std::byte> bytes) {
// The incremental API accepts the complete checkpoint size. Void's one-shot
// helper has a separate 16 MiB message limit.
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
if (!hasher || !hasher->update(bytes)) {
fail(CheckpointError::ResourceFailure, "sha256", "Could not hash the checkpoint.");
}
const auto result = hasher->finalize();
if (!result || result->size() != digest_size) {
fail(CheckpointError::ResourceFailure, "sha256", "Could not finalize the checkpoint hash.");
}
RulesDigest value{};
std::copy(result->begin(), result->end(), value.begin());
return value;
}
template<class T>
void put(Void::Binary::Writer& writer, T value) {
if (!writer.writeLittle(value)) {
fail(CheckpointError::InvalidFrame, "frame", "Could not encode the checkpoint field.");
}
}
void put_bytes(Void::Binary::Writer& writer, std::span<const std::byte> bytes) {
if (!writer.writeBytes(bytes)) {
fail(CheckpointError::InvalidFrame, "frame", "Could not encode checkpoint bytes.");
}
}
void put_text(Void::Binary::Writer& writer, std::string_view text) {
put(writer, static_cast<std::uint16_t>(text.size()));
put_bytes(writer, wire_bytes(text));
}
template<class T>
T get(Void::Binary::Reader& reader, std::string_view field) {
const auto result = reader.readLittle<T>();
if (!result) fail(CheckpointError::InvalidFrame, std::string(field), "Checkpoint field is incomplete.");
return *result;
}
std::span<const std::byte> get_bytes(Void::Binary::Reader& reader, std::size_t count,
std::string_view field) {
const auto result = reader.readBytes(count);
if (!result) fail(CheckpointError::InvalidFrame, std::string(field), "Checkpoint bytes are incomplete.");
return *result;
}
std::string get_text(Void::Binary::Reader& reader, std::size_t limit, std::string_view field) {
const auto count = get<std::uint16_t>(reader, field);
if (count == 0 || count > limit) {
fail(CheckpointError::LimitExceeded, std::string(field), "Package metadata length is invalid.");
}
const auto bytes = get_bytes(reader, count, field);
return {reinterpret_cast<const char*>(bytes.data()), bytes.size()};
}
void validate_identity(const Void::Uuid::Uuid& world_id, std::uint64_t city) {
if (world_id.is_nil()) fail(CheckpointError::InvalidIdentity, "world_id", "World UUID must be nonnil.");
if (city == 0) fail(CheckpointError::InvalidIdentity, "city", "City identity must be nonzero.");
}
RulesManifest validate_rules(std::span<const FrozenRulePackage> saved, const RulesDigest& fingerprint,
std::span<const RulePackage> installed) {
std::vector<std::string> selected;
selected.reserve(saved.size());
for (const auto& expected : saved) {
const auto found = std::find_if(installed.begin(), installed.end(), [&](const RulePackage& package) {
return package.identity().id == expected.id;
});
if (found == installed.end()) {
fail(CheckpointError::RulesMismatch, "rules.packages", "Required package is not installed.", expected.id);
}
if (found->identity().exact_version != expected.exact_version) {
fail(CheckpointError::RulesMismatch, "rules.version", "Installed package version differs from the checkpoint.", expected.id);
}
if (found->identity().content_sha256 != expected.content_sha256) {
fail(CheckpointError::RulesMismatch, "rules.sha256", "Installed package content differs from the checkpoint.", expected.id);
}
selected.push_back(expected.id);
}
auto resolved = resolve_rules(installed, selected);
if (!resolved) {
const auto& diagnostic = resolved.error();
fail(CheckpointError::RulesMismatch, "rules." + diagnostic.field,
diagnostic.message, diagnostic.package);
}
if (!std::ranges::equal(resolved->packages(), saved)) {
const auto added = std::find_if(resolved->packages().begin(), resolved->packages().end(),
[&](const FrozenRulePackage& package) {
return std::none_of(saved.begin(), saved.end(), [&](const FrozenRulePackage& expected) {
return expected.id == package.id;
});
});
fail(CheckpointError::RulesMismatch, "rules.packages", "Saved package set does not include its complete dependency closure.",
added == resolved->packages().end() ? std::string{} : added->id);
}
if (resolved->fingerprint() != fingerprint) {
fail(CheckpointError::RulesMismatch, "rules.fingerprint", "Rules fingerprint differs from the resolved packages.");
}
return std::move(*resolved);
}
} // namespace
std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city, const RulesManifest& rules) {
try {
validate_identity(world_id, city);
if (rules.packages().empty() || rules.packages().size() > max_packages) {
fail(CheckpointError::LimitExceeded, "rules.packages", "Checkpoint requires between 1 and 128 packages.");
}
std::size_t metadata_size = fixed_metadata_size;
std::string_view previous;
for (const auto& package : rules.packages()) {
if (package.id.empty() || package.id.size() > max_package_id_bytes ||
package.exact_version.empty() || package.exact_version.size() > max_version_bytes) {
fail(CheckpointError::LimitExceeded, "rules.packages", "Package metadata length is invalid.", package.id);
}
if (!previous.empty() && previous >= package.id) {
fail(CheckpointError::RulesMismatch, "rules.packages", "Package IDs must be unique and sorted.", package.id);
}
previous = package.id;
metadata_size += 4 + package.id.size() + package.exact_version.size() + digest_size;
}
if (metadata_size > max_checkpoint_metadata_bytes) {
fail(CheckpointError::LimitExceeded, "metadata_length", "Checkpoint metadata exceeds 64 KiB.");
}
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
auto body = std::move(stream).str();
if (body.size() > max_checkpoint_body_bytes) {
fail(CheckpointError::LimitExceeded, "body_length", "Checkpoint world exceeds 128 MiB.");
}
std::string bytes(header_size + metadata_size + body.size() + digest_size, '\0');
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}));
put_bytes(writer, wire_bytes(checkpoint_signature));
put(writer, checkpoint_version);
put(writer, static_cast<std::uint32_t>(metadata_size));
put(writer, static_cast<std::uint64_t>(body.size()));
put_bytes(writer, std::as_bytes(std::span{world_id.bytes}));
put(writer, city);
put(writer, world.tick());
put_bytes(writer, rules.fingerprint());
put(writer, static_cast<std::uint32_t>(rules.packages().size()));
for (const auto& package : rules.packages()) {
put_text(writer, package.id);
put_text(writer, package.exact_version);
put_bytes(writer, package.content_sha256);
}
put_bytes(writer, wire_bytes(body));
const auto checksum = digest(writer.written());
put_bytes(writer, checksum);
return bytes;
} catch (const InvalidCheckpoint& error) {
return std::unexpected{error.diagnostic};
} catch (const std::bad_alloc&) {
return std::unexpected{CheckpointDiagnostic{CheckpointError::ResourceFailure, "memory", {}, "Checkpoint allocation failed."}};
} catch (const std::exception& error) {
return std::unexpected{CheckpointDiagnostic{CheckpointError::InvalidWorld, "world", {}, error.what()}};
}
}
std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
std::string_view bytes, std::span<const RulePackage> installed, std::size_t workers, ExecutionMode mode) {
try {
if (bytes.size() > max_checkpoint_bytes) {
fail(CheckpointError::LimitExceeded, "frame", "Checkpoint exceeds its byte limit.");
}
if (bytes.size() < header_size + fixed_metadata_size + digest_size) {
fail(CheckpointError::InvalidFrame, "frame", "Checkpoint is incomplete.");
}
Void::Binary::Reader header(wire_bytes(bytes).first(header_size));
if (!std::ranges::equal(get_bytes(header, checkpoint_signature.size(), "magic"), wire_bytes(checkpoint_signature))) {
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
}
if (get<std::uint32_t>(header, "version") != checkpoint_version) {
fail(CheckpointError::UnsupportedVersion, "version", "Checkpoint schema is not supported.");
}
const auto metadata_size = get<std::uint32_t>(header, "metadata_length");
const auto body_size = get<std::uint64_t>(header, "body_length");
if (metadata_size < fixed_metadata_size || metadata_size > max_checkpoint_metadata_bytes ||
body_size == 0 || body_size > max_checkpoint_body_bytes) {
fail(CheckpointError::LimitExceeded, "lengths", "Checkpoint metadata or world length is invalid.");
}
if (bytes.size() != header_size + metadata_size + body_size + digest_size) {
fail(CheckpointError::InvalidFrame, "lengths", "Checkpoint lengths do not match its complete frame.");
}
const auto wire = wire_bytes(bytes);
const auto checksum = digest(wire.first(wire.size() - digest_size));
if (!std::ranges::equal(checksum, wire.last(digest_size))) {
fail(CheckpointError::IntegrityMismatch, "sha256", "Checkpoint integrity hash does not match.");
}
Void::Binary::Reader metadata(wire.subspan(header_size, metadata_size));
Void::Uuid::Uuid world_id;
const auto identity_bytes = get_bytes(metadata, world_id.bytes.size(), "world_id");
for (std::size_t i = 0; i < world_id.bytes.size(); ++i) {
world_id.bytes[i] = std::to_integer<std::uint8_t>(identity_bytes[i]);
}
const auto city = get<std::uint64_t>(metadata, "city");
validate_identity(world_id, city);
const auto tick = get<std::uint64_t>(metadata, "tick");
RulesDigest fingerprint{};
const auto fingerprint_bytes = get_bytes(metadata, fingerprint.size(), "rules.fingerprint");
std::copy(fingerprint_bytes.begin(), fingerprint_bytes.end(), fingerprint.begin());
const auto package_count = get<std::uint32_t>(metadata, "rules.packages");
if (package_count == 0 || package_count > max_packages) {
fail(CheckpointError::LimitExceeded, "rules.packages", "Checkpoint requires between 1 and 128 packages.");
}
std::vector<FrozenRulePackage> saved;
saved.reserve(package_count);
for (std::uint32_t i = 0; i < package_count; ++i) {
FrozenRulePackage package;
package.id = get_text(metadata, max_package_id_bytes, "rules.id");
package.exact_version = get_text(metadata, max_version_bytes, "rules.version");
const auto package_digest = get_bytes(metadata, digest_size, "rules.sha256");
std::copy(package_digest.begin(), package_digest.end(), package.content_sha256.begin());
if (!saved.empty() && saved.back().id >= package.id) {
fail(CheckpointError::RulesMismatch, "rules.packages", "Package IDs must be unique and sorted.", package.id);
}
saved.push_back(std::move(package));
}
if (!metadata.empty()) {
fail(CheckpointError::InvalidFrame, "metadata", "Checkpoint metadata contains trailing bytes.");
}
auto rules = validate_rules(saved, fingerprint, installed);
const auto body = bytes.substr(header_size + metadata_size, static_cast<std::size_t>(body_size));
std::ispanstream stream(std::span<const char>{body.data(), body.size()});
auto world = World::read_save(stream, workers, mode);
if (world->tick() != tick) {
fail(CheckpointError::InvalidWorld, "tick", "Checkpoint tick differs from its world state.");
}
return WorldCheckpoint{std::move(world), world_id, city, std::move(rules)};
} catch (const InvalidCheckpoint& error) {
return std::unexpected{error.diagnostic};
} catch (const std::bad_alloc&) {
return std::unexpected{CheckpointDiagnostic{CheckpointError::ResourceFailure, "memory", {}, "Checkpoint allocation failed."}};
} catch (const std::exception& error) {
return std::unexpected{CheckpointDiagnostic{CheckpointError::InvalidWorld, "world", {}, error.what()}};
}
}
} // namespace settlement
+248
View File
@@ -0,0 +1,248 @@
#include "settlement/core/checkpoint_files.hpp"
#include <Void/Async/FuturePool.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <algorithm>
#include <array>
#include <limits>
#include <mutex>
#include <spanstream>
#include <stdexcept>
#include <utility>
namespace settlement {
namespace {
constexpr std::string_view legacy_signature = "SETTLERS";
bool valid_path(const std::filesystem::path& path) {
return path.is_absolute() && !path.filename().empty() &&
path.native().find(L'\0') == std::wstring::npos;
}
std::vector<RulePackage> default_catalog() {
auto catalog = builtin_rule_packages();
if (!catalog) throw std::runtime_error(catalog.error().message);
return std::move(*catalog);
}
struct OpenFile {
HANDLE handle;
~OpenFile() { CloseHandle(handle); }
};
CheckpointFileDiagnostic diagnostic(CheckpointFileError code, std::string message,
std::uint32_t native_error = 0) {
return {code, std::move(message), native_error, std::nullopt};
}
// Void::FileSystem::read_file_bounded is unsupported on Windows at the pin.
// https://git.faumaray.com/Void/Library/issues/9 tracks this adapter's replacement.
// Reuse it after checkpoint-file tests prove one-handle reads, Unicode paths,
// initial/growing-file limits, EOF checking and independent bounded admission.
CheckpointLoadResult prepare(const std::filesystem::path& path,
std::span<const RulePackage> catalog,
const CheckpointFilesOptions& options,
std::size_t workers, ExecutionMode mode) {
try {
OpenFile file{CreateFileW(path.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr)};
if (file.handle == INVALID_HANDLE_VALUE) {
return std::unexpected{diagnostic(CheckpointFileError::Io,
"Could not open the checkpoint file.", GetLastError())};
}
LARGE_INTEGER size{};
if (GetFileType(file.handle) != FILE_TYPE_DISK || !GetFileSizeEx(file.handle, &size)) {
return std::unexpected{diagnostic(CheckpointFileError::Io,
"Could not determine the checkpoint file size.", GetLastError())};
}
if (size.QuadPart < 0 ||
static_cast<std::uint64_t>(size.QuadPart) > options.max_load_bytes) {
return std::unexpected{diagnostic(CheckpointFileError::TooLarge,
"Checkpoint file exceeds the configured byte limit.")};
}
if (options.read_observer) options.read_observer(CheckpointReadPhase::Opened);
std::string bytes;
bytes.reserve(static_cast<std::size_t>(size.QuadPart));
std::array<char, 65536> buffer;
for (;;) {
if (options.read_observer) options.read_observer(CheckpointReadPhase::BeforeRead);
DWORD count = 0;
if (!ReadFile(file.handle, buffer.data(), static_cast<DWORD>(buffer.size()), &count, nullptr)) {
return std::unexpected{diagnostic(CheckpointFileError::Io,
"Could not read the checkpoint file.", GetLastError())};
}
if (count == 0) break;
if (count > options.max_load_bytes - bytes.size()) {
return std::unexpected{diagnostic(CheckpointFileError::TooLarge,
"Checkpoint file grew beyond the configured byte limit.")};
}
bytes.append(buffer.data(), count);
}
if (bytes.starts_with(checkpoint_signature)) {
auto candidate = decode_checkpoint(bytes, catalog, workers, mode);
if (!candidate) {
CheckpointFileDiagnostic error{CheckpointFileError::InvalidCheckpoint,
candidate.error().message, 0, std::move(candidate.error())};
return std::unexpected{std::move(error)};
}
return std::move(*candidate);
}
if (!bytes.starts_with(legacy_signature)) {
return std::unexpected{diagnostic(CheckpointFileError::UnsupportedFormat,
"File has neither a checkpoint nor a legacy settlement signature.")};
}
auto defaults = default_rules_manifest();
if (!defaults) {
return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure,
defaults.error().message)};
}
std::vector<std::string> selected;
selected.reserve(defaults->packages().size());
for (const auto& package : defaults->packages()) selected.push_back(package.id);
auto installed_defaults = resolve_rules(catalog, selected);
if (!installed_defaults || *installed_defaults != *defaults) {
CheckpointDiagnostic detail{CheckpointError::RulesMismatch, "rules.packages", {},
"Legacy imports require the exact supported default packages."};
if (!installed_defaults) {
detail.package = installed_defaults.error().package;
detail.message = installed_defaults.error().message;
} else {
for (const auto& package : defaults->packages()) {
const auto found = std::find(installed_defaults->packages().begin(),
installed_defaults->packages().end(), package);
if (found == installed_defaults->packages().end()) {
detail.package = package.id;
break;
}
}
}
return std::unexpected{CheckpointFileDiagnostic{CheckpointFileError::InvalidCheckpoint,
detail.message, 0, std::move(detail)}};
}
std::unique_ptr<World> world;
try {
std::ispanstream input{std::span<const char>{bytes.data(), bytes.size()}};
world = World::read_save(input, workers, mode);
} catch (const std::bad_alloc&) {
throw;
} catch (const std::exception& error) {
return std::unexpected{diagnostic(CheckpointFileError::InvalidLegacy, error.what())};
}
const auto id = Void::Uuid::try_v4();
if (!id || id->is_nil()) {
return std::unexpected{diagnostic(CheckpointFileError::IdentityGeneration,
"Could not create an identity for the imported world.")};
}
return WorldCheckpoint{std::move(world), *id, 1, std::move(*installed_defaults)};
} catch (const std::bad_alloc&) {
return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure, "Out of memory.")};
} catch (const std::exception& error) {
return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, error.what())};
} catch (...) {
return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, "Checkpoint reader failed.")};
}
}
} // namespace
struct CheckpointFiles::Impl {
Impl(std::vector<RulePackage> catalog, CheckpointFilesOptions configured)
: options(std::move(configured)), installed(std::move(catalog)),
writer(SaveServiceOptions{.capacity = options.save_capacity,
.max_bytes = max_checkpoint_bytes, .fault_hook = {}}) {
if (options.load_capacity == 0 || options.max_load_bytes == 0 ||
options.max_load_bytes > max_checkpoint_bytes) {
throw std::invalid_argument("checkpoint reader limits are invalid");
}
auto created = Void::Async::ThreadExecutor::create(
{.workers = 1, .max_admitted = options.load_capacity});
if (!created) throw std::runtime_error("cannot create checkpoint reader");
executor = std::move(*created);
pool = std::make_unique<Void::Async::FuturePool>(*executor);
if (!executor->start()) throw std::runtime_error("cannot start checkpoint reader");
}
CheckpointFilesOptions options;
std::vector<RulePackage> installed;
SaveService writer;
std::unique_ptr<Void::Async::ThreadExecutor> executor;
std::unique_ptr<Void::Async::FuturePool> pool;
std::mutex admission_mutex;
bool closed = false;
std::uint64_t next_id = 1;
};
CheckpointFiles::CheckpointFiles(CheckpointFilesOptions options)
: CheckpointFiles(default_catalog(), std::move(options)) {}
CheckpointFiles::CheckpointFiles(std::vector<RulePackage> installed, CheckpointFilesOptions options)
: impl_(std::make_unique<Impl>(std::move(installed), std::move(options))) {}
CheckpointFiles::~CheckpointFiles() { shutdown(); }
SaveSubmission CheckpointFiles::try_save(
const std::filesystem::path& destination,
const std::shared_ptr<const PublishedSnapshot>& snapshot) {
std::unique_lock lock(impl_->admission_mutex, std::try_to_lock);
if (!lock.owns_lock()) return {SaveAdmission::Busy, 0, {}};
if (impl_->closed) return {SaveAdmission::Closed, 0, {}};
if (!snapshot || !snapshot->world || !snapshot->rules ||
snapshot->identity.world.is_nil() || snapshot->identity.city == 0) {
return {SaveAdmission::InvalidRequest, 0, {}};
}
return impl_->writer.try_submit(SaveRequest{destination, snapshot->world->tick(),
snapshot->identity.session, [snapshot] {
auto bytes = encode_checkpoint(*snapshot->world, snapshot->identity.world,
snapshot->identity.city, *snapshot->rules);
if (!bytes) throw std::runtime_error(bytes.error().message);
return std::move(*bytes);
}});
}
CheckpointLoadSubmission CheckpointFiles::try_load(
const std::filesystem::path& source, std::size_t workers, ExecutionMode mode) {
std::unique_lock lock(impl_->admission_mutex, std::try_to_lock);
if (!lock.owns_lock()) return {CheckpointLoadAdmission::Busy, 0, {}};
if (impl_->closed) return {CheckpointLoadAdmission::Closed, 0, {}};
if (impl_->executor->admitted() >= impl_->options.load_capacity) {
return {CheckpointLoadAdmission::Busy, 0, {}};
}
if (!valid_path(source) ||
(mode == ExecutionMode::Parallel && (workers < min_worker_count || workers > max_worker_count)) ||
(mode != ExecutionMode::Parallel && mode != ExecutionMode::SerialReference)) {
return {CheckpointLoadAdmission::InvalidRequest, 0, {}};
}
if (impl_->next_id == 0) return {CheckpointLoadAdmission::IdExhausted, 0, {}};
auto future = impl_->pool->try_submit(
[state = impl_.get(), source = std::filesystem::path(source), workers, mode] {
return prepare(source, state->installed, state->options, workers, mode);
});
if (!future) {
return {future.error() == Void::Async::AdmissionError::overloaded ?
CheckpointLoadAdmission::Busy : CheckpointLoadAdmission::Closed, 0, {}};
}
const auto id = impl_->next_id++;
return {CheckpointLoadAdmission::Accepted, id, std::move(*future)};
}
void CheckpointFiles::shutdown() {
if (impl_->executor->is_executor_thread()) {
throw std::logic_error("checkpoint reader cannot join itself");
}
{
std::lock_guard lock(impl_->admission_mutex);
impl_->closed = true;
}
static_cast<void>(impl_->executor->join());
impl_->writer.shutdown();
}
} // namespace settlement
+134
View File
@@ -0,0 +1,134 @@
#include "settlement/core/colony_profile.hpp"
#include <Void/Data/StrictJson.hpp>
#include <algorithm>
#include <array>
#include <exception>
#include <utility>
namespace settlement {
namespace {
RulesDiagnostic unsupported(std::string package, std::string message) {
return {std::move(package), "builtin/colony-profile", "profile", std::move(message), 0};
}
std::expected<RulesManifest, RulesDiagnostic> resolve_profile(
ColonyProfile profile, std::span<const RulePackage> catalog) {
if (profile != ColonyProfile::Default && profile != ColonyProfile::PlankBeds) {
return std::unexpected{unsupported({}, "Unknown colony profile.")};
}
const std::array selected{std::string{profile == ColonyProfile::Default ?
"settlement.colony" : "settlement.plankbeds"}};
return resolve_rules(catalog, selected);
}
std::expected<BedConstructionMode, RulesDiagnostic> plank_bed_mode(const RulePackage& package) {
namespace json = Void::Json::Strict;
const auto definitions = package.definitions();
if (definitions.size() != 1 || definitions.front().id != "settlement.plankbeds:bed" ||
definitions.front().kind != "recipe") {
return std::unexpected{unsupported(package.identity().id, "Plank-bed recipe is missing.")};
}
const auto parsed = json::parse(definitions.front().canonical_data,
{.maximumDepth = 4, .allowDecimals = false});
const auto* fields = parsed ? std::get_if<json::Value::Object>(&parsed->value) : nullptr;
if (!fields || fields->size() != 5) {
return std::unexpected{unsupported(package.identity().id, "Invalid plank-bed recipe data.")};
}
const auto matches = [&]<class T>(std::string_view key, const T& expected) {
const auto entry = fields->find(key);
if (entry == fields->end()) return false;
const auto* value = std::get_if<T>(&entry->second.value);
return value && *value == expected;
};
// This finite profile binds typed content to the already implemented recipe.
// General recipe-data execution is scheduled separately in S19-W02.
if (!matches("assembly", std::string{"plank"}) ||
!matches("input", std::string{"settlement.colony:board"}) ||
!matches("input_count", std::int64_t{1}) ||
!matches("saw_work_ticks", std::int64_t{12}) ||
!matches("work_ticks", std::int64_t{14})) {
return std::unexpected{unsupported(package.identity().id, "Plank-bed recipe is not implemented.")};
}
return BedConstructionMode::Plank;
}
CheckpointDiagnostic checkpoint_error(const RulesDiagnostic& error) {
return {CheckpointError::RulesMismatch, error.field, error.package, error.message};
}
} // namespace
ColonyRules::ColonyRules(ColonyProfile profile, BedConstructionMode beds, RulesManifest manifest)
: profile_(profile), bed_mode_(beds), manifest_(std::move(manifest)) {}
std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest& manifest) {
const auto catalog = builtin_rule_packages();
if (!catalog) return std::unexpected{catalog.error()};
for (const auto& identity : manifest.packages()) {
const auto installed = std::find_if(catalog->begin(), catalog->end(),
[&](const auto& package) { return package.identity().id == identity.id; });
if (installed == catalog->end() || installed->identity() != identity) {
return std::unexpected{unsupported(identity.id, "Package has no matching compiled colony implementation.")};
}
}
const auto default_manifest = resolve_profile(ColonyProfile::Default, *catalog);
if (!default_manifest) return std::unexpected{default_manifest.error()};
if (manifest == *default_manifest) {
return ColonyRules{ColonyProfile::Default, BedConstructionMode::Staged, manifest};
}
const auto plank_manifest = resolve_profile(ColonyProfile::PlankBeds, *catalog);
if (!plank_manifest) return std::unexpected{plank_manifest.error()};
if (manifest != *plank_manifest) {
return std::unexpected{unsupported({}, "Selected package closure is not an implemented colony profile.")};
}
const auto package = std::find_if(catalog->begin(), catalog->end(),
[](const auto& entry) { return entry.identity().id == "settlement.plankbeds"; });
const auto mode = plank_bed_mode(*package);
if (!mode) return std::unexpected{mode.error()};
return ColonyRules{ColonyProfile::PlankBeds, *mode, manifest};
}
std::expected<ColonyRules, RulesDiagnostic> colony_rules(ColonyProfile profile) {
const auto catalog = builtin_rule_packages();
if (!catalog) return std::unexpected{catalog.error()};
const auto manifest = resolve_profile(profile, *catalog);
if (!manifest) return std::unexpected{manifest.error()};
return compile_colony_rules(*manifest);
}
std::expected<WorldCheckpoint, CheckpointDiagnostic> make_colony_checkpoint(
ColonyProfile profile, std::size_t workers, ExecutionMode mode) {
const auto rules = colony_rules(profile);
if (!rules) return std::unexpected{checkpoint_error(rules.error())};
const auto world_id = Void::Uuid::try_v4();
if (!world_id) {
return std::unexpected{CheckpointDiagnostic{
CheckpointError::ResourceFailure, "world_id", {}, "Could not create a world identity."}};
}
try {
return WorldCheckpoint{make_first_colony(workers, rules->bed_mode(), mode),
*world_id, 1, rules->manifest()};
} catch (const std::exception& error) {
return std::unexpected{CheckpointDiagnostic{
CheckpointError::ResourceFailure, "world", {}, error.what()}};
}
}
std::expected<void, CheckpointDiagnostic> validate_colony_checkpoint(const WorldCheckpoint& candidate) {
if (!candidate.world || candidate.world_id.is_nil() || candidate.city == 0) {
return std::unexpected{CheckpointDiagnostic{
CheckpointError::InvalidIdentity, "world", {}, "A colony needs an owned world and nonzero identities."}};
}
const auto rules = compile_colony_rules(candidate.rules);
if (!rules) return std::unexpected{checkpoint_error(rules.error())};
if (rules->profile() == ColonyProfile::PlankBeds && candidate.world->staged_beds()) {
return std::unexpected{CheckpointDiagnostic{CheckpointError::RulesMismatch, "world.staged_beds",
"settlement.plankbeds", "Saved bed assembly does not match the selected plank-bed package."}};
}
return {};
}
} // namespace settlement
+113
View File
@@ -0,0 +1,113 @@
#include "settlement/core/command_dispatcher.hpp"
#include <limits>
#include <stdexcept>
namespace settlement {
namespace {
bool valid_client(TrustedClient client) noexcept {
return client.player >= colony_host && client.player <= colony_player_slots;
}
std::size_t client_index(TrustedClient client) noexcept {
return static_cast<std::size_t>(client.player - colony_host);
}
} // namespace
CommandDispatcher::CommandDispatcher(SessionIdentity identity, CommandDispatcherOptions options)
: identity_(identity), options_(options) {
if (identity.world.is_nil() || identity.session.is_nil() || identity.city == 0) {
throw std::invalid_argument("command dispatcher requires nonnil world/session and a city");
}
if (options.max_receipts_per_client == 0 ||
options.max_receipts_per_client >= std::numeric_limits<std::uint64_t>::max()) {
throw std::invalid_argument("receipt capacity must be positive and leave a next request number");
}
}
std::size_t CommandDispatcher::receipt_count(TrustedClient client) const noexcept {
return valid_client(client) ? records_[client_index(client)].size() : 0;
}
std::uint64_t CommandDispatcher::next_request(TrustedClient client) const noexcept {
if (!valid_client(client)) return 0;
return static_cast<std::uint64_t>(records_[client_index(client)].size()) + 1;
}
std::optional<DispatchStatus> CommandDispatcher::validate_context(
TrustedClient client, const CommandEnvelope& command) const noexcept {
if (!valid_client(client)) return DispatchStatus::UnauthorizedClient;
if (command.version != command_envelope_version) return DispatchStatus::UnsupportedVersion;
if (command.world.is_nil() || command.world != identity_.world) return DispatchStatus::WrongWorld;
if (command.session.is_nil() || command.session != identity_.session) return DispatchStatus::StaleSession;
if (command.request == 0) return DispatchStatus::InvalidRequest;
return std::nullopt;
}
std::optional<DispatchReceipt> CommandDispatcher::lookup(
TrustedClient client, const CommandEnvelope& command) const {
if (const auto invalid = validate_context(client, command)) return DispatchReceipt{*invalid};
const auto& records = records_[client_index(client)];
if (command.request > records.size()) return std::nullopt;
const auto& record = records[static_cast<std::size_t>(command.request - 1)];
if (command.city != record.city || command.payload != record.payload) {
return DispatchReceipt{DispatchStatus::Conflict};
}
return record.completed ? record.receipt : DispatchReceipt{DispatchStatus::Faulted};
}
CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const CommandEnvelope& command) {
if (command.city != identity_.city) return CommandStatus::Unauthorized;
if (const auto* payload = std::get_if<CommandPayload>(&command.payload)) {
if (payload->kind > CommandKind::CraftFurniture) return CommandStatus::InvalidTarget;
if (payload->kind == CommandKind::PlaceRoom) {
const auto inside = [&world](GridPosition cell) {
return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height();
};
// Legacy room-size arithmetic assumes coordinates belong to this map.
if (!inside(payload->cell) || !inside(payload->destination)) return CommandStatus::InvalidTarget;
}
return world.apply_command({client.player, world.next_command_sequence(client.player), payload->kind,
payload->cell, payload->value, payload->destination, payload->resident}).status;
}
if (client.player != colony_host) return CommandStatus::Unauthorized;
if (world.scenario_active()) return CommandStatus::Unavailable;
const auto& payload = std::get<LegacyCabinPayload>(command.payload);
try {
world.queue_cabin(payload.cell, payload.sawmill, payload.stonecutter);
} catch (const std::invalid_argument&) {
return CommandStatus::InvalidTarget;
}
return CommandStatus::Accepted;
}
DispatchReceipt CommandDispatcher::dispatch(World& world, TrustedClient client, const CommandEnvelope& command) {
if (const auto recorded = lookup(client, command)) return *recorded;
if (faulted_) return {DispatchStatus::Faulted};
auto& records = records_[client_index(client)];
if (command.request != next_request(client)) return {DispatchStatus::OutOfOrder};
if (records.size() == options_.max_receipts_per_client ||
revision_ == std::numeric_limits<std::uint64_t>::max()) return {DispatchStatus::Busy};
// All record allocation/copy work happens before the authoritative mutation.
// An exceptional effect leaves this entry incomplete and fences further work.
records.push_back(Record{command.city, command.payload});
auto& record = records.back();
try {
if (options_.mutation_observer) options_.mutation_observer(CommandMutationPhase::BeforeMutation);
const auto status = apply(world, client, command);
if (options_.mutation_observer) options_.mutation_observer(CommandMutationPhase::AfterMutation);
if (status == CommandStatus::Accepted) ++revision_;
record.receipt = {DispatchStatus::Completed, status, world.tick(), revision_};
record.completed = true;
} catch (...) {
faulted_ = true;
throw;
}
return record.receipt;
}
} // namespace settlement
+3 -3
View File
@@ -5,9 +5,9 @@
namespace settlement {
std::unique_ptr<World> make_first_colony(std::size_t workers) {
std::unique_ptr<World> make_first_colony(std::size_t workers, BedConstructionMode beds, ExecutionMode mode) {
constexpr auto size = first_colony_map_size;
auto world = std::make_unique<World>(2026, size, size, workers);
auto world = std::make_unique<World>(2026, size, size, workers, mode);
DeterministicRng terrain_rng(0x534554544C454D45ULL);
for (int y = 2; y < size - 2; ++y) {
for (int x = 2; x < size - 2; ++x) {
@@ -28,7 +28,7 @@ std::unique_ptr<World> make_first_colony(std::size_t workers) {
for (const auto position : {GridPosition{13, 14}, {14, 12}, {18, 12}, {19, 14}}) {
static_cast<void>(world->add_resource_node(position, ItemType::Berries, 16));
}
world->start_scenario({15, 14});
world->start_scenario({15, 14}, beds);
return world;
}
+402
View File
@@ -0,0 +1,402 @@
#include "settlement/core/rules_manifest.hpp"
#include <Void/Algorithms/Graph.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Text/Semver.hpp>
#include <algorithm>
#include <map>
#include <set>
#include <utility>
#include <variant>
namespace settlement {
namespace json = Void::Json::Strict;
struct RuleDependency {
std::string id;
std::string range;
};
struct RulePackageData {
FrozenRulePackage identity;
std::string source;
std::string canonical_json;
std::vector<RuleDependency> dependencies;
std::vector<std::string> capabilities;
std::vector<RuleDefinition> definitions;
};
namespace {
struct InvalidRules {
RulesDiagnostic diagnostic;
};
struct Context {
std::string package;
std::string source;
[[noreturn]] void fail(std::string field, std::string message, std::size_t offset = 0) const {
throw InvalidRules{{package, source, std::move(field), std::move(message), offset}};
}
};
bool local_name(std::string_view text) {
if (text.empty() || text.size() > 128 || text.front() < 'a' || text.front() > 'z') return false;
return std::all_of(text.begin(), text.end(), [](char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-';
});
}
bool package_id(std::string_view text) {
if (text.size() > 128 || text.find('.') == std::string_view::npos) return false;
for (;;) {
const auto separator = text.find('.');
if (!local_name(text.substr(0, separator))) return false;
if (separator == std::string_view::npos) return true;
text.remove_prefix(separator + 1);
}
}
bool qualified_id(std::string_view text) {
const auto separator = text.find(':');
return separator != std::string_view::npos && package_id(text.substr(0, separator)) &&
local_name(text.substr(separator + 1));
}
void input_budget(std::string_view text, const RulesLimits& limits, const Context& context) {
if (text.size() > limits.package_bytes) context.fail("$", "package byte limit exceeded");
if (limits.json_depth == 0 || limits.json_depth > 64) context.fail("$", "JSON depth limit must be 1..64");
// Count lexical nodes (including object keys) before the JSON parser allocates.
std::size_t nodes = 0;
bool in_string = false;
bool escaped = false;
bool scalar = false;
for (char ch : text) {
if (in_string) {
if (escaped) escaped = false;
else if (ch == '\\') escaped = true;
else if (ch == '"') in_string = false;
continue;
}
if (ch == '"') {
in_string = true;
scalar = false;
++nodes;
} else if (ch == '{' || ch == '[') {
scalar = false;
++nodes;
} else if (ch == '}' || ch == ']' || ch == ',' || ch == ':' ||
ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t') {
scalar = false;
} else if (!scalar) {
scalar = true;
++nodes;
}
if (nodes > limits.json_nodes) context.fail("$", "JSON node limit exceeded");
}
}
template <class T>
const T& as(const json::Value& value, const Context& context, std::string_view field) {
const auto* result = std::get_if<T>(&value.value);
if (!result) context.fail(std::string(field), "unexpected JSON type");
return *result;
}
const json::Value::Object& object(const json::Value& value, const Context& context,
std::string_view field, std::initializer_list<std::string_view> names) {
const auto& result = as<json::Value::Object>(value, context, field);
for (const auto& [key, ignored] : result) {
static_cast<void>(ignored);
if (std::find(names.begin(), names.end(), key) == names.end()) {
context.fail(std::string(field) + "." + key, "unknown field");
}
}
for (auto key : names) {
if (!result.contains(key)) context.fail(std::string(field) + "." + std::string(key), "required field is missing");
}
return result;
}
std::string text(const json::Value& value, const Context& context, const std::string& field) {
const auto& result = as<std::string>(value, context, field);
if (result.size() > 256) context.fail(field, "metadata string limit exceeded");
return result;
}
std::vector<std::string> id_set(const json::Value& value, const Context& context,
const std::string& field, std::size_t maximum) {
const auto& entries = as<json::Value::Array>(value, context, field);
if (entries.size() > maximum) context.fail(field, "entry limit exceeded");
std::vector<std::string> result;
for (const auto& entry : entries) {
auto id = text(entry, context, field);
if (!qualified_id(id)) context.fail(field, "expected a package:local-name identifier");
result.push_back(std::move(id));
}
std::sort(result.begin(), result.end());
if (std::adjacent_find(result.begin(), result.end()) != result.end()) context.fail(field, "duplicate identifier");
return result;
}
json::Value string_array(const std::vector<std::string>& values) {
json::Value::Array result;
for (const auto& value : values) result.push_back(json::Value{value});
return json::Value{std::move(result)};
}
std::string serialize(const json::Value& value, const Context& context, std::size_t depth) {
auto result = json::serialize(value, depth);
if (!result) context.fail("$", result.error().message, result.error().offset);
return std::move(*result);
}
RulesDigest digest(std::string_view bytes, const Context& context) {
auto result = Void::Crypto::sha256(bytes);
if (!result || result->size() != 32) context.fail("sha256", "SHA-256 computation failed");
RulesDigest output{};
std::copy(result->begin(), result->end(), output.begin());
return output;
}
std::shared_ptr<const RulePackageData> parse_package(std::string_view source, std::string_view bytes,
const RulesLimits& limits) {
Context context{"", std::string(source)};
input_budget(bytes, limits, context);
auto parsed = json::parse(bytes, json::ParseOptions{limits.json_depth, false});
if (!parsed) context.fail("$", parsed.error().message, parsed.error().offset);
const auto& root = object(*parsed, context, "$",
{"schema", "id", "version", "dependencies", "exclusive_capabilities", "definitions"});
auto result = std::make_shared<RulePackageData>();
result->source = source;
context.package = text(root.at("id"), context, "id");
if (!package_id(context.package)) context.fail("id", "expected a lower-case dot-separated package ID");
result->identity.id = context.package;
if (as<std::int64_t>(root.at("schema"), context, "schema") != 1) context.fail("schema", "unsupported package schema");
const auto version = Void::Semver::parse_strict(text(root.at("version"), context, "version"));
if (!version) context.fail("version", "invalid strict SemVer");
result->identity.exact_version = version->to_string();
const auto& dependencies = as<json::Value::Array>(root.at("dependencies"), context, "dependencies");
if (dependencies.size() > limits.dependencies) context.fail("dependencies", "dependency limit exceeded");
for (std::size_t i = 0; i < dependencies.size(); ++i) {
const auto field = "dependencies[" + std::to_string(i) + "]";
const auto& dep = object(dependencies[i], context, field, {"id", "version"});
auto id = text(dep.at("id"), context, field + ".id");
auto range = text(dep.at("version"), context, field + ".version");
if (!package_id(id)) context.fail(field + ".id", "invalid dependency package ID");
if (range.empty() || !Void::Semver::VersionRange::parse(range)) context.fail(field + ".version", "invalid version range");
result->dependencies.push_back({std::move(id), std::move(range)});
}
std::sort(result->dependencies.begin(), result->dependencies.end(), [](const auto& a, const auto& b) { return a.id < b.id; });
if (std::adjacent_find(result->dependencies.begin(), result->dependencies.end(),
[](const auto& a, const auto& b) { return a.id == b.id; }) != result->dependencies.end()) {
context.fail("dependencies", "duplicate dependency package ID");
}
result->capabilities = id_set(root.at("exclusive_capabilities"), context, "exclusive_capabilities", limits.definitions);
const auto& definitions = as<json::Value::Array>(root.at("definitions"), context, "definitions");
if (definitions.size() > limits.definitions) context.fail("definitions", "definition limit exceeded");
std::map<std::string, json::Value> canonical_definitions;
for (std::size_t i = 0; i < definitions.size(); ++i) {
const auto field = "definitions[" + std::to_string(i) + "]";
const auto& entry = object(definitions[i], context, field, {"id", "kind", "data", "references"});
RuleDefinition definition;
definition.id = text(entry.at("id"), context, field + ".id");
if (!qualified_id(definition.id) || !definition.id.starts_with(context.package + ":")) {
context.fail(field + ".id", "definition must belong to its package namespace");
}
definition.kind = text(entry.at("kind"), context, field + ".kind");
constexpr std::string_view kinds[]{"item", "profession", "recipe", "material", "event"};
if (std::find(std::begin(kinds), std::end(kinds), definition.kind) == std::end(kinds)) context.fail(field + ".kind", "unknown definition kind");
definition.references = id_set(entry.at("references"), context, field + ".references", limits.references);
definition.canonical_data = serialize(entry.at("data"), context, limits.json_depth);
auto canonical = entry;
canonical.at("references") = string_array(definition.references);
if (!canonical_definitions.emplace(definition.id, json::Value{std::move(canonical)}).second) {
context.fail(field + ".id", "duplicate definition ID");
}
result->definitions.push_back(std::move(definition));
}
std::sort(result->definitions.begin(), result->definitions.end(), [](const auto& a, const auto& b) { return a.id < b.id; });
json::Value::Array canonical_dependencies;
for (const auto& dep : result->dependencies) canonical_dependencies.push_back(json::Value{json::Value::Object{
{"id", json::Value{dep.id}}, {"version", json::Value{dep.range}}}});
json::Value::Array canonical_definition_array;
for (auto& [id, value] : canonical_definitions) {
static_cast<void>(id);
canonical_definition_array.push_back(std::move(value));
}
auto canonical = root;
canonical.at("version") = json::Value{result->identity.exact_version};
canonical.at("dependencies") = json::Value{std::move(canonical_dependencies)};
canonical.at("exclusive_capabilities") = string_array(result->capabilities);
canonical.at("definitions") = json::Value{std::move(canonical_definition_array)};
result->canonical_json = serialize(json::Value{std::move(canonical)}, context, limits.json_depth);
result->identity.content_sha256 = digest(result->canonical_json, context);
return result;
}
} // namespace
RulePackage::RulePackage(std::shared_ptr<const RulePackageData> data) : data_(std::move(data)) {}
const FrozenRulePackage& RulePackage::identity() const noexcept { return data_->identity; }
std::span<const RuleDefinition> RulePackage::definitions() const noexcept { return data_->definitions; }
std::string_view RulePackage::canonical_json() const noexcept { return data_->canonical_json; }
RulesManifest::RulesManifest(std::vector<FrozenRulePackage> packages, RulesDigest fingerprint, std::string bytes)
: packages_(std::move(packages)), fingerprint_(fingerprint), canonical_json_(std::move(bytes)) {}
std::expected<RulePackage, RulesDiagnostic> load_rule_package(std::string_view source, std::string_view bytes,
const RulesLimits& limits) {
try {
return RulePackage{parse_package(source, bytes, limits)};
} catch (const InvalidRules& error) {
return std::unexpected{error.diagnostic};
}
}
std::string rules_digest_hex(const RulesDigest& hash) {
constexpr char alphabet[] = "0123456789abcdef";
std::string result;
result.reserve(hash.size() * 2);
for (auto byte : hash) {
const auto value = std::to_integer<unsigned int>(byte);
result.push_back(alphabet[value >> 4]);
result.push_back(alphabet[value & 15]);
}
return result;
}
std::expected<RulesManifest, RulesDiagnostic> resolve_rules(std::span<const RulePackage> available,
std::span<const std::string> selected,
const RulesLimits& limits) {
try {
Context context{"", "catalog"};
if (available.size() > limits.packages || selected.size() > limits.packages) context.fail("packages", "package count limit exceeded");
std::map<std::string, const RulePackageData*> catalog;
std::size_t byte_count = 0;
for (const auto& package : available) {
const auto& data = *package.data_;
context = {data.identity.id, data.source};
// Revalidate limits at the resolver boundary, including callers using a
// package parsed with more permissive limits.
if (data.canonical_json.size() > limits.catalog_bytes - std::min(byte_count, limits.catalog_bytes)) {
context.fail("packages", "catalog byte limit exceeded");
}
static_cast<void>(parse_package(data.source, data.canonical_json, limits));
byte_count += data.canonical_json.size();
if (!catalog.emplace(data.identity.id, &data).second) context.fail("id", "duplicate installed package ID");
}
std::set<std::string> chosen;
std::vector<std::string> pending(selected.begin(), selected.end());
std::sort(pending.begin(), pending.end());
if (pending.empty()) context.fail("selected", "select at least one package");
if (std::adjacent_find(pending.begin(), pending.end()) != pending.end()) context.fail("selected", "duplicate selected package ID");
for (std::size_t i = 0; i < pending.size(); ++i) {
const auto id = pending[i];
context = {id, "selection"};
if (!package_id(id)) context.fail("selected", "invalid selected package ID");
if (chosen.contains(id)) continue;
const auto found = catalog.find(id);
if (found == catalog.end()) context.fail("selected", "package is not installed: " + id);
const auto& package = *found->second;
context = {id, package.source};
chosen.insert(id);
for (const auto& dep : package.dependencies) {
const auto dependency = catalog.find(dep.id);
if (dependency == catalog.end()) context.fail("dependencies." + dep.id, "required package is not installed");
const auto version = Void::Semver::parse_strict(dependency->second->identity.exact_version);
const auto range = Void::Semver::VersionRange::parse(dep.range);
const bool prerelease_allowed = version->pre_release.empty() || dep.range == version->to_string() || dep.range == "=" + version->to_string();
if (!prerelease_allowed || !range->contains(*version)) context.fail("dependencies." + dep.id, "installed version does not satisfy the constraint");
if (!chosen.contains(dep.id)) pending.push_back(dep.id);
}
}
std::vector<const RulePackageData*> packages;
std::map<std::string, std::size_t> indices;
for (const auto& id : chosen) {
indices.emplace(id, packages.size());
packages.push_back(catalog.at(id));
}
std::vector<std::vector<std::size_t>> edges(packages.size());
for (std::size_t i = 0; i < packages.size(); ++i) {
for (const auto& dep : packages[i]->dependencies) edges[indices.at(dep.id)].push_back(i);
}
Void::Algorithms::WorkLimits graph_limits;
graph_limits.max_vertices = limits.packages;
const auto topology = Void::Algorithms::topological_order(Void::Algorithms::AdjacencyView{edges}, graph_limits);
if (!topology) {
std::string message = topology.error().message;
for (auto index : topology.error().cycle) message += " " + packages.at(index)->identity.id;
context.fail("dependencies", message);
}
std::map<std::string, std::string> providers;
std::set<std::string> definition_ids;
for (const auto* package : packages) {
context = {package->identity.id, package->source};
for (const auto& capability : package->capabilities) {
auto [provider, inserted] = providers.emplace(capability, package->identity.id);
if (!inserted) context.fail("exclusive_capabilities", "conflicting provider for " + capability + ": " + provider->second);
}
for (const auto& definition : package->definitions) definition_ids.insert(definition.id);
}
for (const auto* package : packages) {
context = {package->identity.id, package->source};
std::set<std::string> accessible{package->identity.id};
std::vector<std::string> dependencies{package->identity.id};
for (std::size_t i = 0; i < dependencies.size(); ++i) {
for (const auto& dep : catalog.at(dependencies[i])->dependencies) {
if (accessible.insert(dep.id).second) dependencies.push_back(dep.id);
}
}
for (const auto& definition : package->definitions) {
for (const auto& reference : definition.references) {
const auto owner = reference.substr(0, reference.find(':'));
if (!accessible.contains(owner) || !definition_ids.contains(reference)) {
context.fail("definitions." + definition.id + ".references", "unresolved or undeclared reference: " + reference);
}
}
}
}
std::vector<FrozenRulePackage> frozen;
json::Value::Array array;
for (const auto* package : packages) {
frozen.push_back(package->identity);
array.push_back(json::Value{json::Value::Object{
{"id", json::Value{package->identity.id}},
{"version", json::Value{package->identity.exact_version}},
{"sha256", json::Value{rules_digest_hex(package->identity.content_sha256)}}}});
}
auto canonical = serialize(json::Value{json::Value::Object{
{"schema", json::Value{std::int64_t{1}}}, {"packages", json::Value{std::move(array)}}}}, context, 8);
const auto fingerprint = digest(canonical, context);
return RulesManifest{std::move(frozen), fingerprint, std::move(canonical)};
} catch (const InvalidRules& error) {
return std::unexpected{error.diagnostic};
}
}
std::expected<std::vector<RulePackage>, RulesDiagnostic> builtin_rule_packages() {
constexpr std::string_view core = R"({"schema":1,"id":"settlement.core","version":"1.0.0","dependencies":[],"exclusive_capabilities":["settlement.core:materials"],"definitions":[{"id":"settlement.core:wood","kind":"item","data":{"stack_limit":64},"references":[]},{"id":"settlement.core:stone","kind":"item","data":{"stack_limit":64},"references":[]}]})";
constexpr std::string_view colony = R"({"schema":1,"id":"settlement.colony","version":"1.0.0","dependencies":[{"id":"settlement.core","version":"1.0.0"}],"exclusive_capabilities":["settlement.colony:construction"],"definitions":[{"id":"settlement.colony:board","kind":"recipe","data":{"output_count":1,"work_ticks":8},"references":["settlement.core:wood"]}]})";
auto first = load_rule_package("builtin/core", core);
if (!first) return std::unexpected{first.error()};
auto second = load_rule_package("builtin/colony", colony);
if (!second) return std::unexpected{second.error()};
constexpr std::string_view plankbeds = R"({"schema":1,"id":"settlement.plankbeds","version":"1.0.0","dependencies":[{"id":"settlement.colony","version":"1.0.0"}],"exclusive_capabilities":[],"definitions":[{"id":"settlement.plankbeds:bed","kind":"recipe","data":{"assembly":"plank","input":"settlement.colony:board","input_count":1,"saw_work_ticks":12,"work_ticks":14},"references":["settlement.colony:board"]}]})";
auto third = load_rule_package("builtin/plankbeds", plankbeds);
if (!third) return std::unexpected{third.error()};
return std::vector<RulePackage>{std::move(*first), std::move(*second), std::move(*third)};
}
std::expected<RulesManifest, RulesDiagnostic> default_rules_manifest() {
auto packages = builtin_rule_packages();
if (!packages) return std::unexpected{packages.error()};
const std::array selected{std::string{"settlement.colony"}};
return resolve_rules(*packages, selected);
}
} // namespace settlement
+221
View File
@@ -0,0 +1,221 @@
#include "settlement/core/save_service.hpp"
#include <Void/Async/FuturePool.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <algorithm>
#include <limits>
#include <mutex>
#include <stdexcept>
#include <utility>
namespace settlement {
namespace {
// CREATE_NEW establishes ownership. No cleanup ever scans by filename prefix.
struct StagingFile {
HANDLE handle{INVALID_HANDLE_VALUE};
std::filesystem::path path;
bool owned{false};
void cleanup(SaveResult& result) noexcept {
if (handle != INVALID_HANDLE_VALUE) {
if (!CloseHandle(handle)) result.cleanup_error = GetLastError();
handle = INVALID_HANDLE_VALUE;
}
if (owned && !DeleteFileW(path.c_str())) {
result.cleanup_error = GetLastError();
// Moving a path is noexcept, including during allocation failure.
result.retained_staging_file = std::move(path);
}
owned = false;
}
};
bool valid_request(const SaveRequest& request) {
const auto& path = request.destination;
if (!request.produce || request.session.is_nil() || !path.is_absolute() ||
path.native().find(L'\0') != std::wstring::npos) return false;
const auto filename = path.filename();
return !filename.empty() && filename != L"." && filename != L".." &&
filename.native().find(L':') == std::wstring::npos;
}
SaveResult publish(const SaveRequest& request, std::uint64_t id,
const SaveServiceOptions& options) noexcept {
SaveResult result;
result.request_id = id;
result.tick = request.tick;
result.session = request.session;
StagingFile staging;
const auto phase = [&](SavePhase next) {
result.phase = next;
if (options.fault_hook) {
result.native_error = options.fault_hook(next);
if (result.native_error != 0) {
result.error = SaveError::Injected;
return false;
}
}
return true;
};
const auto io_error = [&] {
result.error = SaveError::Io;
result.native_error = GetLastError();
};
try {
// A single exit after this body performs cleanup before returning the
// result, including when path allocation or the producer throws.
[&] {
if (!phase(SavePhase::Materialize)) return;
std::string bytes;
try {
bytes = request.produce();
} catch (...) {
result.error = SaveError::ProducerFailed;
return;
}
if (bytes.size() > options.max_bytes) {
result.error = SaveError::TooLarge;
return;
}
if (!phase(SavePhase::CreateStage)) return;
for (int attempt = 0; attempt < 16; ++attempt) {
const auto uuid = Void::Uuid::try_v4();
if (!uuid) {
result.error = SaveError::Internal;
return;
}
const auto name = uuid->to_string();
staging.path = request.destination.parent_path() /
(L".settlement-save-" + std::wstring(name.begin(), name.end()) + L".tmp");
staging.handle = CreateFileW(staging.path.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
if (staging.handle != INVALID_HANDLE_VALUE) {
staging.owned = true;
break;
}
const auto error = GetLastError();
if (error != ERROR_FILE_EXISTS && error != ERROR_ALREADY_EXISTS) {
result.error = SaveError::Io;
result.native_error = error;
return;
}
}
if (!staging.owned) {
result.error = SaveError::Io;
result.native_error = ERROR_FILE_EXISTS;
return;
}
std::size_t offset = 0;
while (offset < bytes.size()) {
if (!phase(SavePhase::WriteStage)) return;
const auto count = static_cast<DWORD>(std::min<std::size_t>(bytes.size() - offset, 65536));
DWORD written = 0;
if (!WriteFile(staging.handle, bytes.data() + offset, count, &written, nullptr)) {
io_error();
return;
}
if (written == 0 || written > count) {
result.error = SaveError::Io;
result.native_error = ERROR_WRITE_FAULT;
return;
}
offset += written; // Includes short successful writes.
}
if (!phase(SavePhase::FlushStage)) return;
if (!FlushFileBuffers(staging.handle)) {
io_error();
return;
}
if (!phase(SavePhase::CloseStage)) return;
if (!CloseHandle(staging.handle)) {
io_error();
return;
}
staging.handle = INVALID_HANDLE_VALUE;
if (!phase(SavePhase::Publish)) return;
// Same-directory rename, no MOVEFILE_COPY_ALLOWED fallback. This
// publishes complete flushed bytes; WRITE_THROUGH alone does not
// establish power-loss durability of directory metadata.
if (!MoveFileExW(staging.path.c_str(), request.destination.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
io_error();
return;
}
staging.owned = false;
result.visible_on_disk = true;
static_cast<void>(phase(SavePhase::Published));
}();
} catch (...) {
result.error = SaveError::Internal;
}
result.durability_unknown = result.visible_on_disk && result.error != SaveError::None;
staging.cleanup(result);
return result;
}
} // namespace
struct SaveService::Impl {
explicit Impl(SaveServiceOptions configured) : options(std::move(configured)) {
if (options.capacity == 0 || options.max_bytes == 0) {
throw std::invalid_argument("save service limits must be positive");
}
auto created = Void::Async::ThreadExecutor::create({.workers = 1, .max_admitted = options.capacity});
if (!created) throw std::runtime_error("cannot create save writer");
executor = std::move(*created);
pool = std::make_unique<Void::Async::FuturePool>(*executor);
if (!executor->start()) throw std::runtime_error("cannot start save writer");
}
SaveServiceOptions options;
std::unique_ptr<Void::Async::ThreadExecutor> executor;
std::unique_ptr<Void::Async::FuturePool> pool;
std::mutex admission_mutex;
bool closed{false};
std::uint64_t next_id{1};
};
SaveService::SaveService(SaveServiceOptions options) : impl_(std::make_unique<Impl>(std::move(options))) {}
SaveService::~SaveService() { shutdown(); }
SaveSubmission SaveService::try_submit(const SaveRequest& request) {
std::unique_lock lock(impl_->admission_mutex, std::try_to_lock);
if (!lock.owns_lock()) return {SaveAdmission::Busy, 0, {}};
if (impl_->closed) return {SaveAdmission::Closed, 0, {}};
if (impl_->executor->admitted() >= impl_->options.capacity) return {SaveAdmission::Busy, 0, {}};
if (!valid_request(request)) return {SaveAdmission::InvalidRequest, 0, {}};
if (impl_->next_id == 0) return {SaveAdmission::IdExhausted, 0, {}};
const auto id = impl_->next_id;
auto submitted = impl_->pool->try_submit([state = impl_.get(), request = SaveRequest(request), id]() mutable {
auto result = publish(request, id, state->options);
request.produce = {}; // Release snapshot even if the caller keeps its future.
return result;
});
if (!submitted) {
return {submitted.error() == Void::Async::AdmissionError::overloaded ?
SaveAdmission::Busy : SaveAdmission::Closed, 0, {}};
}
++impl_->next_id; // Unsigned wrap to zero permanently exhausts identities.
return {SaveAdmission::Accepted, id, std::move(*submitted)};
}
void SaveService::shutdown() {
if (impl_->executor->is_executor_thread()) {
throw std::logic_error("save writer cannot join itself");
}
{
std::lock_guard lock(impl_->admission_mutex);
impl_->closed = true;
}
static_cast<void>(impl_->executor->join());
}
} // namespace settlement
+372
View File
@@ -0,0 +1,372 @@
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Async/FuturePool.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <limits>
#include <mutex>
#include <stdexcept>
#include <utility>
namespace settlement {
namespace {
using Clock = Void::Time::MonotonicClock;
constexpr auto tick_interval = std::chrono::milliseconds(50);
SessionIdentity new_identity(const WorldCheckpoint& checkpoint) {
if (!checkpoint.world || checkpoint.world_id.is_nil() || checkpoint.city == 0) {
throw std::invalid_argument("runtime requires a world, nonnil identity and a city");
}
const auto session = Void::Uuid::try_v4();
if (!session) throw std::runtime_error("cannot generate a simulation session UUID");
return {checkpoint.world_id, *session, checkpoint.city};
}
std::shared_ptr<const PublishedSnapshot> capture(
const World& world, const CommandDispatcher& dispatcher,
std::shared_ptr<const RulesManifest> rules, std::uint64_t revision) {
std::array<std::uint64_t, colony_player_slots> next{};
for (std::size_t i = 0; i < next.size(); ++i) {
next[i] = dispatcher.next_request({static_cast<std::uint8_t>(i + colony_host)});
}
return std::make_shared<const PublishedSnapshot>(
dispatcher.identity(), revision, world.capture(), std::move(rules), next);
}
} // namespace
struct SimulationRuntime::Impl {
enum class Kind { Command, Ticking, Fence, Install };
struct Work {
Kind kind;
TrustedClient client{};
CommandEnvelope command{};
bool enabled = false;
Clock::time_point deadline{};
LoadTicket ticket{};
std::optional<WorldCheckpoint> candidate;
std::promise<RuntimeResult> promise;
explicit Work(Kind value) : kind(value) {}
};
RuntimeOptions options;
std::shared_ptr<const Clock> clock;
std::unique_ptr<World> world;
mutable std::mutex mutex;
std::condition_variable changed;
std::deque<std::unique_ptr<Work>> queue;
std::size_t outstanding = 0;
std::uint64_t latest_load = 0;
RuntimeState state = RuntimeState::Running;
std::exception_ptr failure;
std::shared_ptr<const PublishedSnapshot> published;
std::shared_ptr<const CommandDispatcher> committed;
std::atomic<bool> stopping{false};
bool owner_faulted = false;
bool ticking;
Clock::time_point next_tick;
std::unique_ptr<Void::Async::ThreadExecutor> executor;
std::unique_ptr<Void::Async::FuturePool> futures;
std::future<void> owner_done;
Impl(WorldCheckpoint initial, RuntimeOptions settings)
: options(std::move(settings)),
clock(options.clock ? options.clock : std::make_shared<Void::Time::SystemMonotonicClock>()),
ticking(options.ticking) {
if (options.capacity == 0) throw std::invalid_argument("runtime capacity must be positive");
auto dispatcher = std::make_shared<CommandDispatcher>(new_identity(initial), options.dispatcher);
auto rules = std::make_shared<const RulesManifest>(std::move(initial.rules));
published = capture(*initial.world, *dispatcher, std::move(rules), 0);
committed = std::move(dispatcher);
world = std::move(initial.world);
reanchor();
auto created = Void::Async::ThreadExecutor::create({.workers = 1, .max_admitted = 1});
if (!created) throw std::runtime_error(created.error().message());
executor = std::move(*created);
futures = std::make_unique<Void::Async::FuturePool>(*executor);
const auto started = executor->start();
if (!started) throw std::runtime_error(started.error().message());
auto submitted = futures->try_submit([this] { run(); });
if (!submitted) throw std::runtime_error("cannot start simulation owner");
owner_done = std::move(*submitted);
}
~Impl() { shutdown(); }
void reanchor() { next_tick = Void::Time::saturating_add(clock->now(), tick_interval); }
bool advancing() const { return !owner_faulted && ticking && world && !world->paused(); }
void observe(RuntimePhase phase) const { if (options.observer) options.observer(phase); }
std::uint64_t next_revision() const {
if (published->revision == std::numeric_limits<std::uint64_t>::max()) {
throw std::overflow_error("publication revision exhausted");
}
return published->revision + 1;
}
RuntimeSubmission enqueue(std::unique_ptr<Work> work, WorldCheckpoint* candidate = 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 (outstanding == options.capacity) return {RuntimeAdmission::Busy, {}};
queue.push_back(std::move(work));
if (candidate) {
static_assert(std::is_nothrow_move_constructible_v<WorldCheckpoint>);
queue.back()->candidate.emplace(std::move(*candidate));
}
++outstanding;
lock.unlock();
changed.notify_one();
return {RuntimeAdmission::Accepted, std::move(completion)};
}
bool publish(std::shared_ptr<const PublishedSnapshot> snapshot,
std::shared_ptr<const CommandDispatcher> ledger) {
{
std::lock_guard lock(mutex);
if (stopping.load()) return false;
published.swap(snapshot);
committed.swap(ledger);
}
return true;
}
void fault() {
owner_faulted = true;
const auto error = std::current_exception();
{
std::lock_guard lock(mutex);
if (!stopping.load()) {
state = RuntimeState::Faulted;
failure = error;
}
}
// All World stage tasks have drained before an exception reaches here.
world.reset();
}
void tick() {
try {
const auto following = Void::Time::saturating_add(next_tick, tick_interval);
if (following == next_tick) throw std::overflow_error("simulation clock exhausted");
observe(RuntimePhase::BeforeTick);
world->step();
observe(RuntimePhase::BeforeCapture);
auto snapshot = capture(*world, *committed, published->rules, next_revision());
static_cast<void>(publish(std::move(snapshot), committed));
next_tick = following;
} catch (...) {
fault();
}
}
RuntimeResult command(Work& work) {
if (const auto receipt = committed->lookup(work.client, work.command)) {
return {RuntimeOutcome::Completed, *receipt, published};
}
if (owner_faulted) return {RuntimeOutcome::Faulted, {}, published};
try {
const bool was_paused = world->paused();
auto candidate = std::make_shared<CommandDispatcher>(*committed);
const auto receipt = candidate->dispatch(*world, work.client, work.command);
if (receipt.status != DispatchStatus::Completed) {
return {RuntimeOutcome::Completed, receipt, published};
}
observe(RuntimePhase::BeforeCapture);
auto snapshot = capture(*world, *candidate, published->rules, next_revision());
if (!publish(std::move(snapshot), std::move(candidate))) {
return {RuntimeOutcome::Closed, {}, published};
}
if (was_paused != world->paused()) reanchor();
return {RuntimeOutcome::Completed, receipt, published};
} catch (...) {
fault();
return {RuntimeOutcome::Faulted, {}, published};
}
}
bool current_ticket(const LoadTicket& ticket) const {
return ticket.request != 0 && ticket.request == latest_load &&
ticket.expected_session == published->identity.session;
}
RuntimeResult install(Work& work) {
{
std::lock_guard lock(mutex);
if (!current_ticket(work.ticket)) return {RuntimeOutcome::Superseded, {}, published};
}
try {
auto& candidate = *work.candidate;
auto ledger = std::make_shared<CommandDispatcher>(new_identity(candidate), options.dispatcher);
auto rules = std::make_shared<const RulesManifest>(std::move(candidate.rules));
observe(RuntimePhase::BeforeInstallCapture);
auto snapshot = capture(*candidate.world, *ledger, std::move(rules), next_revision());
std::shared_ptr<const CommandDispatcher> immutable_ledger = std::move(ledger);
{
std::lock_guard lock(mutex);
if (stopping.load()) return {RuntimeOutcome::Closed, {}, published};
if (!current_ticket(work.ticket)) return {RuntimeOutcome::Superseded, {}, published};
world.swap(candidate.world);
published.swap(snapshot);
committed.swap(immutable_ledger);
owner_faulted = false;
state = RuntimeState::Running;
failure = {};
}
reanchor();
return {RuntimeOutcome::Completed, {}, published};
} catch (...) {
return {RuntimeOutcome::InvalidCandidate, {}, published};
}
}
RuntimeResult process(Work& work) {
if (stopping.load()) return {RuntimeOutcome::Closed, {}, published};
switch (work.kind) {
case Kind::Command: return command(work);
case Kind::Install: return install(work);
case Kind::Ticking:
if (ticking != work.enabled) {
ticking = work.enabled;
reanchor();
}
break;
case Kind::Fence: break;
}
return {owner_faulted ? RuntimeOutcome::Faulted : RuntimeOutcome::Completed, {}, published};
}
void run() {
for (;;) {
std::unique_ptr<Work> work;
bool due = false;
{
std::unique_lock lock(mutex);
// No domain work or snapshot destruction occurs while holding mutex.
for (;;) {
if (stopping.load() && queue.empty()) return;
due = !stopping.load() && advancing() && next_tick <= clock->now();
if (!queue.empty()) {
const auto& front = *queue.front();
if (!(due && front.kind == Kind::Fence && next_tick <= front.deadline)) {
work = std::move(queue.front());
queue.pop_front();
}
break;
}
if (due) break;
if (advancing()) {
changed.wait_for(lock, Void::Time::remaining_until(*clock, next_tick));
} else {
changed.wait(lock);
}
}
}
if (work) {
auto result = process(*work);
{
std::lock_guard lock(mutex);
--outstanding;
}
work->promise.set_value(std::move(result));
work.reset();
// One tick per turn bounds catch-up work and lets queued input run.
if (!stopping.load() && advancing() && next_tick <= clock->now()) tick();
} else if (due) {
tick();
}
}
}
void shutdown() {
if (executor && executor->is_executor_thread()) {
throw std::logic_error("cannot shut down runtime from its owner");
}
{
std::lock_guard lock(mutex);
stopping.store(true);
state = RuntimeState::Closed;
}
changed.notify_all();
if (executor) static_cast<void>(executor->join());
}
};
SimulationRuntime::SimulationRuntime(WorldCheckpoint initial, RuntimeOptions options)
: impl_(std::make_unique<Impl>(std::move(initial), std::move(options))) {}
SimulationRuntime::~SimulationRuntime() = default;
std::shared_ptr<const PublishedSnapshot> SimulationRuntime::latest() const {
std::lock_guard lock(impl_->mutex);
return impl_->published;
}
RuntimeView SimulationRuntime::view() const {
std::lock_guard lock(impl_->mutex);
return {impl_->state, impl_->published, impl_->failure};
}
std::expected<std::shared_ptr<const PublishedSnapshot>, RuntimeState> SimulationRuntime::snapshot_for_save() const {
std::lock_guard lock(impl_->mutex);
if (impl_->state != RuntimeState::Running) return std::unexpected{impl_->state};
return impl_->published;
}
std::optional<DispatchReceipt> SimulationRuntime::lookup(
TrustedClient client, const CommandEnvelope& command) const {
std::shared_ptr<const CommandDispatcher> ledger;
{
std::lock_guard lock(impl_->mutex);
ledger = impl_->committed;
}
return ledger->lookup(client, command);
}
RuntimeSubmission SimulationRuntime::try_submit(TrustedClient client, const CommandEnvelope& command) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Command);
work->client = client;
work->command = command;
return impl_->enqueue(std::move(work));
}
RuntimeSubmission SimulationRuntime::set_ticking(bool enabled) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Ticking);
work->enabled = enabled;
return impl_->enqueue(std::move(work));
}
RuntimeSubmission SimulationRuntime::synchronize() {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Fence);
work->deadline = impl_->clock->now();
return impl_->enqueue(std::move(work));
}
void SimulationRuntime::notify_clock() {
// Pair with the owner's wait lock so a notification cannot be lost between
// checking the injected clock and beginning the condition-variable wait.
{ std::lock_guard lock(impl_->mutex); }
impl_->changed.notify_one();
}
std::expected<LoadTicket, RuntimeAdmission> SimulationRuntime::begin_load() {
std::lock_guard lock(impl_->mutex);
if (impl_->stopping.load()) return std::unexpected{RuntimeAdmission::Closed};
if (impl_->latest_load == std::numeric_limits<std::uint64_t>::max()) {
return std::unexpected{RuntimeAdmission::IdExhausted};
}
return LoadTicket{++impl_->latest_load, impl_->published->identity.session};
}
RuntimeSubmission SimulationRuntime::try_install(LoadTicket ticket, WorldCheckpoint& candidate) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Install);
work->ticket = ticket;
return impl_->enqueue(std::move(work), &candidate);
}
void SimulationRuntime::shutdown() { impl_->shutdown(); }
} // namespace settlement
+29 -40
View File
@@ -3,54 +3,43 @@
#include <stdexcept>
namespace settlement {
namespace {
WorkerPool::WorkerPool(std::size_t thread_count) {
std::unique_ptr<Void::Async::ThreadExecutor> start_executor(
std::size_t thread_count, const WorkerPoolOptions& options) {
if (thread_count < 2) {
throw std::invalid_argument("worker pool needs at least two threads");
}
workers_.reserve(thread_count);
try {
for (std::size_t index = 0; index < thread_count; ++index) {
workers_.emplace_back([this] { worker_loop(); });
}
} catch (...) {
{
std::lock_guard<std::mutex> lock(mutex_);
stopping_ = true;
}
work_available_.notify_all();
for (std::thread& worker : workers_) {
if (worker.joinable()) worker.join();
}
throw;
if (options.max_admitted == 0) {
throw std::invalid_argument("worker pool capacity must be positive");
}
Void::Async::ThreadExecutorOptions settings;
settings.workers = thread_count;
settings.max_admitted = options.max_admitted;
if (options.before_worker_start) {
settings.before_worker_start = [hook = options.before_worker_start](std::size_t index)
-> Void::Result::Result<void> {
hook(index);
return {};
};
}
auto executor = Void::Async::ThreadExecutor::create(std::move(settings));
if (!executor) throw std::runtime_error(executor.error().message());
const auto started = (*executor)->start();
if (!started) throw std::runtime_error(started.error().message());
return std::move(*executor);
}
WorkerPool::~WorkerPool() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopping_ = true;
}
work_available_.notify_all();
for (std::thread& worker : workers_) {
if (worker.joinable()) worker.join();
}
}
} // namespace
std::size_t WorkerPool::thread_count() const noexcept { return workers_.size(); }
WorkerPool::WorkerPool(std::size_t thread_count, WorkerPoolOptions options)
: thread_count_(thread_count), options_(std::move(options)),
executor_(start_executor(thread_count, options_)), futures_(*executor_) {}
void WorkerPool::worker_loop() {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex_);
work_available_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
if (stopping_ && tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
}
// ThreadExecutor's destructor closes admission and joins every accepted task.
// options_ outlives that join so fault-hook captures remain valid through shutdown.
WorkerPool::~WorkerPool() = default;
std::size_t WorkerPool::thread_count() const noexcept { return thread_count_; }
} // namespace settlement
+154 -71
View File
@@ -1,5 +1,8 @@
#include "settlement/core/world.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
#include <cassert>
@@ -132,6 +135,19 @@ auto stack_position(Storage& storage, ItemType type) {
[](const ItemStack& stack, ItemType target) { return stack.type < target; });
}
template<class Records>
auto record_position(Records& records, std::uint64_t id) {
return std::lower_bound(records.begin(), records.end(), id,
[](const auto& record, std::uint64_t target) { return record.id < target; });
}
template<class Records>
auto& require_record(Records& records, std::uint64_t id) {
const auto found = record_position(records, id);
if (found == records.end() || found->id != id) throw std::logic_error("Missing simulation object ID.");
return *found;
}
std::size_t checked_cell_count(std::int32_t width, std::int32_t height) {
if (width <= 0 || height <= 0 || width > max_map_dimension || height > max_map_dimension) {
throw std::invalid_argument("map dimensions must be in the range 1..512");
@@ -139,7 +155,18 @@ std::size_t checked_cell_count(std::int32_t width, std::int32_t height) {
return static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
}
std::size_t checked_worker_count(std::size_t workers) {
std::size_t checked_worker_count(std::size_t workers, ExecutionMode mode) {
switch (mode) {
case ExecutionMode::SerialReference:
if (workers != 1) {
throw std::invalid_argument("serial reference requires one logical worker");
}
return workers;
case ExecutionMode::Parallel:
break;
default:
throw std::invalid_argument("execution mode is not supported");
}
if (workers < min_worker_count || workers > max_worker_count) {
throw std::invalid_argument("worker count must be in the range 2..64");
}
@@ -268,12 +295,40 @@ void Storage::add_item(ItemType type) {
}
World::World(std::uint64_t seed, std::int32_t width, std::int32_t height,
std::size_t workers)
: seed_(seed),
width_(width),
height_(height),
worker_count_(checked_worker_count(workers)),
blocked_(checked_cell_count(width, height), 0) {}
std::size_t workers, ExecutionMode mode, WorkerPoolOptions worker_options)
: WorldState(seed, width, height),
worker_count_(checked_worker_count(workers, mode)),
execution_mode_(mode),
worker_options_(std::move(worker_options)) {
blocked_.resize(checked_cell_count(width, height), 0);
}
World::World(CaptureTag, const World& source)
: WorldState(source),
worker_count_(source.worker_count_),
execution_mode_(source.execution_mode_) {}
std::shared_ptr<const World> World::capture() const {
return std::shared_ptr<const World>(new const World(CaptureTag{}, *this));
}
const Storage* World::find_storage(StorageId id) const noexcept {
const auto found = record_position(storages_, id);
return found == storages_.end() || found->id != id ? nullptr : &*found;
}
const ResourceNode* World::find_resource_node(ResourceNodeId id) const noexcept {
const auto found = record_position(resource_nodes_, id);
return found == resource_nodes_.end() || found->id != id ? nullptr : &*found;
}
Storage& World::storage_by_id(StorageId id) {
return require_record(storages_, id);
}
ResourceNode& World::resource_node_by_id(ResourceNodeId id) {
return require_record(resource_nodes_, id);
}
std::size_t World::cell_index(GridPosition position) const noexcept {
return static_cast<std::size_t>(position.y) * static_cast<std::size_t>(width_) +
@@ -378,9 +433,14 @@ std::uint64_t World::add_resource_node(GridPosition position, ItemType type,
if ((type != ItemType::Wood && type != ItemType::Stone && type != ItemType::Berries) || quantity == 0) {
throw std::invalid_argument("resource node needs wood, stone, or berries and a positive quantity");
}
const std::uint64_t id = next_resource_node_id_++;
// Restorable counters stay with each World. Replacement contract and limits
// are tracked at https://git.faumaray.com/Void/Library/issues/7.
const std::uint64_t id = next_resource_node_id_;
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
if (!successor) throw std::overflow_error("resource node IDs exhausted");
const bool foraging = type != ItemType::Berries || !scenario_active_;
resource_nodes_.push_back(ResourceNode{id, position, type, quantity, quantity, 0, foraging});
next_resource_node_id_ = *successor;
return id;
}
@@ -395,10 +455,12 @@ std::uint64_t World::add_storage(GridPosition position, std::uint32_t capacity,
throw std::invalid_argument("unknown storage kind");
}
const std::uint64_t id = next_storage_id_;
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
if (!successor) throw std::overflow_error("storage IDs exhausted");
Storage storage{id, position, capacity, 0, {}, kind};
storage.items.reserve(kind == StorageKind::Pantry ? 1 : item_type_count - 1);
storages_.push_back(std::move(storage));
++next_storage_id_;
next_storage_id_ = *successor;
return id;
}
@@ -549,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;
@@ -605,7 +668,7 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe
[](const auto& item) { return item.reserved != 0; })) return busy;
for (const auto& order : production_orders_) {
if (std::any_of(order.materials.begin(), order.materials.end(),
[i](const auto& material) { return material.storage_index == i; })) return busy;
[&storage](const auto& material) { return material.storage_id == storage.id; })) return busy;
}
return ready;
}
@@ -651,13 +714,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
lost_products[i] = storage->item_count(carpentry_products[i]) != 0;
}
const auto removed = static_cast<std::size_t>(storage - storages_.begin());
storages_.erase(storage);
for (auto& agent : agents_) shift_index(agent.storage_index, removed);
for (auto& entry : production_orders_) {
for (auto& material : entry.materials) shift_index(material.storage_index, removed);
for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed);
}
if (scenario_active_) {
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
if (!lost_products[i]) continue;
@@ -683,9 +740,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
}
if (destination) source->position = *destination;
else {
const auto removed = static_cast<std::size_t>(source - resource_nodes_.begin());
resource_nodes_.erase(source);
for (auto& agent : agents_) shift_index(agent.resource_node_index, removed);
}
return CommandStatus::Accepted;
}
@@ -770,9 +825,11 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
} else if (!can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
const auto successor = Void::Numeric::checked_add(next_resource_node_id_, std::uint64_t{1});
if (!successor) return receipt(CommandStatus::Busy);
resource_nodes_.push_back({next_resource_node_id_, command.cell, site_resource(site), mine ? yield : 0,
yield, 0, true, site});
++next_resource_node_id_;
next_resource_node_id_ = *successor;
if (mine) {
blocked_[cell_index(command.cell)] = 0;
assignment_path_cache_.clear();
@@ -847,6 +904,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
if (!Void::Numeric::checked_add(next_storage_id_, std::uint64_t{1})) return receipt(CommandStatus::Busy);
static_cast<void>(add_storage(command.cell, 18, static_cast<StorageKind>(command.value)));
break;
case CommandKind::MoveObject:
@@ -1059,19 +1117,27 @@ void World::assign_idle_agents() {
return choices;
};
std::vector<std::future<std::vector<std::size_t>>> choice_futures;
choice_futures.reserve(chunk_count);
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
const std::size_t end = chunk_start(chunk + 1);
choice_futures.push_back(worker_pool_->submit([&choose_jobs, begin, end] {
return choose_jobs(begin, end);
}));
}
std::vector<std::vector<std::size_t>> choices;
choices.reserve(chunk_count);
for (auto& future : choice_futures) choices.push_back(future.get());
if (execution_mode_ == ExecutionMode::SerialReference) {
choices.push_back(choose_jobs(0, agents_.size()));
} else {
std::vector<std::future<std::vector<std::size_t>>> choice_futures;
choice_futures.reserve(chunk_count);
const auto drain_choices = Void::Scope::on_exit([&choice_futures] {
for (auto& future : choice_futures) {
if (future.valid()) future.wait();
}
});
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
const std::size_t end = chunk_start(chunk + 1);
choice_futures.push_back(worker_pool_->submit([&choose_jobs, begin, end] {
return choose_jobs(begin, end);
}));
}
for (auto& future : choice_futures) choices.push_back(future.get());
}
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
for (std::size_t offset = 0; offset < choices[chunk].size(); ++offset) {
@@ -1089,17 +1155,25 @@ void World::assign_idle_agents() {
if (requests.empty()) return;
std::vector<std::future<PathResult>> futures;
futures.reserve(requests.size());
for (const Request& request : requests) {
futures.push_back(worker_pool_->submit([this, start = request.start, goal = request.goal] {
return find_path(start, goal);
}));
const auto drain_paths = Void::Scope::on_exit([&futures] {
for (auto& future : futures) {
if (future.valid()) future.wait();
}
});
if (execution_mode_ == ExecutionMode::Parallel) {
futures.reserve(requests.size());
for (const Request& request : requests) {
futures.push_back(worker_pool_->submit([this, start = request.start, goal = request.goal] {
return find_path(start, goal);
}));
}
}
for (std::size_t index = 0; index < requests.size(); ++index) {
auto path = futures[index].get();
const Request& request = requests[index];
auto path = execution_mode_ == ExecutionMode::SerialReference
? find_path(request.start, request.goal) : futures[index].get();
++path_searches_;
path_nodes_visited_ += path.nodes_visited;
const Request& request = requests[index];
Agent& agent = agents_[request.agent_index];
WorkJob& job = jobs_[request.job_index];
if (!path.reachable) {
@@ -1205,7 +1279,7 @@ void World::assign_resource_tasks(ResourceFocus focus) {
if (node.needs_tending()) {
++resource_nodes_[node_index].reserved_workers;
--untended_sites;
agent.resource_node_index = node_index;
agent.resource_node_id = node.id;
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
agent.work_remaining = tending_ticks;
@@ -1246,8 +1320,8 @@ void World::assign_resource_tasks(ResourceFocus focus) {
if (storage.kind == StorageKind::Pantry) --open_pantry_count;
else --open_material_store_count;
}
agent.resource_node_index = node_index;
agent.storage_index = storage_index;
agent.resource_node_id = node.id;
agent.storage_id = storage.id;
agent.haul_route = std::move(path_to_storage.positions);
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
@@ -1302,7 +1376,7 @@ void World::assign_production_tasks(bool weaving) {
}
if (access == Access::Unreachable) continue;
}
materials.push_back({storage_index, ingredient.type, count});
materials.push_back({storage.id, ingredient.type, count});
remaining -= count;
}
if (remaining != 0) {
@@ -1315,12 +1389,12 @@ void World::assign_production_tasks(bool weaving) {
std::vector<ConstructionStop> stops;
if (deliver_ingredients) {
for (std::size_t s = 0; s < storage_access.size(); ++s) {
if (storage_access[s] == Access::Reachable) stops.push_back({s, {}});
if (storage_access[s] == Access::Reachable) stops.push_back({storages_[s].id, {}});
}
for (std::size_t i = 0; i < stops.size(); ++i) {
const auto from = storages_[stops[i].storage_index].position;
const auto from = storage_by_id(stops[i].storage_id).position;
const auto to = i + 1 == stops.size()
? order.position : storages_[stops[i + 1].storage_index].position;
? order.position : storage_by_id(stops[i + 1].storage_id).position;
auto path = assignment_path(from, to);
// Each stop can reach the site on the same undirected map.
assert(path.reachable);
@@ -1328,7 +1402,7 @@ void World::assign_production_tasks(bool weaving) {
}
}
const GridPosition destination = deliver_ingredients
? storages_[stops.front().storage_index].position : order.position;
? storage_by_id(stops.front().storage_id).position : order.position;
for (Agent& agent : agents_) {
const bool can_craft = agent.profession == Profession::Carpenter;
const bool eligible = carpentry ? can_craft :
@@ -1337,11 +1411,11 @@ void World::assign_production_tasks(bool weaving) {
auto path = assignment_path(agent.position, destination);
if (!path.reachable) continue;
if (carpentry) {
agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions;
agent.haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions;
}
for (const auto& material : materials) {
stack_position(storages_[material.storage_index], material.type)->reserved += material.count;
stack_position(storage_by_id(material.storage_id), material.type)->reserved += material.count;
}
order.materials = std::move(materials);
order.delivery_stops = std::move(stops);
@@ -1397,7 +1471,7 @@ void World::assign_meals() {
auto stack = stack_position(storage, ItemType::Berries);
++stack->reserved;
agent.storage_index = *pantry;
agent.storage_id = storage.id;
agent.state = AgentState::GoingToEat;
agent.route = std::move(path.positions);
agent.route_cursor = 0;
@@ -1410,9 +1484,9 @@ void World::assign_meals() {
void World::finish_meal_step(Agent& agent) {
if (agent.state == AgentState::GoingToEat) {
if (agent.route_cursor != agent.route.size()) return;
take_reserved_material(storages_[agent.storage_index], {agent.storage_index, ItemType::Berries, 1});
take_reserved_material(storage_by_id(agent.storage_id), {agent.storage_id, ItemType::Berries, 1});
agent.inventory.add(ItemType::Berries);
agent.storage_index = no_entity_index;
agent.storage_id = 0;
agent.route.clear();
agent.route_cursor = 0;
agent.work_remaining = meal_ticks;
@@ -1494,14 +1568,14 @@ void World::advance_construction_delivery(Agent& agent) {
auto& stop = order.delivery_stops[order.collected_stops];
for (const auto& material : order.materials) {
if (material.storage_index == stop.storage_index) {
take_reserved_material(storages_[stop.storage_index], material);
if (material.storage_id == stop.storage_id) {
take_reserved_material(storage_by_id(stop.storage_id), material);
agent.inventory.add(material.type, material.count);
}
}
if (is_carpentry_recipe(order.recipe) && stop.storage_index == order.materials.front().storage_index) {
if (is_carpentry_recipe(order.recipe) && stop.storage_id == order.materials.front().storage_id) {
// Collecting the first ingredient frees a slot for the finished item.
++storages_[stop.storage_index].reserved_slots;
++storage_by_id(stop.storage_id).reserved_slots;
}
++order.collected_stops;
agent.route = std::move(stop.route_to_next);
@@ -1515,7 +1589,7 @@ void World::finish_production(Agent& agent) {
assert(!order.materials.empty());
if (is_carpentry_recipe(order.recipe)) {
agent.inventory.add(recipe.output);
agent.storage_index = order.materials.front().storage_index;
agent.storage_id = order.materials.front().storage_id;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
@@ -1527,10 +1601,10 @@ void World::finish_production(Agent& agent) {
}
if (recipe.output != ItemType::None) {
for (const auto& material : order.materials) {
take_reserved_material(storages_[material.storage_index], material);
take_reserved_material(storage_by_id(material.storage_id), material);
}
// Crafting replaces one raw item with one finished item in the same store.
storages_[order.materials.front().storage_index].add_item(recipe.output);
storage_by_id(order.materials.front().storage_id).add_item(recipe.output);
}
order.materials.clear();
if (order.recipe == RecipeId::BuildBed &&
@@ -1565,7 +1639,9 @@ void World::grow_sites() {
void World::step(TickProfile* profile) {
if (paused_) return;
if (!worker_pool_ && !agents_.empty()) worker_pool_ = std::make_unique<WorkerPool>(worker_count_);
if (execution_mode_ == ExecutionMode::Parallel && !worker_pool_ && !agents_.empty()) {
worker_pool_ = std::make_unique<WorkerPool>(worker_count_, worker_options_);
}
using Clock = std::chrono::steady_clock;
auto phase_start = profile ? Clock::now() : Clock::time_point{};
const auto finish_phase = [&](std::chrono::nanoseconds TickProfile::*phase) {
@@ -1607,7 +1683,7 @@ void World::step(TickProfile* profile) {
agent.route_cursor < agent.route.size()) {
agent.position = agent.route[agent.route_cursor++];
if (agent.state == AgentState::Travelling && agent.route_cursor == agent.route.size()) {
agent.state = agent.resource_node_index == no_entity_index
agent.state = agent.resource_node_id == 0
? AgentState::Working : AgentState::Gathering;
}
}
@@ -1636,10 +1712,17 @@ void World::step(TickProfile* profile) {
return completed;
};
if (!agents_.empty()) {
if (execution_mode_ == ExecutionMode::SerialReference) {
jobs_completed_ += advance_agents(0, agents_.size());
} else if (!agents_.empty()) {
const auto chunk_count = std::min(worker_count_, agents_.size());
std::vector<std::future<std::uint64_t>> futures;
futures.reserve(chunk_count);
const auto drain_advancement = Void::Scope::on_exit([&futures] {
for (auto& future : futures) {
if (future.valid()) future.wait();
}
});
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk * agents_.size() / chunk_count;
const std::size_t end = (chunk + 1) * agents_.size() / chunk_count;
@@ -1669,12 +1752,12 @@ void World::step(TickProfile* profile) {
finish_production(agent);
}
if (agent.state == AgentState::Gathering) {
if (agent.work_remaining == 0 && agent.resource_node_index < resource_nodes_.size()) {
ResourceNode& node = resource_nodes_[agent.resource_node_index];
if (agent.storage_index == no_entity_index) {
if (agent.work_remaining == 0 && agent.resource_node_id != 0) {
ResourceNode& node = resource_node_by_id(agent.resource_node_id);
if (agent.storage_id == 0) {
node.growth_at = tick_ + growing_time(node.site);
--node.reserved_workers;
agent.resource_node_index = no_entity_index;
agent.resource_node_id = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
@@ -1683,7 +1766,7 @@ void World::step(TickProfile* profile) {
if (node.quantity > 0) --node.quantity;
if (node.reserved_workers > 0) --node.reserved_workers;
agent.inventory.add(node.type);
agent.resource_node_index = no_entity_index;
agent.resource_node_id = 0;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
@@ -1692,13 +1775,13 @@ void World::step(TickProfile* profile) {
}
if (agent.state == AgentState::Hauling && agent.route_cursor == agent.route.size() &&
agent.storage_index < storages_.size()) {
Storage& storage = storages_[agent.storage_index];
agent.storage_id != 0) {
Storage& storage = storage_by_id(agent.storage_id);
const ItemType cargo = agent.inventory.first_item();
if (storage.reserved_slots > 0) --storage.reserved_slots;
storage.add_item(cargo);
agent.inventory.remove(cargo);
agent.storage_index = no_entity_index;
agent.storage_id = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
+85 -29
View File
@@ -146,6 +146,41 @@ void index(Archive& archive, Index& value) {
}
}
template<class Records>
std::size_t record_index(const Records& records, std::uint64_t id) {
const auto found = std::lower_bound(records.begin(), records.end(), id,
[](const auto& record, std::uint64_t target) { return record.id < target; });
require_save(found != records.end() && found->id == id, "Save contains an invalid object reference.");
return static_cast<std::size_t>(found - records.begin());
}
template<class Records>
std::uint64_t reference_id(const Records& records, std::size_t position) {
if (position == no_entity_index) return 0;
require_save(position < records.size(), "Save contains an invalid object index.");
return records[position].id;
}
template<class Records>
void validate_reference_pool(const Records& records, std::uint64_t next_id) {
std::uint64_t previous = 0;
for (const auto& record : records) {
require_save(record.id > previous, "Save contains unordered object IDs.");
previous = record.id;
}
require_save(next_id > previous, "Save contains an invalid next object ID.");
}
template<class Archive, class Id, class Records>
void reference(Archive& archive, Id& id, const Records& records) {
std::size_t position = no_entity_index;
if constexpr (!Archive::reading) {
if (id != 0) position = record_index(records, id);
}
index(archive, position);
if constexpr (Archive::reading) id = reference_id(records, position);
}
template<class Archive, class Size>
void offset(Archive& archive, Size& value) {
auto wire = static_cast<std::uint64_t>(value);
@@ -199,6 +234,9 @@ struct WorldSaveCodec {
const auto cells = world.blocked_.size();
for (auto& cell : world.blocked_) archive.field(cell);
// Agent links precede their pools in legacy saves. Raw positions stay
// loader-owned until the complete, ID-ordered pools are available.
std::vector<std::array<std::size_t, 2>> agent_links;
sequence(archive, world.agents_, max_records, [&](auto& agent) {
archive.field(agent.id);
position(archive, agent.position);
@@ -207,8 +245,15 @@ struct WorldSaveCodec {
route(archive, agent.route, cells);
offset(archive, agent.route_cursor);
archive.field(agent.work_remaining);
index(archive, agent.resource_node_index);
index(archive, agent.storage_index);
if constexpr (Archive::reading) {
std::array<std::size_t, 2> links{no_entity_index, no_entity_index};
index(archive, links[0]);
index(archive, links[1]);
agent_links.push_back(links);
} else {
reference(archive, agent.resource_node_id, world.resource_nodes_);
reference(archive, agent.storage_id, world.storages_);
}
const auto inventory_types = version >= 3 ? max_item_count : static_cast<std::size_t>(ItemType::Berries);
for (std::size_t i = 1; i <= inventory_types; ++i) {
const auto type = static_cast<ItemType>(i);
@@ -261,6 +306,14 @@ struct WorldSaveCodec {
storage.items.reserve(storage.kind == StorageKind::Pantry ? 1 : item_types - 1);
}
});
if constexpr (Archive::reading) {
validate_reference_pool(world.resource_nodes_, world.next_resource_node_id_);
validate_reference_pool(world.storages_, world.next_storage_id_);
for (std::size_t i = 0; i < agent_links.size(); ++i) {
world.agents_[i].resource_node_id = reference_id(world.resource_nodes_, agent_links[i][0]);
world.agents_[i].storage_id = reference_id(world.storages_, agent_links[i][1]);
}
}
sequence(archive, world.production_orders_, max_records, [&](auto& order) {
position(archive, order.position);
archive.field(order.recipe);
@@ -272,13 +325,13 @@ struct WorldSaveCodec {
require_save(version >= 13 || order.recipe <= RecipeId::CraftWoodenDoor, "Unknown recipe for save version.");
archive.field(order.state);
sequence(archive, order.materials, item_types, [&](auto& material) {
index(archive, material.storage_index);
reference(archive, material.storage_id, world.storages_);
archive.field(material.type);
require_save(material.type <= max_item, "Unknown material for save version.");
archive.field(material.count);
});
sequence(archive, order.delivery_stops, item_types, [&](auto& stop) {
index(archive, stop.storage_index);
reference(archive, stop.storage_id, world.storages_);
route(archive, stop.route_to_next, cells);
});
offset(archive, order.collected_stops);
@@ -371,6 +424,8 @@ void WorldSaveCodec::validate(const World& world) {
}
}
const auto storage_index = [&](StorageId id) { return record_index(world.storages_, id); };
const auto node_index = [&](ResourceNodeId id) { return record_index(world.resource_nodes_, id); };
std::vector<ItemCounts> reserved_items(world.storages_.size());
std::vector<ItemCounts> expected_cargo(world.production_orders_.size());
std::vector<AgentId> bed_owners;
@@ -399,33 +454,33 @@ void WorldSaveCodec::validate(const World& world) {
const bool delivery = delivers_materials(order.recipe);
invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty()));
std::size_t last_storage = 0;
StorageId last_storage = 0;
bool first_stop = true;
for (const auto& stop : order.delivery_stops) {
invalid(stop.storage_index < world.storages_.size() && (first_stop || last_storage < stop.storage_index));
invalid(world.find_storage(stop.storage_id) != nullptr && (first_stop || last_storage < stop.storage_id));
invalid(std::any_of(order.materials.begin(), order.materials.end(),
[&](const auto& material) { return material.storage_index == stop.storage_index; }));
[&](const auto& material) { return material.storage_id == stop.storage_id; }));
valid_route(stop.route_to_next);
first_stop = false;
last_storage = stop.storage_index;
last_storage = stop.storage_id;
}
ItemCounts ingredients{};
for (const auto& material : order.materials) {
const auto type = item_index(material.type);
invalid(material.storage_index < world.storages_.size() && material.count > 0 &&
world.storages_[material.storage_index].kind == StorageKind::Materials);
invalid(world.find_storage(material.storage_id) != nullptr && material.count > 0 &&
world.storages_[storage_index(material.storage_id)].kind == StorageKind::Materials);
ingredients[type] += material.count;
if (!delivery) {
reserved_items[material.storage_index][type] += material.count;
reserved_items[storage_index(material.storage_id)][type] += material.count;
} else if (!order.delivery_stops.empty()) {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(),
[&](const auto& entry) { return entry.storage_index == material.storage_index; });
[&](const auto& entry) { return entry.storage_id == material.storage_id; });
invalid(stop != order.delivery_stops.end());
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) {
expected_cargo[i][type] += material.count;
} else {
reserved_items[material.storage_index][type] += material.count;
reserved_items[storage_index(material.storage_id)][type] += material.count;
}
}
}
@@ -486,9 +541,9 @@ void WorldSaveCodec::validate(const World& world) {
valid_route(agent.haul_route);
const bool has_job = agent.current_job != 0;
const bool has_order = agent.production_index != no_entity_index;
const bool has_source = agent.resource_node_index != no_entity_index;
const bool has_storage = agent.storage_index != no_entity_index;
invalid(!has_storage || agent.storage_index < world.storages_.size());
const bool has_source = agent.resource_node_id != 0;
const bool has_storage = agent.storage_id != 0;
invalid(!has_storage || world.find_storage(agent.storage_id) != nullptr);
const bool carpentry = has_order && agent.production_index < world.production_orders_.size() &&
is_carpentry_recipe(world.production_orders_[agent.production_index].recipe);
invalid(agent.haul_route.empty() || has_source || carpentry);
@@ -513,12 +568,12 @@ void WorldSaveCodec::validate(const World& world) {
invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe)));
}
if (carpentry) {
const auto storage = order.materials.front().storage_index;
const auto storage = storage_index(order.materials.front().storage_id);
const auto destination = world.storages_[storage].position;
invalid(agent.haul_route.empty() ? destination == order.position : agent.haul_route.back() == destination);
const auto& stops = order.delivery_stops;
const auto output_stop = std::find_if(stops.begin(), stops.end(),
[storage](const auto& stop) { return stop.storage_index == storage; });
[&order](const auto& stop) { return stop.storage_id == order.materials.front().storage_id; });
const bool collected = stops.empty() ||
static_cast<std::size_t>(output_stop - stops.begin()) < order.collected_stops;
if (collected) ++reserved_slots[storage];
@@ -527,32 +582,32 @@ void WorldSaveCodec::validate(const World& world) {
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]);
}
} else if (has_source) {
invalid(agent.resource_node_index < world.resource_nodes_.size() &&
invalid(world.find_resource_node(agent.resource_node_id) != nullptr &&
(agent.state == Travelling || agent.state == Gathering) && agent.inventory.empty() &&
agent.work_remaining > 0);
const auto& source = world.resource_nodes_[agent.resource_node_index];
const auto& source = world.resource_nodes_[node_index(agent.resource_node_id)];
if (has_storage) {
invalid(source.quantity > 0 && world.storages_[agent.storage_index].accepts(source.type));
++reserved_slots[agent.storage_index];
invalid(source.quantity > 0 && world.storages_[storage_index(agent.storage_id)].accepts(source.type));
++reserved_slots[storage_index(agent.storage_id)];
} else {
invalid(source.needs_tending() && agent.haul_route.empty());
}
++reserved_nodes[agent.resource_node_index];
++reserved_nodes[node_index(agent.resource_node_id)];
} else if (agent.state == Hauling) {
const auto cargo = agent.inventory.first_item();
invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone ||
cargo == ItemType::Berries || cargo == ItemType::Flax || is_carpentry_item(cargo)) &&
agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 &&
world.storages_[agent.storage_index].accepts(cargo));
world.storages_[storage_index(agent.storage_id)].accepts(cargo));
for (std::size_t i = 1; i <= item_types; ++i) {
const auto type = static_cast<ItemType>(i);
invalid(type == cargo || agent.inventory.item_count(type) == 0);
}
++reserved_slots[agent.storage_index];
++reserved_slots[storage_index(agent.storage_id)];
} else if (agent.state == GoingToEat) {
invalid(world.hunger_enabled_ && has_storage && agent.inventory.empty() &&
world.storages_[agent.storage_index].kind == StorageKind::Pantry);
++reserved_items[agent.storage_index][item_index(ItemType::Berries)];
world.storages_[storage_index(agent.storage_id)].kind == StorageKind::Pantry);
++reserved_items[storage_index(agent.storage_id)][item_index(ItemType::Berries)];
} else if (agent.state == Eating) {
invalid(world.hunger_enabled_ && !has_storage && agent.work_remaining > 0 &&
agent.inventory.item_count(ItemType::Berries) == 1 &&
@@ -609,7 +664,8 @@ void World::write_save(std::ostream& stream) const {
WorldSaveCodec::body(archive, *this, save_version);
}
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers) {
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode,
WorkerPoolOptions worker_options) {
SaveReader archive(stream);
for (char letter : signature) {
char actual = 0;
@@ -626,7 +682,7 @@ std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t worker
archive.field(seed);
archive.field(width);
archive.field(height);
auto world = std::make_unique<World>(seed, width, height, workers);
auto world = std::make_unique<World>(seed, width, height, workers, mode, std::move(worker_options));
WorldSaveCodec::body(archive, *world, version);
archive.finish();
if (version < 5) {
+347
View File
@@ -0,0 +1,347 @@
#include "settlement/core/checkpoint_files.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Suite.hpp>
#include <atomic>
#include <chrono>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using namespace std::chrono_literals;
using Void::Testing::Test;
void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
struct TemporaryDirectory {
std::filesystem::path path = std::filesystem::temp_directory_path() /
("settlement-checkpoint-files-" + Void::Uuid::v4().to_string());
TemporaryDirectory() {
require(std::filesystem::create_directory(path), "cannot create exclusive test directory");
}
~TemporaryDirectory() {
std::error_code error;
std::filesystem::remove_all(path, error);
}
};
std::string saved(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return std::move(stream).str();
}
Void::Uuid::Uuid identity(std::uint8_t last) {
Void::Uuid::Uuid id;
id.bytes.back() = last;
return id;
}
std::shared_ptr<const PublishedSnapshot> snapshot(const World& world) {
auto rules = default_rules_manifest();
require(rules.has_value(), "cannot resolve fixture rules");
return std::make_shared<const PublishedSnapshot>(PublishedSnapshot{
{identity(1), identity(2), 7}, 1, world.capture(),
std::make_shared<const RulesManifest>(std::move(*rules)), {1, 1}});
}
std::string encoded(const World& world) {
const auto view = snapshot(world);
auto bytes = encode_checkpoint(*view->world, view->identity.world, view->identity.city, *view->rules);
require(bytes.has_value(), "cannot encode fixture");
return std::move(*bytes);
}
void write(const std::filesystem::path& path, std::string_view bytes, bool append = false) {
std::ofstream file(path, std::ios::binary | (append ? std::ios::app : std::ios::trunc));
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
file.close();
require(static_cast<bool>(file), "cannot write fixture");
}
template<class Submit>
auto admitted(Submit submit) {
const auto limit = std::chrono::steady_clock::now() + 10s;
for (;;) {
auto operation = submit();
if (operation.admission != decltype(operation.admission)::Busy) return operation;
require(std::chrono::steady_clock::now() < limit, "admission remained busy");
std::this_thread::yield();
}
}
CheckpointLoadResult loaded(CheckpointLoadSubmission operation) {
require(operation.admission == CheckpointLoadAdmission::Accepted && operation.request_id != 0,
"load was not accepted");
require(operation.completion.wait_for(10s) == std::future_status::ready, "load timed out");
return operation.completion.get();
}
CheckpointLoadResult load(CheckpointFiles& files, const std::filesystem::path& path) {
return loaded(admitted([&] { return files.try_load(path, 1, ExecutionMode::SerialReference); }));
}
SaveResult saved_file(SaveSubmission operation) {
require(operation.admission == SaveAdmission::Accepted && operation.request_id != 0,
"save was not accepted");
require(operation.completion.wait_for(10s) == std::future_status::ready, "save timed out");
auto result = operation.completion.get();
require(result.request_id == operation.request_id, "save completion lost identity");
return result;
}
struct Gate {
std::promise<void> entered;
std::future<void> arrival = entered.get_future();
std::promise<void> released;
std::shared_future<void> release = released.get_future().share();
std::atomic<bool> used = false;
std::atomic<bool> opened = false;
void block_once() {
if (used.exchange(true)) return;
entered.set_value();
require(release.wait_for(10s) == std::future_status::ready, "reader gate timed out");
}
void await_entry() {
require(arrival.wait_for(10s) == std::future_status::ready, "reader did not reach gate");
}
void open() {
if (!opened.exchange(true)) released.set_value();
}
};
struct [[= Void::Testing::name("CheckpointFileTests")]]
CheckpointFileTests : Void::Testing::Suite<CheckpointFileTests> {
[[= Void::Testing::tag("checkpoint-file")]] Test saves_held_snapshot_while_runtime_advances();
[[= Void::Testing::tag("checkpoint-file")]] Test legacy_versions_import_with_fresh_identity();
[[= Void::Testing::tag("checkpoint-file")]] Test modern_failures_retain_exact_diagnostics();
[[= Void::Testing::tag("checkpoint-file")]] Test bounds_cover_initial_size_and_growth();
[[= Void::Testing::tag("checkpoint-file")]] Test reader_bound_writer_progress_and_shutdown_drain();
[[= Void::Testing::tag("checkpoint-file")]] Test failures_recover_and_invalid_admission_preserves_inputs();
[[= Void::Testing::tag("checkpoint-file")]] Test reader_self_shutdown_is_rejected_without_closing();
};
Test CheckpointFileTests::saves_held_snapshot_while_runtime_advances() {
TemporaryDirectory directory;
CheckpointFiles files;
auto rules = default_rules_manifest();
require(rules.has_value(), "fixture rules unavailable");
auto clock = std::make_shared<Void::Time::ManualClock>();
SimulationRuntime runtime(
{make_first_colony(2), identity(23), 1, std::move(*rules)}, {.clock = clock});
auto healthy = runtime.snapshot_for_save();
require(healthy.has_value(), "healthy snapshot unavailable");
const auto old = *healthy;
const auto bytes = saved(*old->world);
const auto path = directory.path / L"Поселение_старый_снимок.settlement";
auto saving = admitted([&] { return files.try_save(path, old); });
require(clock->advance(1s).has_value(), "manual clock failed");
auto fence = admitted([&] { return runtime.synchronize(); });
require(fence.admission == RuntimeAdmission::Accepted, "runtime fence rejected");
require(fence.completion.wait_for(10s) == std::future_status::ready, "runtime did not advance");
require(fence.completion.get().outcome == RuntimeOutcome::Completed, "runtime fence failed");
require(runtime.latest()->world->tick() == old->world->tick() + 20, "live world did not progress");
const auto result = saved_file(std::move(saving));
require(result.succeeded() && result.tick == old->world->tick() &&
result.session == old->identity.session, "save metadata or publication changed");
runtime.shutdown();
auto restored = load(files, path);
require(restored.has_value(), "saved snapshot could not load");
require(restored->world_id == old->identity.world && restored->city == old->identity.city &&
restored->rules == *old->rules && saved(*restored->world) == bytes,
"background save read later mutable state");
}
Test CheckpointFileTests::legacy_versions_import_with_fresh_identity() {
TemporaryDirectory directory;
CheckpointFiles files;
World world(0x0102030405060708, 5, 5, 1, ExecutionMode::SerialReference);
const auto current = saved(world);
require(current.size() == 183, "legacy fixture layout changed");
std::vector<std::string> versions{current.substr(0, 146), current, current, current};
versions[0][8] = 1;
versions[0].append("\x58\xc1\x77\x19\x3a\x69\xca\x2c", 8);
versions[1][8] = 8;
versions[1].append("\x33\x73\x67\x28\xa8\x53\x56\xfa", 8);
versions[2][8] = 9;
const auto rules = default_rules_manifest();
require(rules.has_value(), "fixture default rules unavailable");
Void::Uuid::Uuid previous;
for (const auto& version : versions) {
const auto path = directory.path / L"старое.settlement";
write(path, version);
auto restored = load(files, path);
require(restored.has_value(), "historical fixture rejected");
require(!restored->world_id.is_nil() && restored->world_id != previous &&
restored->city == 1 && restored->rules == *rules && saved(*restored->world) == current,
"legacy import lost state or identity isolation");
previous = restored->world_id;
}
const auto path = directory.path / "legacy-trailing.settlement";
write(path, current + 'x');
const auto trailing = load(files, path);
require(!trailing && trailing.error().code == CheckpointFileError::InvalidLegacy,
"legacy trailing bytes were accepted");
}
Test CheckpointFileTests::modern_failures_retain_exact_diagnostics() {
TemporaryDirectory directory;
CheckpointFiles files;
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto current = encoded(world);
const auto path = directory.path / "modern.settlement";
for (const auto& invalid : {current.substr(0, 8), current.substr(0, current.size() - 1), current + 'x'}) {
write(path, invalid);
const auto result = load(files, path);
require(!result && result.error().code == CheckpointFileError::InvalidCheckpoint &&
result.error().checkpoint.has_value() && !result.error().message.empty(),
"modern failure lost its codec diagnostic");
}
auto unsupported = current;
unsupported[8] = 2;
write(path, unsupported);
const auto version = load(files, path);
require(!version && version.error().checkpoint &&
version.error().checkpoint->code == CheckpointError::UnsupportedVersion,
"modern unsupported version was downgraded or obscured");
write(path, current);
CheckpointFiles missing(std::vector<RulePackage>{});
const auto mismatch = load(missing, path);
require(!mismatch && mismatch.error().checkpoint &&
mismatch.error().checkpoint->code == CheckpointError::RulesMismatch &&
!mismatch.error().checkpoint->package.empty(), "missing package diagnostic was lost");
write(path, saved(world));
const auto legacy_mismatch = load(missing, path);
require(!legacy_mismatch && legacy_mismatch.error().checkpoint &&
legacy_mismatch.error().checkpoint->code == CheckpointError::RulesMismatch,
"legacy import bound unavailable default packages");
write(path, current);
require(load(files, path).has_value(), "reader did not recover after malformed files");
}
Test CheckpointFileTests::bounds_cover_initial_size_and_growth() {
TemporaryDirectory directory;
const auto path = directory.path / "oversized.settlement";
write(path, "");
std::filesystem::resize_file(path, max_checkpoint_bytes + 1);
CheckpointFiles files;
const auto large = load(files, path);
require(!large && large.error().code == CheckpointFileError::TooLarge,
"oversized initial file reached decoding");
write(path, "SETTLERS");
auto grew = std::make_shared<std::atomic<bool>>(false);
CheckpointFiles growing({.max_load_bytes = 512,
.read_observer = [grew, path](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && !grew->exchange(true)) {
write(path, std::string(1024, 'x'), true);
}
}});
const auto growth = load(growing, path);
require(!growth && growth.error().code == CheckpointFileError::TooLarge,
"growth after initial size check escaped the cap");
}
Test CheckpointFileTests::reader_bound_writer_progress_and_shutdown_drain() {
TemporaryDirectory directory;
World world(7, 5, 5, 1, ExecutionMode::SerialReference);
const auto path = directory.path / "read.settlement";
write(path, encoded(world));
World newer(8, 5, 5, 1, ExecutionMode::SerialReference);
const auto new_path = directory.path / "newer.settlement";
write(new_path, encoded(newer));
auto gate = std::make_shared<Gate>();
CheckpointFiles files({.load_capacity = 2, .read_observer = [gate](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened) gate->block_once();
}});
auto unblock = Void::Scope::on_exit([gate] { gate->open(); });
auto first = files.try_load(path);
require(first.admission == CheckpointLoadAdmission::Accepted, "first reader rejected");
gate->await_entry();
auto second = files.try_load(new_path);
require(second.admission == CheckpointLoadAdmission::Accepted && second.request_id > first.request_id,
"second reader did not queue in order");
require(files.try_load(path).admission == CheckpointLoadAdmission::Busy,
"running reader was excluded from bound");
const auto view = snapshot(world);
require(saved_file(admitted([&] { return files.try_save(directory.path / "write.settlement", view); })).succeeded(),
"held reader blocked independent writer");
require(first.completion.wait_for(0s) == std::future_status::timeout, "gate did not hold active read");
auto stopping = std::async(std::launch::async, [&] { files.shutdown(); });
auto release_shutdown = Void::Scope::on_exit([gate] { gate->open(); });
const auto deadline = std::chrono::steady_clock::now() + 10s;
for (;;) {
const auto operation = files.try_load(path);
if (operation.admission == CheckpointLoadAdmission::Closed) break;
require(operation.admission == CheckpointLoadAdmission::Busy, "shutdown unexpectedly admitted a read");
require(std::chrono::steady_clock::now() < deadline, "shutdown did not close admission");
std::this_thread::yield();
}
require(files.try_save(directory.path / "closed.settlement", view).admission == SaveAdmission::Closed,
"shutdown left save admission open");
gate->open();
auto first_result = loaded(std::move(first));
auto second_result = loaded(std::move(second));
require(first_result.has_value() && second_result.has_value() &&
first_result->world->seed() == world.seed() && second_result->world->seed() == newer.seed(),
"shutdown lost or mixed queued load candidates");
require(stopping.wait_for(10s) == std::future_status::ready, "shutdown did not finish");
stopping.get();
}
Test CheckpointFileTests::failures_recover_and_invalid_admission_preserves_inputs() {
TemporaryDirectory directory;
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto path = directory.path / "valid.settlement";
write(path, encoded(world));
auto fail = std::make_shared<std::atomic<bool>>(true);
CheckpointFiles files({.read_observer = [fail](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && fail->exchange(false)) {
throw std::runtime_error("injected read observer failure");
}
}});
require(files.try_load("relative.settlement").admission == CheckpointLoadAdmission::InvalidRequest,
"relative input was admitted");
require(files.try_load(path, 1).admission == CheckpointLoadAdmission::InvalidRequest,
"unsupported parallel worker count admitted");
require(files.try_save(path, {}).admission == SaveAdmission::InvalidRequest, "null snapshot admitted");
const auto view = snapshot(world);
require(files.try_save("relative.settlement", view).admission == SaveAdmission::InvalidRequest &&
view->world->tick() == world.tick(), "invalid save altered its input");
const auto failed = load(files, path);
require(!failed && failed.error().code == CheckpointFileError::ReaderFailure,
"observer failure did not settle future");
const auto missing = load(files, directory.path / "missing.settlement");
require(!missing && missing.error().code == CheckpointFileError::Io && missing.error().native_error != 0,
"missing file lost native error");
write(directory.path / "unknown.settlement", "arbitrary bytes");
const auto unknown = load(files, directory.path / "unknown.settlement");
require(!unknown && unknown.error().code == CheckpointFileError::UnsupportedFormat,
"unknown signature was accepted");
require(load(files, path).has_value(), "failed read poisoned the service");
}
Test CheckpointFileTests::reader_self_shutdown_is_rejected_without_closing() {
TemporaryDirectory directory;
World world(3, 5, 5, 1, ExecutionMode::SerialReference);
const auto path = directory.path / "self.settlement";
write(path, encoded(world));
CheckpointFiles* owner = nullptr;
auto first = std::make_shared<std::atomic<bool>>(true);
CheckpointFiles files({.read_observer = [&owner, first](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && first->exchange(false)) owner->shutdown();
}});
owner = &files;
const auto failure = load(files, path);
require(!failure && failure.error().code == CheckpointFileError::ReaderFailure,
"self shutdown did not report failure");
require(load(files, path).has_value(), "self shutdown closed admission before rejecting");
}
} // namespace
+336
View File
@@ -0,0 +1,336 @@
#include "settlement/core/checkpoint.hpp"
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}};
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
template<class T, class Error>
T checked(std::expected<T, Error> result) {
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return std::move(stream).str();
}
std::string encoded(const World& world, const RulesManifest& rules) {
return checked(encode_checkpoint(world, world_id, 7, rules));
}
WorldCheckpoint decoded(std::string_view bytes, std::span<const RulePackage> catalog) {
return checked(decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference));
}
void rejected(std::string_view bytes, std::span<const RulePackage> catalog,
CheckpointError code, std::string_view field = {}, std::string_view package = {}) {
const auto result = decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference);
require(!result, "invalid checkpoint was accepted");
require(result.error().code == code && !result.error().message.empty(), "checkpoint error lost its code or message");
require(result.error().field.find(field) != std::string::npos, "checkpoint error named the wrong field");
require(result.error().package.find(package) != std::string::npos, "checkpoint error lost its package");
}
template<class T>
void change(std::string& bytes, std::size_t offset, T value) {
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset));
require(writer.writeLittle(value).has_value(), "fixture field write failed");
}
void rehash(std::string& bytes) {
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
require(hasher.has_value(), "fixture hasher creation failed");
require(hasher->update(std::string_view(bytes).substr(0, bytes.size() - 32)).has_value(), "fixture hash failed");
const auto checksum = hasher->finalize();
require(checksum.has_value() && checksum->size() == 32, "fixture hash finalization failed");
std::memcpy(bytes.data() + bytes.size() - 32, checksum->data(), checksum->size());
}
struct PackageLocation {
std::size_t begin;
std::size_t version_length;
std::size_t end;
};
struct FrameLayout {
std::uint32_t metadata_size;
std::uint64_t body_size;
std::size_t body_begin;
std::vector<PackageLocation> packages;
};
FrameLayout layout(std::string_view bytes) {
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(), bytes.size()}));
require(reader.skip(12).has_value(), "fixture header skip failed");
FrameLayout result{};
result.metadata_size = reader.readLittle<std::uint32_t>().value();
result.body_size = reader.readLittle<std::uint64_t>().value();
result.body_begin = 24 + result.metadata_size;
require(reader.skip(64).has_value(), "fixture metadata skip failed");
const auto count = reader.readLittle<std::uint32_t>().value();
for (std::uint32_t i = 0; i < count; ++i) {
const auto begin = reader.position();
const auto id_size = reader.readLittle<std::uint16_t>().value();
require(reader.skip(id_size).has_value(), "fixture ID skip failed");
const auto version_length = reader.position();
const auto version_size = reader.readLittle<std::uint16_t>().value();
require(reader.skip(version_size + 32).has_value(), "fixture identity skip failed");
result.packages.push_back({begin, version_length, reader.position()});
}
return result;
}
std::string package_json(std::string_view id, std::string_view version = "1.0.0",
std::string_view dependencies = "[]") {
return "{\"schema\":1,\"id\":\"" + std::string(id) + "\",\"version\":\"" + std::string(version) +
"\",\"dependencies\":" + std::string(dependencies) + ",\"exclusive_capabilities\":[],\"definitions\":[]}";
}
RulePackage load(std::string_view json) { return checked(load_rule_package("checkpoint-fixture.json", json)); }
struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Testing::Suite<CheckpointTests> {
[[= Void::Testing::tag("checkpoint")]] Test test_round_trip_preserves_identity_and_legacy_world_bytes();
[[= Void::Testing::tag("checkpoint")]] Test test_mid_carry_round_trip_continues_the_same_world();
[[= Void::Testing::tag("checkpoint")]] Test test_selected_rules_survive_catalog_reordering();
[[= Void::Testing::tag("checkpoint")]] Test test_missing_changed_and_duplicate_installed_packages();
[[= Void::Testing::tag("checkpoint")]] Test test_integrity_covers_the_entire_frame_and_rejects_truncation();
[[= Void::Testing::tag("checkpoint")]] Test test_bounded_metadata_and_complete_dependency_closure();
[[= Void::Testing::tag("checkpoint")]] Test test_valid_checksum_still_requires_valid_identity_and_world();
[[= Void::Testing::tag("checkpoint")]] Test test_world_body_larger_than_one_shot_hash_limit();
};
Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes() {
const auto catalog = checked(builtin_rule_packages());
const auto rules = checked(default_rules_manifest());
World world(43, 8, 9, 1, ExecutionMode::SerialReference);
static_cast<void>(world.spawn_agent({1, 1}));
static_cast<void>(world.add_job({6, 6}, 4));
for (int i = 0; i < 4; ++i) world.step();
const auto before = saved_state(world);
const auto bytes = encoded(world, rules);
auto restored = decoded(bytes, catalog);
require(restored.world_id == world_id && restored.city == 7 && restored.rules == rules,
"checkpoint lost stable world identity, city or rules");
require(saved_state(*restored.world) == before && saved_state(world) == before,
"checkpoint changed the original or restored canonical state");
require(bytes.substr(layout(bytes).body_begin, before.size()) == before,
"checkpoint did not use the existing world serialization");
require(before.substr(0, 8) == "SETTLERS" && static_cast<unsigned char>(before[8]) == 13,
"canonical serialization version changed");
require(encoded(*restored.world, restored.rules) == bytes, "re-encoding changed the checkpoint frame");
auto parallel = checked(decode_checkpoint(bytes, catalog, 6));
require(parallel.world->worker_count() == 6 && saved_state(*parallel.world) == before,
"checkpoint did not honor requested execution configuration");
auto nil = encode_checkpoint(world, {}, 7, rules);
auto no_city = encode_checkpoint(world, world_id, 0, rules);
require(!nil && nil.error().code == CheckpointError::InvalidIdentity &&
!no_city && no_city.error().code == CheckpointError::InvalidIdentity,
"encode accepted an invalid world or city identity");
}
Test CheckpointTests::test_mid_carry_round_trip_continues_the_same_world() {
const auto catalog = checked(builtin_rule_packages());
const auto rules = checked(default_rules_manifest());
auto world = make_first_colony(2);
require(world->apply_command({1, 1, CommandKind::PlaceBed, {16, 18}}).status == CommandStatus::Accepted,
"fixture bed placement failed");
bool carrying = false;
for (int i = 0; i < 300 && !carrying; ++i) {
world->step();
carrying = std::any_of(world->agents().begin(), world->agents().end(), [](const Agent& agent) {
return agent.inventory.item_count(ItemType::Wood) > 0 ||
agent.inventory.item_count(ItemType::Stone) > 0 ||
agent.inventory.item_count(ItemType::Cloth) > 0;
});
}
require(carrying, "fixture never carried construction material");
const auto before = saved_state(*world);
auto restored = decoded(encoded(*world, rules), catalog);
require(saved_state(*restored.world) == before, "mid-carry checkpoint changed reservations or inventory");
for (int i = 0; i < 300; ++i) {
world->step();
restored.world->step();
require(saved_state(*world) == saved_state(*restored.world), "checkpoint continuation diverged");
}
require(world->scenario_progress().assigned_beds >= 1, "checkpoint fixture never completed its bed");
}
Test CheckpointTests::test_selected_rules_survive_catalog_reordering() {
std::vector<RulePackage> catalog{
load(package_json("game.core")),
load(package_json("game.water", "1.0.0", R"([{"id":"game.core","version":"1.0.0"}])")),
load(package_json("game.unselected"))};
const std::array dry_selection{std::string{"game.core"}};
const std::array wet_selection{std::string{"game.water"}};
const auto dry = checked(resolve_rules(catalog, dry_selection));
const auto wet = checked(resolve_rules(catalog, wet_selection));
World world(12, 5, 5, 1, ExecutionMode::SerialReference);
const auto dry_frame = encoded(world, dry);
const auto wet_frame = encoded(world, wet);
std::reverse(catalog.begin(), catalog.end());
require(decoded(dry_frame, catalog).rules == dry && decoded(wet_frame, catalog).rules == wet && dry != wet,
"installed discovery order changed selected world rules");
require(decoded(wet_frame, catalog).rules.packages().size() == 2,
"unselected installed package entered the saved rules");
}
Test CheckpointTests::test_missing_changed_and_duplicate_installed_packages() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
std::vector<RulePackage> catalog{load(package_json("game.core"))};
const std::array selected{std::string{"game.core"}};
const auto rules = checked(resolve_rules(catalog, selected));
const auto bytes = encoded(world, rules);
rejected(bytes, {}, CheckpointError::RulesMismatch, "packages", "game.core");
for (std::string_view version : {"1.0.1", "1.0.0+build2"}) {
const std::array changed{load(package_json("game.core", version))};
rejected(bytes, changed, CheckpointError::RulesMismatch, "version", "game.core");
}
const std::array changed_content{load(R"({"schema":1,"id":"game.core","version":"1.0.0","dependencies":[],"exclusive_capabilities":["game.core:changed"],"definitions":[]})")};
rejected(bytes, changed_content, CheckpointError::RulesMismatch, "sha256", "game.core");
catalog.push_back(catalog.front());
rejected(bytes, catalog, CheckpointError::RulesMismatch, "id", "game.core");
}
Test CheckpointTests::test_integrity_covers_the_entire_frame_and_rejects_truncation() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, checked(default_rules_manifest()));
for (std::size_t length = 0; length < bytes.size(); ++length) {
require(!decode_checkpoint(std::string_view(bytes).substr(0, length), catalog), "truncated frame was accepted");
}
rejected(bytes + "x", catalog, CheckpointError::InvalidFrame, "lengths");
for (std::size_t offset : {std::size_t{24}, std::size_t{40}, std::size_t{48}, std::size_t{56},
layout(bytes).packages.front().begin + 2, layout(bytes).body_begin, bytes.size() - 1}) {
auto corrupt = bytes;
corrupt[offset] ^= 1;
rejected(corrupt, catalog, CheckpointError::IntegrityMismatch, "sha256");
}
auto unsupported = bytes;
change(unsupported, 8, checkpoint_version + 1);
rejected(unsupported, catalog, CheckpointError::UnsupportedVersion, "version");
auto wrong_magic = bytes;
wrong_magic[0] = 'X';
rejected(wrong_magic, catalog, CheckpointError::InvalidFrame, "magic");
}
Test CheckpointTests::test_bounded_metadata_and_complete_dependency_closure() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, checked(default_rules_manifest()));
const auto wire = layout(bytes);
auto huge_body = bytes;
change(huge_body, 16, std::numeric_limits<std::uint64_t>::max());
rejected(huge_body, catalog, CheckpointError::LimitExceeded, "lengths");
auto huge_metadata = bytes;
change(huge_metadata, 12, static_cast<std::uint32_t>(max_checkpoint_metadata_bytes + 1));
rejected(huge_metadata, catalog, CheckpointError::LimitExceeded, "lengths");
for (std::uint32_t count : {0U, 129U}) {
auto invalid = bytes;
change(invalid, 88, count);
rehash(invalid);
rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.packages");
}
for (std::uint16_t count : {std::uint16_t{0}, std::uint16_t{129}}) {
auto invalid = bytes;
change(invalid, wire.packages.front().begin, count);
rehash(invalid);
rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.id");
}
auto long_version = bytes;
change(long_version, wire.packages.front().version_length, std::uint16_t{257});
rehash(long_version);
rejected(long_version, catalog, CheckpointError::LimitExceeded, "rules.version");
const auto first = wire.packages.front();
const auto last = wire.packages.back();
auto duplicate = bytes;
const auto record = bytes.substr(first.begin, first.end - first.begin);
duplicate.replace(last.begin, last.end - last.begin, record);
change(duplicate, 12, static_cast<std::uint32_t>(wire.metadata_size + record.size() - (last.end - last.begin)));
rehash(duplicate);
rejected(duplicate, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.colony");
auto missing_dependency = bytes;
missing_dependency.erase(last.begin, last.end - last.begin);
change(missing_dependency, 12, static_cast<std::uint32_t>(wire.metadata_size - (last.end - last.begin)));
change(missing_dependency, 88, std::uint32_t{1});
rehash(missing_dependency);
rejected(missing_dependency, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.core");
auto bad_fingerprint = bytes;
bad_fingerprint[56] ^= 1;
rehash(bad_fingerprint);
rejected(bad_fingerprint, catalog, CheckpointError::RulesMismatch, "rules.fingerprint");
}
Test CheckpointTests::test_valid_checksum_still_requires_valid_identity_and_world() {
World world(4, 5, 5, 1, ExecutionMode::SerialReference);
const auto before = saved_state(world);
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, checked(default_rules_manifest()));
const auto wire = layout(bytes);
auto nil = bytes;
std::fill_n(nil.begin() + 24, 16, '\0');
rehash(nil);
rejected(nil, catalog, CheckpointError::InvalidIdentity, "world_id");
auto no_city = bytes;
change(no_city, 40, std::uint64_t{0});
rehash(no_city);
rejected(no_city, catalog, CheckpointError::InvalidIdentity, "city");
auto wrong_tick = bytes;
change(wrong_tick, 48, std::uint64_t{1});
rehash(wrong_tick);
rejected(wrong_tick, catalog, CheckpointError::InvalidWorld, "tick");
auto invalid_dimensions = bytes;
change(invalid_dimensions, wire.body_begin + 20, std::int32_t{0});
rehash(invalid_dimensions);
rejected(invalid_dimensions, catalog, CheckpointError::InvalidWorld, "world");
auto invalid_counter = bytes;
// The existing save13 header places next_agent_id after tick, four counters and hunger.
change(invalid_counter, wire.body_begin + 69, std::uint64_t{0});
rehash(invalid_counter);
rejected(invalid_counter, catalog, CheckpointError::InvalidWorld, "world");
auto inner_trailing = bytes;
inner_trailing.insert(wire.body_begin + static_cast<std::size_t>(wire.body_size), 1, 'x');
change(inner_trailing, 16, wire.body_size + 1);
rehash(inner_trailing);
rejected(inner_trailing, catalog, CheckpointError::InvalidWorld, "world");
require(saved_state(world) == before, "failed checkpoint preparation changed the live world");
}
Test CheckpointTests::test_world_body_larger_than_one_shot_hash_limit() {
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
for (int i = 0; i < 700'000; ++i) static_cast<void>(world.add_job({1, 1}, 1));
const auto rules = checked(default_rules_manifest());
const auto catalog = checked(builtin_rule_packages());
const auto bytes = encoded(world, rules);
require(layout(bytes).body_size > 16 * 1024 * 1024, "fixture did not exceed the one-shot hash limit");
auto restored = decoded(bytes, catalog);
require(restored.world->jobs().size() == world.jobs().size() &&
restored.world->jobs().back().id == world.jobs().back().id &&
saved_state(*restored.world) == saved_state(world),
"incremental checkpoint hash lost a large supported world");
}
} // namespace
+8 -8
View File
@@ -694,12 +694,12 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
CommandStatus::Accepted, "could not schedule the specialist jobs");
world.step();
for (std::size_t index = 0; index < 3; ++index) {
require(world.agents()[index].resource_node_index == index, "a specialist chose the wrong resource");
require(world.agents()[index].resource_node_id == world.resource_nodes()[index].id, "a specialist chose the wrong resource");
}
require(world.agents()[3].production_index == 0 && world.agents()[3].resource_node_index == no_entity_index,
require(world.agents()[3].production_index == 0 && world.agents()[3].resource_node_id == 0,
"the builder did not take the construction job");
require(assign(miner, Profession::Woodcutter) == CommandStatus::Accepted &&
world.agents()[2].resource_node_index == 2,
world.agents()[2].resource_node_id == world.resource_nodes()[2].id,
"changing professions interrupted a reserved mining job");
auto copy = save_roundtrip(world);
@@ -711,8 +711,8 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
require(save_contents(world) == save_contents(*copy), "specialist jobs diverged after loading");
const auto& resident = world.agents()[2];
if (resident.inventory.item_count(ItemType::Stone) > 0) delivered_stone = true;
if (resident.resource_node_index == 1) later_cut_wood = true;
if (later_cut_wood) require(resident.resource_node_index != 2, "a woodcutter kept selecting mining jobs");
if (resident.resource_node_id == world.resource_nodes()[1].id) later_cut_wood = true;
if (later_cut_wood) require(resident.resource_node_id != world.resource_nodes()[2].id, "a woodcutter kept selecting mining jobs");
}
require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood");
require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed");
@@ -812,7 +812,7 @@ Test CoreTests::test_field_growth_requires_a_worker() {
"could not assign the farmer");
world.step();
require(world.agents().front().state == AgentState::Travelling &&
world.agents().front().storage_index == no_entity_index &&
world.agents().front().storage_id == 0 &&
world.object_status(field, true) == CommandStatus::Busy, "the farmer did not reserve and walk to the field");
auto restored = save_roundtrip(world);
for (int i = 0; i < 100; ++i) {
@@ -840,7 +840,7 @@ Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() {
require(world.apply_command({1, 2, CommandKind::PlaceMine, {3, 4}}).status == CommandStatus::Accepted,
"failed to open a passage");
world.step();
require(world.agents().front().resource_node_index == 0 &&
require(world.agents().front().resource_node_id == world.resource_nodes()[0].id &&
world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache");
}
@@ -1041,7 +1041,7 @@ Test CoreTests::test_carpenter_delivers_the_door_before_installation() {
}
if (!delivered_door && resident.inventory.item_count(ItemType::WoodenDoor) == 1) {
delivered_door = true;
require(resident.state == AgentState::Hauling && resident.storage_index == 0 &&
require(resident.state == AgentState::Hauling && resident.storage_id == world->storages()[0].id &&
world->storages()[0].item_count(ItemType::WoodenDoor) == 0,
"the finished door appeared on the store before being delivered");
world = save_roundtrip(*world);
+219
View File
@@ -0,0 +1,219 @@
#include "settlement/core/world.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <atomic>
#include <chrono>
#include <future>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using namespace std::chrono_literals;
using Void::Testing::expect_throw;
using Void::Testing::require;
using Void::Testing::Test;
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
void populate_jobs(World& world) {
for (int i = 0; i < 12; ++i) {
static_cast<void>(world.spawn_agent({1 + i % 3, 1 + i / 3}));
static_cast<void>(world.add_job({15, 1 + i}, 3));
}
}
// The later task remains inside a borrowed world-stage callable while an
// earlier get() or a later submission fails. Returning from step must drain it.
void check_world_unwind(std::size_t phase, bool submit_failure) {
std::promise<void> blocked;
auto entered = blocked.get_future();
std::promise<void> release;
auto permit = release.get_future().share();
std::atomic<bool> completed{false};
WorkerPoolOptions options;
options.before_submit = [phase, submit_failure](std::size_t index) {
if (submit_failure && index == phase + 1) throw std::bad_alloc();
};
options.before_execute = [&](std::size_t index) {
if (index == phase + (submit_failure ? 0U : 1U)) {
blocked.set_value();
if (permit.wait_for(5s) != std::future_status::ready) {
throw std::runtime_error("test did not release a blocked world task");
}
completed.store(true);
}
if (!submit_failure && index == phase) throw std::runtime_error("injected task failure");
};
World world(55, 16, 16, 2, ExecutionMode::Parallel, options);
static_cast<void>(world.spawn_agent({1, 1}));
static_cast<void>(world.spawn_agent({1, 2}));
// Distinct nearest goals avoid a second arbitration batch before paths.
static_cast<void>(world.add_job({5, 1}, 3));
static_cast<void>(world.add_job({5, 2}, 3));
auto result = std::async(std::launch::async, [&] {
try {
world.step();
} catch (const std::bad_alloc&) {
return submit_failure && completed.load();
} catch (const std::runtime_error&) {
return !submit_failure && completed.load();
}
return false;
});
// Declared after result so failure always releases the task before joining.
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
require(entered.wait_for(5s) == std::future_status::ready);
require(result.wait_for(0s) == std::future_status::timeout);
release_task.release();
release.set_value();
require(result.wait_for(5s) == std::future_status::ready);
require(result.get());
}
struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing::Suite<ExecutorTests> {
[[= Void::Testing::tag("executor")]] Test test_limits_and_nested_submission();
[[= Void::Testing::tag("executor")]] Test test_capacity_retains_move_only_work_and_exceptions();
[[= Void::Testing::tag("executor")]] Test test_failed_callable_transfer_releases_capacity();
[[= Void::Testing::tag("executor")]] Test test_partial_start_failure_and_retry();
[[= Void::Testing::tag("executor")]] Test test_shutdown_drains_work();
[[= Void::Testing::tag("executor")]] Test test_world_drains_after_submission_failure();
[[= Void::Testing::tag("executor")]] Test test_world_drains_after_task_failure();
[[= Void::Testing::tag("executor")]] Test test_world_capacity_one_matches_reference();
};
Test ExecutorTests::test_limits_and_nested_submission() {
expect_throw<std::invalid_argument>([] { WorkerPool pool(1); });
expect_throw<std::invalid_argument>([] { WorkerPool pool(2, {.max_admitted = 0}); });
WorkerPool pool(2);
require(pool.thread_count() == 2);
auto nested = pool.submit([&] { return pool.submit([] { return 7; }).get(); });
expect_throw<std::logic_error>([&] { static_cast<void>(nested.get()); });
require(pool.submit([] { return 9; }).get() == 9);
}
Test ExecutorTests::test_capacity_retains_move_only_work_and_exceptions() {
std::promise<void> running;
auto entered = running.get_future();
std::promise<void> release;
auto permit = release.get_future().share();
WorkerPool pool(2, {.max_admitted = 1});
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
auto held = pool.submit([&] {
running.set_value();
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("test release timeout");
return 3;
});
require(entered.wait_for(5s) == std::future_status::ready);
const auto coordinator = std::this_thread::get_id();
std::atomic<int> executions{0};
auto answer = pool.submit([value = std::make_unique<int>(17), coordinator, &executions] {
require(std::this_thread::get_id() == coordinator);
++executions;
return *value;
});
require(answer.get() == 17 && executions.load() == 1);
auto failed = pool.submit([]() -> int { throw std::runtime_error("inline failure"); });
expect_throw<std::runtime_error>([&] { static_cast<void>(failed.get()); });
release_task.release();
release.set_value();
require(held.get() == 3);
auto threaded_failure = pool.submit([] { throw std::runtime_error("worker failure"); });
expect_throw<std::runtime_error>([&] { threaded_failure.get(); });
}
Test ExecutorTests::test_failed_callable_transfer_releases_capacity() {
struct FailingMove {
FailingMove() = default;
FailingMove(const FailingMove&) = delete;
FailingMove(FailingMove&&) { throw std::bad_alloc(); }
void operator()() const {}
};
WorkerPool pool(2, {.max_admitted = 1});
FailingMove function;
expect_throw<std::bad_alloc>([&] { static_cast<void>(pool.submit(std::move(function))); });
const auto coordinator = std::this_thread::get_id();
require(pool.submit([coordinator] { return std::this_thread::get_id() != coordinator; }).get());
}
Test ExecutorTests::test_partial_start_failure_and_retry() {
int calls = 0;
WorkerPoolOptions options;
options.before_worker_start = [&](std::size_t index) {
++calls;
if (index == 1) throw std::runtime_error("injected partial start failure");
};
expect_throw<std::runtime_error>([&] { WorkerPool failed(3, options); });
require(calls == 2);
WorkerPool retry(3);
require(retry.thread_count() == 3 && retry.submit([] { return 4; }).get() == 4);
}
Test ExecutorTests::test_shutdown_drains_work() {
std::promise<void> running;
auto entered = running.get_future();
std::promise<void> release;
auto permit = release.get_future().share();
std::atomic<int> completed{0};
auto pool = std::make_unique<WorkerPool>(2);
auto work = pool->submit([&] {
running.set_value();
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("test release timeout");
++completed;
});
std::promise<void> destroying;
auto started = destroying.get_future();
auto destruction = std::async(std::launch::async, [&, owned = std::move(pool)]() mutable {
destroying.set_value();
owned.reset();
return completed.load();
});
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
require(entered.wait_for(5s) == std::future_status::ready);
require(started.wait_for(5s) == std::future_status::ready);
require(destruction.wait_for(10ms) == std::future_status::timeout);
release_task.release();
release.set_value();
require(destruction.wait_for(5s) == std::future_status::ready);
require(destruction.get() == 1 && work.wait_for(0s) == std::future_status::ready);
work.get();
}
Test ExecutorTests::test_world_drains_after_submission_failure() {
for (std::size_t phase : {0U, 2U, 4U}) check_world_unwind(phase, true);
}
Test ExecutorTests::test_world_drains_after_task_failure() {
for (std::size_t phase : {0U, 2U, 4U}) check_world_unwind(phase, false);
}
Test ExecutorTests::test_world_capacity_one_matches_reference() {
World reference(77, 20, 20, 1, ExecutionMode::SerialReference);
populate_jobs(reference);
for (std::size_t workers : {2U, 6U, 12U}) {
World candidate(77, 20, 20, workers, ExecutionMode::Parallel, {.max_admitted = 1});
populate_jobs(candidate);
// Each candidate is paired with its own uninterrupted serial run.
World serial(77, 20, 20, 1, ExecutionMode::SerialReference);
populate_jobs(serial);
require(bytes(serial) == bytes(reference));
for (int tick = 0; tick < 60; ++tick) {
serial.step();
candidate.step();
require(bytes(candidate) == bytes(serial));
}
require(candidate.jobs_completed() == 12);
}
}
} // namespace
+258
View File
@@ -0,0 +1,258 @@
#include "settlement/core/checkpoint.hpp"
#include "settlement/core/world.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <array>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, const char* message = "identity invariant failed") {
if (!condition) throw std::runtime_error(message);
}
constexpr auto last_counter = std::numeric_limits<std::uint64_t>::max();
// Format 13 header, five tick/stat counters, hunger and four next-ID counters.
constexpr std::size_t next_node_offset = 85;
constexpr std::size_t next_storage_offset = 93;
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
void put_u64(std::string& data, std::size_t at, std::uint64_t value) {
require(at + 8 <= data.size(), "fixture offset outside save");
for (unsigned i = 0; i < 8; ++i) data[at + i] = static_cast<char>((value >> (i * 8)) & 255);
}
std::unique_ptr<World> restore(const std::string& data, std::size_t workers = 1) {
std::istringstream input(data, std::ios::binary);
return World::read_save(input, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
}
CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
return world.apply_command({1, world.next_command_sequence(1), kind, cell, value}).status;
}
void compare_continuation(World& original, int ticks) {
const auto initial = bytes(original);
std::array copies{restore(initial, 1), restore(initial, 2), restore(initial, 6), restore(initial, 12)};
const auto catalog = builtin_rule_packages();
const auto rules = default_rules_manifest();
require(catalog.has_value() && rules.has_value(), "built-in rule fixture failed");
const auto id = Void::Uuid::try_v4();
require(id.has_value(), "UUID fixture failed");
const auto checkpoint = encode_checkpoint(original, *id, 1, *rules);
require(checkpoint.has_value(), "checkpoint encode failed");
auto candidate = decode_checkpoint(*checkpoint, *catalog, 1, ExecutionMode::SerialReference);
require(candidate.has_value(), "checkpoint decode failed");
const auto held = original.capture();
for (int tick = 0; tick < ticks; ++tick) {
original.step();
const auto expected = bytes(original);
for (auto& copy : copies) {
copy->step();
require(bytes(*copy) == expected, "ID-linked continuation differs across execution modes");
}
candidate->world->step();
require(bytes(*candidate->world) == expected, "checkpoint continuation changed ID links");
require(bytes(*held) == initial, "held snapshot changed after ID-linked world advanced");
}
}
template<class Work>
void require_exhausted(World& world, Work work) {
const auto before = bytes(world);
bool overflow = false;
try { work(); } catch (const std::overflow_error&) { overflow = true; }
require(overflow && bytes(world) == before, "exhausted factory mutated state or failed to report overflow");
}
struct [[= Void::Testing::name("IdentityTests")]] IdentityTests : Void::Testing::Suite<IdentityTests> {
[[= Void::Testing::tag("identity")]] Test test_active_haul_survives_earlier_storage_and_node_deletion();
[[= Void::Testing::tag("identity")]] Test test_construction_stops_retain_ids_after_earlier_storage_deletion();
[[= Void::Testing::tag("identity")]] Test test_pantry_and_unstored_tending_restore_stable_ids();
[[= Void::Testing::tag("identity")]] Test test_carpenter_output_retains_its_storage_id();
[[= Void::Testing::tag("identity")]] Test test_factory_counters_stop_before_max_without_mutation();
[[= Void::Testing::tag("identity")]] Test test_command_counters_stop_before_max_without_terrain_changes();
[[= Void::Testing::tag("identity")]] Test test_invalid_legacy_positions_fail_before_candidate_publication();
};
Test IdentityTests::test_active_haul_survives_earlier_storage_and_node_deletion() {
World world(42, 32, 32, 1, ExecutionMode::SerialReference);
const auto unused_store = world.add_storage({1, 1}, 10, StorageKind::Pantry);
const auto destination = world.add_storage({28, 4}, 30);
const auto unused_node = world.add_resource_node({30, 25}, ItemType::Stone, 3);
const auto source = world.add_resource_node({6, 4}, ItemType::Wood, 5);
const auto resident = world.spawn_agent({4, 4});
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Woodcutter), {}, resident}).status == CommandStatus::Accepted);
world.step();
require(world.agents().front().resource_node_id == source &&
world.agents().front().storage_id == destination, "fixture did not reserve the later node and store");
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted &&
command(world, CommandKind::DemolishObject, {30, 25}) == CommandStatus::Accepted);
require(world.find_storage(unused_store) == nullptr && world.find_resource_node(unused_node) == nullptr);
require(world.agents().front().resource_node_id == source &&
world.agents().front().storage_id == destination, "deleting earlier records changed durable links");
require(world.find_storage(0) == nullptr && world.find_resource_node(last_counter) == nullptr);
for (int tick = 0; tick < 40 && world.agents().front().state != AgentState::Hauling; ++tick) world.step();
require(world.agents().front().state == AgentState::Hauling &&
world.agents().front().inventory.item_count(ItemType::Wood) == 1);
compare_continuation(world, 80);
require(world.find_storage(destination)->item_count(ItemType::Wood) > 0, "cargo missed its stable destination");
}
Test IdentityTests::test_construction_stops_retain_ids_after_earlier_storage_deletion() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(world.add_storage({1, 1}, 10, StorageKind::Pantry));
const auto planks = world.add_storage({3, 3}, 20);
const auto blocks = world.add_storage({8, 3}, 20);
world.stock_storage(planks, ItemType::Plank, 3);
world.stock_storage(blocks, ItemType::StoneBlock, 2);
static_cast<void>(world.spawn_agent({2, 3}));
world.queue_production({14, 3}, RecipeId::BuildCabin);
world.step();
const auto& order = world.production_orders().front();
require(order.delivery_stops.size() == 2 && order.delivery_stops[0].storage_id == planks &&
order.delivery_stops[1].storage_id == blocks, "construction did not retain both actual store IDs");
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
require(order.materials[0].storage_id == planks && order.materials[1].storage_id == blocks);
for (int tick = 0; tick < 20 && order.collected_stops == 0; ++tick) world.step();
require(order.collected_stops == 1 && !world.agents().front().inventory.empty());
compare_continuation(world, 65);
require(order.state == JobState::Completed, "multi-store construction did not finish");
}
Test IdentityTests::test_pantry_and_unstored_tending_restore_stable_ids() {
World meal(44, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(meal.add_storage({1, 1}, 5));
const auto pantry = meal.add_storage({28, 4}, 50, StorageKind::Pantry);
meal.stock_storage(pantry, ItemType::Berries, 40);
static_cast<void>(meal.spawn_agent({4, 4}));
meal.enable_hunger();
for (int tick = 0; tick < 500 && meal.agents().front().state != AgentState::GoingToEat; ++tick) meal.step();
require(meal.agents().front().storage_id == pantry);
require(command(meal, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
compare_continuation(meal, 50);
require(meal.meals_eaten() > 0);
World tending(45, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(tending.spawn_agent({2, 3}));
static_cast<void>(tending.add_resource_node({30, 30}, ItemType::Stone, 1));
require(command(tending, CommandKind::PlaceBerryField, {9, 3}) == CommandStatus::Accepted);
tending.step();
require(tending.agents().front().resource_node_id == tending.resource_nodes().back().id &&
tending.agents().front().storage_id == 0, "tending acquired an unrelated storage");
require(command(tending, CommandKind::DemolishObject, {30, 30}) == CommandStatus::Accepted);
compare_continuation(tending, 100);
require(tending.resource_nodes().front().quantity > 0);
}
Test IdentityTests::test_carpenter_output_retains_its_storage_id() {
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(world.add_storage({1, 1}, 10, StorageKind::Pantry));
const auto materials = world.add_storage({2, 3}, 10);
world.stock_storage(materials, ItemType::Wood, 2);
const auto carpenter = world.spawn_agent({2, 2});
world.start_scenario({8, 3});
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
world.queue_production({8, 3}, RecipeId::CraftWoodenDoor);
world.step();
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
for (int tick = 0; tick < 100 &&
world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 0; ++tick) world.step();
require(world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 1 &&
world.agents().front().storage_id == materials && world.find_storage(materials)->reserved_slots == 1,
"carpenter output lost its persistent reserved destination");
compare_continuation(world, 30);
require(world.find_storage(materials)->item_count(ItemType::WoodenDoor) == 1 &&
world.find_storage(materials)->reserved_slots == 0, "carpenter delivered into the wrong storage");
}
Test IdentityTests::test_factory_counters_stop_before_max_without_mutation() {
World empty(46, 8, 8, 1, ExecutionMode::SerialReference);
for (const auto offset : {next_node_offset, next_storage_offset}) {
auto data = bytes(empty);
put_u64(data, offset, last_counter - 1);
auto world = restore(data);
if (offset == next_node_offset) {
require(world->add_resource_node({2, 2}, ItemType::Wood, 1) == last_counter - 1);
world = restore(bytes(*world));
require_exhausted(*world, [&] { static_cast<void>(world->add_resource_node({3, 3}, ItemType::Stone, 1)); });
} else {
require(world->add_storage({2, 2}, 10) == last_counter - 1);
world = restore(bytes(*world));
require_exhausted(*world, [&] { static_cast<void>(world->add_storage({3, 3}, 10)); });
}
put_u64(data, offset, last_counter);
world = restore(data);
if (offset == next_node_offset) {
require_exhausted(*world, [&] { static_cast<void>(world->add_resource_node({2, 2}, ItemType::Wood, 1)); });
} else {
require_exhausted(*world, [&] { static_cast<void>(world->add_storage({2, 2}, 10)); });
}
}
}
Test IdentityTests::test_command_counters_stop_before_max_without_terrain_changes() {
constexpr std::array kinds{CommandKind::PlaceBerryField, CommandKind::PlaceTreePlot,
CommandKind::PlaceFlaxField, CommandKind::PlaceMine, CommandKind::PlaceStorage};
for (const auto kind : kinds) {
World initial(47, 8, 8, 1, ExecutionMode::SerialReference);
static_cast<void>(initial.spawn_agent({2, 2}));
const bool mine = kind == CommandKind::PlaceMine;
if (mine) {
initial.set_blocked({4, 4});
initial.set_blocked({5, 4});
}
const auto offset = kind == CommandKind::PlaceStorage ? next_storage_offset : next_node_offset;
auto data = bytes(initial);
put_u64(data, offset, last_counter);
auto world = restore(data);
const auto before = bytes(*world);
require(command(*world, kind, {4, 4}) == CommandStatus::Busy && bytes(*world) == before &&
world->next_command_sequence(1) == 1, "exhausted command changed world or consumed sequence");
if (mine) require(!world->is_walkable({4, 4}));
put_u64(data, offset, last_counter - 1);
world = restore(data);
require(command(*world, kind, {4, 4}) == CommandStatus::Accepted);
require(kind == CommandKind::PlaceStorage ? world->storages().back().id == last_counter - 1 :
world->resource_nodes().back().id == last_counter - 1);
world = restore(bytes(*world));
const auto exhausted = bytes(*world);
require(command(*world, kind, {5, 4}) == CommandStatus::Busy && bytes(*world) == exhausted &&
world->next_command_sequence(1) == 2, "second exhausted command changed state");
if (mine) require(!world->is_walkable({5, 4}));
}
}
Test IdentityTests::test_invalid_legacy_positions_fail_before_candidate_publication() {
World world(48, 8, 8, 1, ExecutionMode::SerialReference);
static_cast<void>(world.spawn_agent({2, 2}));
static_cast<void>(world.add_resource_node({3, 3}, ItemType::Wood, 2));
static_cast<void>(world.add_storage({4, 4}, 10));
const auto original = bytes(world);
// The first resident has an empty route. Its two legacy links follow the
// 101-byte prefix, cell mask, resident count and 41 bytes of resident fields.
constexpr std::size_t node_link = 101 + 8 * 8 + 4 + 41;
for (const auto at : {node_link, node_link + 8}) {
auto invalid = original;
put_u64(invalid, at, 2); // One-based position two, with a single record.
bool rejected = false;
try { static_cast<void>(restore(invalid)); } catch (const std::runtime_error&) { rejected = true; }
require(rejected && bytes(world) == original, "dangling legacy link escaped candidate validation");
}
}
} // namespace
+285
View File
@@ -0,0 +1,285 @@
#include "settlement/core/colony_profile.hpp"
#include <Void/Core/Hash.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
template<class T, class E>
T checked(std::expected<T, E> result) {
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string saved(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return std::move(stream).str();
}
std::string checkpoint(const World& world, const WorldCheckpoint& identity) {
return checked(encode_checkpoint(world, identity.world_id, identity.city, identity.rules));
}
void command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
GridPosition target = {}, AgentId resident = 0) {
const auto receipt = world.apply_command(
{1, world.next_command_sequence(1), kind, cell, value, target, resident});
require(receipt.status == CommandStatus::Accepted, "profile command was rejected");
}
std::uint64_t stock(const World& world, ItemType item) {
std::uint64_t count = 0;
for (const auto& storage : world.storages()) count += storage.item_count(item);
for (const auto& agent : world.agents()) count += agent.inventory.item_count(item);
return count;
}
void queue_three_beds(World& world) {
command(world, CommandKind::PlaceBed, {16, 18});
command(world, CommandKind::PlaceBed, {17, 18}, 1);
command(world, CommandKind::PlaceBed, {18, 18});
command(world, CommandKind::SetForaging, {14, 12}, 1);
command(world, CommandKind::SetForaging, {13, 14}, 1);
}
std::size_t count_recipe(const World& world, RecipeId recipe) {
return static_cast<std::size_t>(std::count_if(
world.production_orders().begin(), world.production_orders().end(),
[recipe](const auto& order) { return order.recipe == recipe; }));
}
std::string from_hex(std::string_view hex) {
const auto digit = [](char value) {
return value <= '9' ? value - '0' : value - 'a' + 10;
};
std::string bytes;
for (std::size_t i = 0; i < hex.size(); i += 2) {
bytes.push_back(static_cast<char>(digit(hex[i]) * 16 + digit(hex[i + 1])));
}
return bytes;
}
// Produced by the pre-profile core and header at 60154bd, SHA-256
// 8936352f8f8c939f866195bd434fe58c3bcf9ace49202c937c9cb2a026583d48.
// Checkpoint schema 1 holds an active default-manifest world with simple beds.
const std::string legacy_simple_checkpoint = from_hex(
"53544843484b505401000000b6000000b7000000000000000102030405064708890a0b0c0d0e0f10"
"0100000000000000000000000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72d"
"c0984cfc62cd83d1020000001100736574746c656d656e742e636f6c6f6e790500312e302e3008e1"
"8a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c0890f00736574746c656d65"
"6e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530d0000002f010000000000000500000005000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000000010100000000"
"00000001000000000000000100000000000000010000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000100000002000000"
"0200000000000000000000000000000000000000000000000000000000ada3be851474c1ab6aa6bb"
"0efc1a3cc103430f5b1a69fd602ec6bf02b93f98c6");
struct [[= Void::Testing::name("ProfileTests")]] ProfileTests : Void::Testing::Suite<ProfileTests> {
[[= Void::Testing::tag("profile")]] Test test_compiled_profiles_resolve_exact_content();
[[= Void::Testing::tag("profile")]] Test test_both_first_colonies_complete_with_the_selected_material_chain();
[[= Void::Testing::tag("profile")]] Test test_furnished_rooms_use_the_selected_bed_recipe();
[[= Void::Testing::tag("profile")]] Test test_profiles_replay_and_resume_mid_delivery();
[[= Void::Testing::tag("profile")]] Test test_historical_default_simple_and_inactive_worlds_keep_their_mode();
[[= Void::Testing::tag("profile")]] Test test_supported_profile_gate_rejects_mismatches_without_mutation();
[[= Void::Testing::tag("profile")]] Test test_scenario_profile_cannot_change_after_start();
};
Test ProfileTests::test_compiled_profiles_resolve_exact_content() {
const auto original = checked(colony_rules(ColonyProfile::Default));
const auto planks = checked(colony_rules(ColonyProfile::PlankBeds));
require(original.manifest() == checked(default_rules_manifest()) &&
original.bed_mode() == BedConstructionMode::Staged, "default compilation changed");
require(planks.manifest().packages().size() == 3 && planks.bed_mode() == BedConstructionMode::Plank,
"optional package did not select plank construction");
auto catalog = checked(builtin_rule_packages());
std::reverse(catalog.begin(), catalog.end());
const std::array selected{std::string{"settlement.plankbeds"}};
const auto shuffled = checked(resolve_rules(catalog, selected));
require(shuffled == planks.manifest() &&
checked(compile_colony_rules(shuffled)).profile() == ColonyProfile::PlankBeds,
"catalog order changed the compiled profile");
require(!colony_rules(static_cast<ColonyProfile>(255)), "unknown profile compiled");
require(!make_colony_checkpoint(ColonyProfile::Default, 1),
"parallel one-worker colony was created");
}
Test ProfileTests::test_both_first_colonies_complete_with_the_selected_material_chain() {
for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) {
auto candidate = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference));
require(!candidate.world_id.is_nil() && candidate.city == 1, "colony identity is missing");
require(validate_colony_checkpoint(candidate).has_value(), "new colony profile failed validation");
auto& world = *candidate.world;
queue_three_beds(world);
const bool staged = profile == ColonyProfile::Default;
require(world.staged_beds() == staged &&
count_recipe(world, RecipeId::SawPlank) == (staged ? 0U : 3U),
"bed command ignored its selected recipe");
for (const auto& order : world.production_orders()) {
if (order.recipe != RecipeId::BuildBed) continue;
require(order.bed_material() == (staged ?
(order.bed_base == BedBase::Stone ? ItemType::Stone : ItemType::Wood) : ItemType::Plank),
"material preview does not match the enacted profile");
}
for (int tick = 0; tick < 1200 && !world.scenario_progress().completed; ++tick) world.step();
require(world.scenario_progress().completed && world.scenario_progress().assigned_beds == 3,
"selected first-colony profile did not complete the three-bed food objective");
require(stock(world, ItemType::Cloth) == (staged ? 6U : 12U) &&
stock(world, ItemType::Stone) == (staged ? 5U : 6U),
"bed profile consumed the wrong cloth or foundation material");
require(std::all_of(world.production_orders().begin(), world.production_orders().end(),
[](const auto& order) { return order.state == JobState::Completed; }),
"selected profile left an unfinished prerequisite");
}
}
Test ProfileTests::test_furnished_rooms_use_the_selected_bed_recipe() {
for (auto mode : {BedConstructionMode::Staged, BedConstructionMode::Plank}) {
World world(64, 20, 18, 1, ExecutionMode::SerialReference);
const auto builder = world.spawn_agent({5, 3});
const auto carpenter = world.spawn_agent({3, 3});
const auto materials = world.add_storage({3, 4}, 128);
world.stock_storage(materials, ItemType::Wood, 80);
world.stock_storage(materials, ItemType::Stone, 6);
world.stock_storage(materials, ItemType::Cloth, 2);
const auto food = world.add_storage({2, 4}, 200, StorageKind::Pantry);
world.stock_storage(food, ItemType::Berries, 200);
world.start_scenario({4, 3}, mode);
command(world, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Builder), {}, builder);
command(world, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter);
const RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, RoomTemplate::Miner};
command(world, CommandKind::PlaceRoom, plan.first, plan.placement_value(), plan.last);
require(count_recipe(world, RecipeId::SawPlank) == (mode == BedConstructionMode::Plank ? 1U : 0U),
"furnished room ignored the optional plank prerequisite");
for (int tick = 0; tick < 2200 && world.scenario_progress().assigned_beds == 0; ++tick) world.step();
require(world.scenario_progress().assigned_beds == 1, "room bed did not complete");
require(stock(world, ItemType::Cloth) == (mode == BedConstructionMode::Plank ? 2U : 0U),
"furnished room consumed the wrong bedding");
}
}
Test ProfileTests::test_profiles_replay_and_resume_mid_delivery() {
const auto catalog = checked(builtin_rule_packages());
for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) {
auto initial = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference));
queue_three_beds(*initial.world);
const auto initial_bytes = checkpoint(*initial.world, initial);
std::vector<WorldCheckpoint> runs;
for (std::size_t workers : {2U, 6U, 12U}) {
runs.push_back(checked(decode_checkpoint(initial_bytes, catalog, workers)));
}
std::shared_ptr<const World> held;
std::string held_bytes;
bool resumed = false;
for (int tick = 0; tick < 500; ++tick) {
initial.world->step();
for (auto& run : runs) run.world->step();
const auto expected = checkpoint(*initial.world, initial);
for (const auto& run : runs) {
require(checkpoint(*run.world, run) == expected, "profile parallel replay diverged");
}
if (!resumed && std::any_of(initial.world->agents().begin(), initial.world->agents().end(),
[](const auto& agent) {
return agent.state == AgentState::Hauling &&
(agent.inventory.item_count(ItemType::Wood) != 0 ||
agent.inventory.item_count(ItemType::Stone) != 0 ||
agent.inventory.item_count(ItemType::Plank) != 0 ||
agent.inventory.item_count(ItemType::Cloth) != 0);
})) {
held = initial.world->capture();
held_bytes = saved(*held);
runs.push_back(checked(decode_checkpoint(expected, catalog, 1, ExecutionMode::SerialReference)));
resumed = true;
}
}
require(resumed && saved(*held) == held_bytes, "held material snapshot changed or was never captured");
require(initial.world->scenario_progress().assigned_beds == 3, "replay profile failed its bed objective");
}
}
Test ProfileTests::test_historical_default_simple_and_inactive_worlds_keep_their_mode() {
const auto catalog = checked(builtin_rule_packages());
auto legacy = checked(decode_checkpoint(legacy_simple_checkpoint, catalog, 1, ExecutionMode::SerialReference));
require(legacy.world->scenario_active() && !legacy.world->staged_beds(),
"authentic schema-1 fixture lost its historical mode");
const auto before = saved(*legacy.world);
require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == before,
"default profile gate rewrote a historical simple colony");
auto current = checked(decode_checkpoint(checkpoint(*legacy.world, legacy), catalog, 1, ExecutionMode::SerialReference));
require(validate_colony_checkpoint(current).has_value() && saved(*current.world) == before,
"resaving historical defaults changed their enacted rules");
// The corresponding v2 raw format omitted the staged flag and used an FNV footer.
auto raw_v2 = before;
raw_v2[8] = 2;
raw_v2.pop_back();
auto digest = Void::Hash::fnv1a64_offset_basis;
digest = Void::Hash::fnv1a64_update(digest, std::as_bytes(std::span{raw_v2}));
for (unsigned shift = 0; shift < 64; shift += 8) raw_v2.push_back(static_cast<char>(digest >> shift));
std::istringstream input(raw_v2, std::ios::binary);
legacy.world = World::read_save(input, 1, ExecutionMode::SerialReference);
require(legacy.world->scenario_active() && !legacy.world->staged_beds() &&
validate_colony_checkpoint(legacy).has_value(), "active raw-v2 import lost default compatibility");
legacy.world = std::make_unique<World>(17, 5, 5, 1, ExecutionMode::SerialReference);
const auto inactive_before = saved(*legacy.world);
require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == inactive_before,
"inactive historical default was rejected or modified");
}
Test ProfileTests::test_supported_profile_gate_rejects_mismatches_without_mutation() {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 1, ExecutionMode::SerialReference));
const auto before = saved(*candidate.world);
candidate.rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest();
auto invalid = validate_colony_checkpoint(candidate);
require(!invalid && invalid.error().package == "settlement.plankbeds" &&
saved(*candidate.world) == before, "staged world with plank rules was accepted or changed");
auto catalog = checked(builtin_rule_packages());
auto altered = std::string(catalog.back().canonical_json());
const auto work = altered.find("\"work_ticks\":14");
require(work != std::string::npos, "plank fixture has no work duration");
altered.replace(work, std::string_view{"\"work_ticks\":14"}.size(), "\"work_ticks\":15");
catalog.back() = checked(load_rule_package("altered/plankbeds", altered));
const std::array selected{std::string{"settlement.plankbeds"}};
candidate.rules = checked(resolve_rules(catalog, selected));
require(!validate_colony_checkpoint(candidate) && saved(*candidate.world) == before,
"modified recipe content was accepted as an implemented profile");
const std::array core_only{std::string{"settlement.core"}};
require(!compile_colony_rules(checked(resolve_rules(catalog, core_only))), "incomplete profile compiled");
const auto extra = checked(load_rule_package("extra",
R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})"));
catalog.push_back(extra);
const std::array with_extra{std::string{"settlement.colony"}, std::string{"game.extra"}};
require(!compile_colony_rules(checked(resolve_rules(catalog, with_extra))), "unimplemented package compiled");
require(!resolve_rules(catalog, std::array{std::string{"missing.package"}}), "missing package resolved");
}
Test ProfileTests::test_scenario_profile_cannot_change_after_start() {
World world(17, 5, 5, 1, ExecutionMode::SerialReference);
const auto before = saved(world);
Void::Testing::expect_throw<std::invalid_argument>([&] {
world.start_scenario({2, 2}, static_cast<BedConstructionMode>(255));
});
require(saved(world) == before, "invalid mode changed the world");
world.start_scenario({2, 2}, BedConstructionMode::Plank);
const auto started = saved(world);
Void::Testing::expect_throw<std::invalid_argument>([&] { world.start_scenario({2, 2}); });
require(saved(world) == started, "started colony changed its creation profile");
}
} // namespace
+324
View File
@@ -0,0 +1,324 @@
#include "settlement/core/world.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::expect_throw;
using Void::Testing::Test;
struct ExecutionConfig {
std::size_t workers;
ExecutionMode mode;
};
constexpr std::array execution_configs{
ExecutionConfig{1, ExecutionMode::SerialReference},
ExecutionConfig{2, ExecutionMode::Parallel},
ExecutionConfig{6, ExecutionMode::Parallel},
ExecutionConfig{12, ExecutionMode::Parallel},
};
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config,
WorkerPoolOptions options = {}) {
std::istringstream stream(bytes, std::ios::binary);
auto world = World::read_save(stream, config.workers, config.mode, std::move(options));
require(world->worker_count() == config.workers, "load changed the requested worker count");
return world;
}
// Every run starts from one serialized fixture. The reference stays alive when
// checkpoint copies are added, so reload is checked against uninterrupted work.
class ReplayWorlds {
public:
explicit ReplayWorlds(const World& initial, std::size_t capacity = 4096)
: options_{.max_admitted = capacity} {
const auto bytes = saved_state(initial);
reference = load_state(bytes, execution_configs.front(), options_);
require(saved_state(*reference) == bytes, "loading changed the starting fixture");
for (std::size_t i = 1; i < execution_configs.size(); ++i) {
runs_.push_back({execution_configs[i], false, load_state(bytes, execution_configs[i], options_)});
}
compare();
}
void step() {
reference->step();
for (auto& run : runs_) run.world->step();
compare();
}
void command(const PlayerCommand& command, CommandStatus expected_status,
std::uint64_t expected_tick, std::uint64_t expected_revision) {
const auto check = [&](World& world) {
const auto result = world.apply_command(command);
require(result.status == expected_status && result.tick == expected_tick &&
result.revision == expected_revision,
"command receipt differs from the recorded status, tick or revision");
};
check(*reference);
for (auto& run : runs_) check(*run.world);
compare();
}
void checkpoint() {
const auto bytes = saved_state(*reference);
for (auto config : execution_configs) {
runs_.push_back({config, true, load_state(bytes, config, options_)});
}
compare();
}
std::unique_ptr<World> reference;
private:
struct Run {
ExecutionConfig config;
bool reloaded;
std::unique_ptr<World> world;
};
void compare() const {
const auto expected = saved_state(*reference);
for (const auto& run : runs_) {
const auto actual = saved_state(*run.world);
if (actual == expected) continue;
const auto mismatch = std::mismatch(expected.begin(), expected.end(), actual.begin(), actual.end());
const auto offset = static_cast<std::size_t>(mismatch.first - expected.begin());
throw std::runtime_error("replay diverged at tick " + std::to_string(reference->tick()) +
", workers " + std::to_string(run.config.workers) +
(run.reloaded ? ", reloaded" : ", uninterrupted") +
", byte " + std::to_string(offset) +
", path searches " + std::to_string(reference->path_searches()) + "/" +
std::to_string(run.world->path_searches()) + ", path nodes " +
std::to_string(reference->path_nodes_visited()) + "/" +
std::to_string(run.world->path_nodes_visited()));
}
}
WorkerPoolOptions options_;
std::vector<Run> runs_;
};
struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite<ReplayTests> {
[[= Void::Testing::tag("replay")]] Test test_execution_configuration_and_empty_world();
[[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work();
[[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes();
[[= Void::Testing::tag("replay")]] Test test_recorded_colony_commands_and_loaded_delivery();
[[= Void::Testing::tag("replay")]] Test test_recorded_colony_at_capacity_one();
[[= Void::Testing::tag("replay")]] Test test_last_meal_has_one_winner_and_one_consumer();
};
Test ReplayTests::test_execution_configuration_and_empty_world() {
World initial(20261202, 5, 5);
const auto bytes = saved_state(initial);
constexpr std::array invalid_configs{
ExecutionConfig{0, ExecutionMode::Parallel},
ExecutionConfig{1, ExecutionMode::Parallel},
ExecutionConfig{max_worker_count + 1, ExecutionMode::Parallel},
ExecutionConfig{0, ExecutionMode::SerialReference},
ExecutionConfig{2, ExecutionMode::SerialReference},
ExecutionConfig{max_worker_count + 1, ExecutionMode::SerialReference},
ExecutionConfig{2, static_cast<ExecutionMode>(255)},
};
for (auto config : invalid_configs) {
expect_throw<std::invalid_argument>([&] {
World invalid(20261202, 5, 5, config.workers, config.mode);
});
expect_throw<std::invalid_argument>([&] { static_cast<void>(load_state(bytes, config)); });
}
expect_throw<std::invalid_argument>([] { World legacy(20261202, 5, 5, 1); });
World maximum(20261202, 5, 5, max_worker_count);
require(maximum.worker_count() == max_worker_count, "maximum parallel count was rejected");
require(saved_state(maximum) == bytes, "execution configuration changed the save bytes");
auto restored_maximum = load_state(bytes, {max_worker_count, ExecutionMode::Parallel});
require(saved_state(*restored_maximum) == bytes, "maximum-count load changed game state");
ReplayWorlds replay(initial);
for (int tick = 0; tick < 4; ++tick) replay.step();
require(replay.reference->tick() == 4 && replay.reference->agents().empty() &&
replay.reference->jobs_completed() == 0,
"an empty world failed to advance without residents");
}
Test ReplayTests::test_one_resident_completes_work() {
World initial(73, 8, 8);
static_cast<void>(initial.spawn_agent({1, 1}));
static_cast<void>(initial.add_job({6, 5}, 3));
ReplayWorlds replay(initial);
for (int tick = 0; tick < 20; ++tick) replay.step();
require(replay.reference->jobs_completed() == 1 &&
replay.reference->jobs().front().state == JobState::Completed &&
replay.reference->agents().front().position == GridPosition{6, 5},
"one resident failed to travel and complete the job");
}
Test ReplayTests::test_competing_jobs_retry_unreachable_routes() {
World initial(83, 12, 8);
for (int y = 0; y < 8; ++y) initial.set_blocked({5, y});
const auto unreachable = initial.add_job({6, 3}, 2);
std::array<JobId, 3> reachable{};
for (int i = 0; i < 3; ++i) {
static_cast<void>(initial.spawn_agent({3, 3}));
reachable[static_cast<std::size_t>(i)] = initial.add_job({0, 3 + i}, 2);
}
ReplayWorlds replay(initial);
replay.step();
for (std::size_t i = 0; i < reachable.size(); ++i) {
require(replay.reference->agents()[i].current_job == reachable[i],
"the job winner changed or an unreachable job prevented a retry");
}
require(replay.reference->path_searches() >= 6,
"the fixture did not attempt the unreachable route for every contender");
for (int tick = 1; tick < 20; ++tick) replay.step();
require(replay.reference->jobs_completed() == 3 &&
replay.reference->jobs().front().id == unreachable &&
replay.reference->jobs().front().state == JobState::Available,
"reachable work failed to complete or the sealed job was completed");
require(std::all_of(replay.reference->jobs().begin() + 1, replay.reference->jobs().end(),
[](const WorkJob& job) { return job.state == JobState::Completed; }),
"the completed count hid an unfinished reachable job");
}
void replay_colony_journal(std::size_t capacity) {
const auto initial = make_first_colony(2);
ReplayWorlds replay(*initial, capacity);
struct RecordedCommand {
int attempt;
PlayerCommand command;
CommandStatus status;
std::uint64_t tick;
std::uint64_t revision;
};
// Ordinals include the two paused step attempts. Rejected commands do not
// consume a sequence number or advance the command revision.
const std::array journal{
RecordedCommand{0, {1, 1, CommandKind::SetPaused, {}, 1}, CommandStatus::Accepted, 0, 1},
RecordedCommand{0, {2, 1, CommandKind::SetPaused, {}, 0}, CommandStatus::Unauthorized, 0, 1},
RecordedCommand{0, {1, 2, CommandKind::PlaceBed, {16, 18}}, CommandStatus::Accepted, 0, 2},
RecordedCommand{0, {2, 1, CommandKind::PlaceBed, {17, 18}, 1}, CommandStatus::Accepted, 0, 3},
RecordedCommand{0, {2, 1, CommandKind::PlaceBed, {18, 18}}, CommandStatus::WrongSequence, 0, 3},
RecordedCommand{0, {2, 2, CommandKind::PlaceBed, {16, 18}}, CommandStatus::InvalidTarget, 0, 3},
RecordedCommand{0, {2, 2, CommandKind::PlaceBed, {18, 18}}, CommandStatus::Accepted, 0, 4},
RecordedCommand{2, {1, 3, CommandKind::SetPaused, {}, 0}, CommandStatus::Accepted, 0, 5},
RecordedCommand{302, {2, 3, CommandKind::SetForaging, {14, 12}, 1}, CommandStatus::Accepted, 300, 6},
RecordedCommand{302, {1, 4, CommandKind::SetPriority, {}, 1}, CommandStatus::Accepted, 300, 7},
};
std::size_t next_command = 0;
bool saved_delivery = false;
for (int attempt = 0; attempt < 752; ++attempt) {
while (next_command < journal.size() && journal[next_command].attempt == attempt) {
const auto& entry = journal[next_command++];
replay.command(entry.command, entry.status, entry.tick, entry.revision);
}
const auto before = saved_state(*replay.reference);
replay.step();
if (attempt < 2) {
require(saved_state(*replay.reference) == before,
"a paused step changed the colony");
}
if (attempt == 301) {
require(replay.reference->scenario_progress().assigned_beds == 3 &&
!replay.reference->scenario_progress().completed &&
replay.reference->scenario_progress().available_food == 0,
"construction failed or unmarked food bypassed the recorded command");
}
const bool carrying_material = std::any_of(replay.reference->agents().begin(),
replay.reference->agents().end(), [](const Agent& agent) {
return agent.inventory.item_count(ItemType::Wood) > 0 ||
agent.inventory.item_count(ItemType::Stone) > 0 ||
agent.inventory.item_count(ItemType::Cloth) > 0;
});
if (!saved_delivery && carrying_material && replay.reference->assignment_path_cache_hits() > 0) {
replay.checkpoint();
saved_delivery = true;
}
}
require(saved_delivery, "no material-in-hand checkpoint with a warmed path cache was replayed");
require(next_command == journal.size() && replay.reference->tick() == 750,
"the recorded command schedule did not finish");
require(replay.reference->scenario_progress().completed && replay.reference->meals_eaten() >= 3,
"the recorded colony failed to build its beds and feed its residents");
require(replay.reference->next_command_sequence(1) == 5 &&
replay.reference->next_command_sequence(2) == 4,
"rejected commands changed player sequence progress");
}
Test ReplayTests::test_recorded_colony_commands_and_loaded_delivery() {
replay_colony_journal(4096);
}
Test ReplayTests::test_recorded_colony_at_capacity_one() {
replay_colony_journal(1);
}
Test ReplayTests::test_last_meal_has_one_winner_and_one_consumer() {
World initial(97, 8, 8);
const auto pantry = initial.add_storage({1, 1}, 1, StorageKind::Pantry);
const auto winner = initial.spawn_agent({5, 1});
static_cast<void>(initial.spawn_agent({5, 1}));
initial.enable_hunger();
// Hunger is staggered by resident ID. Supply the item only after both are
// eligible, so the first arbitration has two contenders for the same unit.
for (std::uint16_t tick = 0; tick < hunger_threshold; ++tick) initial.step();
require(initial.agents()[0].hungry() && initial.agents()[1].hungry(),
"the last-meal fixture requires two hungry contenders");
initial.stock_storage(pantry, ItemType::Berries, 1);
ReplayWorlds replay(initial);
bool saw_reservation = false;
bool saved_meal = false;
for (int tick = 0; tick < 40; ++tick) {
replay.step();
const auto& world = *replay.reference;
const auto& first = world.agents()[0];
const auto& second = world.agents()[1];
const auto& storage = world.storages().front();
const auto accounted = storage.item_count(ItemType::Berries) +
first.inventory.item_count(ItemType::Berries) + second.inventory.item_count(ItemType::Berries) +
world.meals_eaten();
require(accounted == 1, "the last meal was lost or duplicated");
require(second.inventory.empty() && second.state != AgentState::GoingToEat &&
second.state != AgentState::Eating,
"both contenders reserved the last meal");
if (first.state == AgentState::GoingToEat) {
require(first.id == winner && storage.items.front().reserved == 1 && first.inventory.empty(),
"stable resident order did not determine the last-meal reservation");
saw_reservation = true;
}
if (!saved_meal && first.inventory.item_count(ItemType::Berries) == 1) {
require(first.state == AgentState::Eating, "the meal was held outside its eating state");
replay.checkpoint();
saved_meal = true;
}
}
require(saw_reservation && saved_meal && replay.reference->meals_eaten() == 1 &&
replay.reference->storages().front().total_items() == 0 &&
replay.reference->agents()[0].hunger < hunger_threshold &&
replay.reference->agents()[1].hunger >= hunger_threshold,
"the stable winner did not consume the one available meal exactly once");
}
} // namespace
+233
View File
@@ -0,0 +1,233 @@
#include "settlement/core/rules_manifest.hpp"
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
template <class T>
T checked(std::expected<T, RulesDiagnostic> result) {
if (!result) {
const auto& d = result.error();
throw std::runtime_error(d.source + " " + d.package + " " + d.field + " " + d.message);
}
return std::move(*result);
}
std::string package(std::string_view id, std::string_view definitions = "[]",
std::string_view dependencies = "[]", std::string_view capabilities = "[]",
std::string_view version = "1.0.0") {
return "{\"schema\":1,\"id\":\"" + std::string(id) + "\",\"version\":\"" + std::string(version) +
"\",\"dependencies\":" + std::string(dependencies) + ",\"exclusive_capabilities\":" +
std::string(capabilities) + ",\"definitions\":" + std::string(definitions) + "}";
}
constexpr std::string_view wood = R"({"id":"game.core:wood","kind":"item","data":{"stack_limit":64},"references":[]})";
constexpr std::string_view stone = R"({"id":"game.core:stone","kind":"item","data":{"stack_limit":32},"references":[]})";
constexpr std::string_view board = R"([{"id":"game.colony:board","kind":"recipe","data":{"work_ticks":8},"references":["game.core:wood","game.core:stone"]}])";
constexpr std::string_view core_dependency = R"([{"id":"game.core","version":">=1.0.0 <2.0.0"}])";
RulePackage load(std::string_view json) { return checked(load_rule_package("fixture.json", json)); }
RulesManifest resolve(std::vector<RulePackage> packages, std::vector<std::string> selected = {"game.colony"},
const RulesLimits& limits = {}) {
return checked(resolve_rules(packages, selected, limits));
}
void parse_error(std::string_view json, std::string_view field, const RulesLimits& limits = {}) {
const auto result = load_rule_package("bad-package.json", json, limits);
require(!result, "invalid package was accepted");
require(result.error().source == "bad-package.json" && result.error().field.find(field) != std::string::npos &&
!result.error().message.empty(), "parser diagnostic lost source or field");
}
void resolution_error(const std::vector<RulePackage>& packages, const std::vector<std::string>& selected,
std::string_view field, const RulesLimits& limits = {}) {
const auto result = resolve_rules(packages, selected, limits);
require(!result, "invalid package set was accepted");
require(result.error().field.find(field) != std::string::npos && !result.error().source.empty() &&
!result.error().message.empty(), "resolver diagnostic lost source or field");
}
struct [[= Void::Testing::name("RulesTests")]] RulesTests : Void::Testing::Suite<RulesTests> {
[[= Void::Testing::tag("rules")]] Test test_manifest_identity_is_independent_of_discovery_order();
[[= Void::Testing::tag("rules")]] Test test_frozen_identity_covers_content_and_exact_versions();
[[= Void::Testing::tag("rules")]] Test test_transitive_selection_and_unselected_packages();
[[= Void::Testing::tag("rules")]] Test test_invalid_dependencies_and_provider_conflicts();
[[= Void::Testing::tag("rules")]] Test test_definition_references_and_namespaces();
[[= Void::Testing::tag("rules")]] Test test_strict_json_schema_and_input_budgets();
[[= Void::Testing::tag("rules")]] Test test_catalog_and_model_limits();
[[= Void::Testing::tag("rules")]] Test test_prerelease_policy();
[[= Void::Testing::tag("rules")]] Test test_builtin_default_and_known_digest();
};
Test RulesTests::test_manifest_identity_is_independent_of_discovery_order() {
const auto core_a = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"));
const auto core_b = load(package("game.core", "[" + std::string(stone) + "," + std::string(wood) + "]"));
const auto tools = load(package("game.tools"));
const auto colony_a = load(package("game.colony", board,
R"([{"id":"game.core","version":">=1.0.0 <2.0.0"},{"id":"game.tools","version":"1.0.0"}])",
R"(["game.colony:weather","game.colony:building"])"));
std::string reversed_board(board);
const auto refs = reversed_board.find("\"game.core:wood\",\"game.core:stone\"");
reversed_board.replace(refs, std::string("\"game.core:wood\",\"game.core:stone\"").size(),
"\"game.core:stone\",\"game.core:wood\"");
const auto colony_b = load(package("game.colony", reversed_board,
R"([{"id":"game.tools","version":"1.0.0"},{"id":"game.core","version":">=1.0.0 <2.0.0"}])",
R"(["game.colony:building","game.colony:weather"])"));
const auto first = resolve({core_a, colony_a, tools});
const auto second = resolve({tools, colony_b, core_b});
require(first == second, "permuting package, definition, capability or reference order changed identity");
require(first.packages().size() == 3 && first.packages()[0].id == "game.colony" &&
first.packages()[1].id == "game.core", "frozen packages are not sorted by ID");
require(core_a.canonical_json() == core_b.canonical_json(), "canonical package bytes changed with input order");
const auto reloaded = load(core_a.canonical_json());
require(reloaded.identity() == core_a.identity(), "canonical document did not round-trip");
}
Test RulesTests::test_frozen_identity_covers_content_and_exact_versions() {
const auto source = package("game.core", "[" + std::string(wood) + "]");
const auto original = resolve({load(source)}, {"game.core"});
const auto compare = [&](std::string changed) {
require(resolve({load(changed)}, {"game.core"}) != original, "simulation change kept the frozen fingerprint");
};
auto modified = source;
modified.replace(modified.find("64"), 2, "65");
compare(modified);
compare(package("game.core", "[" + std::string(wood) + "]", "[]", "[]", "1.0.1"));
compare(package("game.core", "[" + std::string(wood) + "]", "[]", "[]", "1.0.0+build2"));
compare(package("game.core"));
modified = source;
modified.replace(modified.find("game.core:wood"), 14, "game.core:logs");
compare(modified);
const auto a = resolve({load(package("game.core", R"([{"id":"game.core:path","kind":"event","data":[1,2],"references":[]}])"))}, {"game.core"});
const auto b = resolve({load(package("game.core", R"([{"id":"game.core:path","kind":"event","data":[2,1],"references":[]}])"))}, {"game.core"});
require(a != b, "ordered definition data was sorted as a set");
}
Test RulesTests::test_transitive_selection_and_unselected_packages() {
const auto core = load(package("game.core"));
const auto colony = load(package("game.colony", "[]", core_dependency));
const auto ui = load(package("game.ui", "[]", R"([{"id":"game.colony","version":"1.0.0"}])"));
const auto broken_unselected = load(package("game.unselected", "[]", R"([{"id":"game.missing","version":"1.0.0"}])"));
const auto first = resolve({ui, colony, core, broken_unselected}, {"game.ui"});
const auto second = resolve({core, ui, colony}, {"game.core", "game.ui"});
require(first == second && first.packages().size() == 3, "transitive dependency closure changed with selection order");
resolution_error({core}, {"game.absent"}, "selected");
resolution_error({core}, {}, "selected");
resolution_error({core}, {"game.core", "game.core"}, "selected");
}
Test RulesTests::test_invalid_dependencies_and_provider_conflicts() {
const auto core = load(package("game.core"));
resolution_error({core, core}, {"game.core"}, "id");
resolution_error({load(package("game.colony", "[]", core_dependency))}, {"game.colony"}, "dependencies");
const auto incompatible = load(package("game.colony", "[]", R"([{"id":"game.core","version":"^2.0.0"}])"));
resolution_error({core, incompatible}, {"game.colony"}, "dependencies.game.core");
const auto back_edge = load(package("game.core", "[]", R"([{"id":"game.colony","version":"*"}])"));
resolution_error({back_edge, load(package("game.colony", "[]", core_dependency))}, {"game.colony"}, "dependencies");
const auto provider_a = load(package("game.first", "[]", "[]", R"(["game.core:terrain"])"));
const auto provider_b = load(package("game.second", "[]", "[]", R"(["game.core:terrain"])"));
resolution_error({provider_a, provider_b}, {"game.first", "game.second"}, "exclusive_capabilities");
parse_error(package("game.colony", "[]", R"([{"id":"game.core","version":"=>broken"}])"), "version");
parse_error(package("game.colony", "[]", R"([{"id":"game.core","version":"*"},{"id":"game.core","version":"*"}])"), "dependencies");
}
Test RulesTests::test_definition_references_and_namespaces() {
const auto core = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"));
const auto colony = load(package("game.colony", board, core_dependency));
static_cast<void>(resolve({core, colony}));
resolution_error({load(package("game.core")), colony}, {"game.colony"}, "references");
resolution_error({core, load(package("game.colony", board))}, {"game.core", "game.colony"}, "references");
parse_error(package("game.colony", "[" + std::string(wood) + "]"), ".id");
parse_error(package("game.core", "[" + std::string(wood) + "," + std::string(wood) + "]"), ".id");
parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"native","data":{},"references":[]}])"), ".kind");
parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"item","data":{},"references":["not-qualified"]}])"), ".references");
}
Test RulesTests::test_strict_json_schema_and_input_budgets() {
const auto valid = package("game.core");
parse_error("{\"schema\":1,\"schema\":1}", "$");
parse_error(valid + " false", "$");
parse_error("{\"id\":\"\xff\"}", "$");
parse_error("{}", "$");
auto modified = valid;
modified.insert(1, "\"sha256\":\"forged\",");
parse_error(modified, "sha256");
modified = valid;
modified.replace(modified.find("\"schema\":1"), 10, "\"schema\":2");
parse_error(modified, "schema");
parse_error(package("Game"), "id");
parse_error(package("game.core", "[]", "[]", "[]", "v1.0.0"), "version");
parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"item","data":0.5,"references":[]}])"), "$");
RulesLimits limits;
limits.package_bytes = valid.size() - 1;
parse_error(valid, "$", limits);
limits = {};
limits.json_nodes = 4;
parse_error(valid, "$", limits);
limits = {};
limits.json_depth = 2;
parse_error(package("game.core", "[" + std::string(wood) + "]"), "$", limits);
}
Test RulesTests::test_catalog_and_model_limits() {
const auto core = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"));
const auto colony = load(package("game.colony", board, core_dependency));
RulesLimits limits;
limits.packages = 1;
resolution_error({core, colony}, {"game.colony"}, "packages", limits);
limits = {};
limits.catalog_bytes = 2;
resolution_error({core, colony}, {"game.colony"}, "packages", limits);
limits = {};
limits.definitions = 1;
resolution_error({core}, {"game.core"}, "definitions", limits);
parse_error(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"), "definitions", limits);
limits = {};
limits.dependencies = 0;
parse_error(package("game.colony", board, core_dependency), "dependencies", limits);
limits = {};
limits.references = 1;
parse_error(package("game.colony", board, core_dependency), "references", limits);
}
Test RulesTests::test_prerelease_policy() {
const auto prerelease = load(package("game.core", "[]", "[]", "[]", "1.0.0-preview+test"));
const auto broad = load(package("game.colony", "[]", R"([{"id":"game.core","version":"*"}])"));
resolution_error({prerelease, broad}, {"game.colony"}, "dependencies");
const auto exact = load(package("game.colony", "[]", R"([{"id":"game.core","version":"=1.0.0-preview+test"}])"));
const auto result = resolve({prerelease, exact});
require(result.packages()[1].exact_version == "1.0.0-preview+test", "prerelease exact identity was lost");
}
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");
}
} // namespace
+398
View File
@@ -0,0 +1,398 @@
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using namespace std::chrono_literals;
using Void::Testing::require;
using Void::Testing::Test;
constexpr TrustedClient host{1};
constexpr TrustedClient guest{2};
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
WorldCheckpoint colony(std::size_t workers = 2, WorkerPoolOptions options = {}) {
auto original = make_first_colony(2);
std::istringstream input(bytes(*original), std::ios::binary);
auto world = World::read_save(input, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel, std::move(options));
Void::Uuid::Uuid id;
id.bytes.back() = 71;
auto rules = default_rules_manifest();
require(rules.has_value());
return {std::move(world), id, 1, std::move(*rules)};
}
template<class Submit>
RuntimeSubmission admitted(Submit submit) {
const auto limit = std::chrono::steady_clock::now() + 5s;
for (;;) {
auto operation = submit();
if (operation.admission != RuntimeAdmission::Busy) return operation;
require(std::chrono::steady_clock::now() < limit);
std::this_thread::yield();
}
}
RuntimeResult finished(RuntimeSubmission operation) {
require(operation.admission == RuntimeAdmission::Accepted);
require(operation.completion.wait_for(5s) == std::future_status::ready);
return operation.completion.get();
}
RuntimeResult fence(SimulationRuntime& runtime) {
return finished(admitted([&] { return runtime.synchronize(); }));
}
CommandEnvelope envelope(const PublishedSnapshot& snapshot, std::uint64_t request,
CommandKind kind, std::uint8_t value = 0) {
return {command_envelope_version, snapshot.identity.world, snapshot.identity.session,
snapshot.identity.city, request, CommandPayload{kind, {}, value}};
}
RuntimeResult send(SimulationRuntime& runtime, TrustedClient client, const CommandEnvelope& command) {
return finished(admitted([&] { return runtime.try_submit(client, command); }));
}
struct Gate {
std::mutex mutex;
std::condition_variable changed;
bool entered = false;
bool released = false;
void block() {
std::unique_lock lock(mutex);
entered = true;
changed.notify_all();
if (!changed.wait_for(lock, 5s, [&] { return released; })) throw std::runtime_error("gate timed out");
}
void wait() {
std::unique_lock lock(mutex);
require(changed.wait_for(lock, 5s, [&] { return entered; }));
}
void release() {
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
};
std::atomic<bool> fail_after_mutation{false};
void command_observer(CommandMutationPhase phase) {
if (phase == CommandMutationPhase::AfterMutation && fail_after_mutation.exchange(false)) {
throw std::runtime_error("after command mutation");
}
}
struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::Suite<RuntimeTests> {
[[= Void::Testing::tag("runtime")]] Test test_fixed_clock_matches_reference_and_suspend_discards_idle_time();
[[= Void::Testing::tag("runtime")]] Test test_paused_commands_publish_and_two_clients_replay_exact_results();
[[= Void::Testing::tag("runtime")]] Test test_readers_and_save_capture_progress_during_real_worker_tick();
[[= Void::Testing::tag("runtime")]] Test test_tick_and_capture_failures_keep_previous_publication_and_recover();
[[= Void::Testing::tag("runtime")]] Test test_failed_command_keeps_committed_receipts_and_settles_queue();
[[= Void::Testing::tag("runtime")]] Test test_newer_load_supersedes_preparing_candidate_and_fences_old_commands();
[[= Void::Testing::tag("runtime")]] Test test_invalid_install_preserves_healthy_world_and_ticket_scope();
[[= Void::Testing::tag("runtime")]] Test test_capacity_and_shutdown_settle_accepted_work();
[[= Void::Testing::tag("runtime")]] Test test_command_capture_failure_settles_queued_mutations();
[[= Void::Testing::tag("runtime")]] Test test_exhausted_clock_faults_without_spinning();
};
Test RuntimeTests::test_fixed_clock_matches_reference_and_suspend_discards_idle_time() {
for (const auto workers : {1U, 2U, 6U, 12U}) {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto reference = colony(1);
SimulationRuntime runtime(colony(workers), {.clock = clock});
for (int i = 0; i < 20; ++i) {
require(clock->advance(50ms).has_value());
require(fence(runtime).outcome == RuntimeOutcome::Completed);
reference.world->step();
require(bytes(*runtime.latest()->world) == bytes(*reference.world));
}
require(runtime.latest()->world->tick() == 20);
require(finished(admitted([&] { return runtime.set_ticking(false); })).outcome == RuntimeOutcome::Completed);
require(clock->advance(1h).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 20);
static_cast<void>(finished(admitted([&] { return runtime.set_ticking(true); })));
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 20);
require(clock->advance(1s).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 40);
}
}
Test RuntimeTests::test_paused_commands_publish_and_two_clients_replay_exact_results() {
auto clock = std::make_shared<Void::Time::ManualClock>();
SimulationRuntime runtime(colony(), {.clock = clock});
const auto initial = runtime.latest();
auto pause = envelope(*initial, 1, CommandKind::SetPaused, 1);
auto result = send(runtime, host, pause);
require(result.receipt->command_status == CommandStatus::Accepted);
require(result.snapshot->world->paused() && result.snapshot->world->tick() == 0);
require(result.snapshot->revision > initial->revision);
require(clock->advance(1h).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 0);
auto invalid = envelope(*initial, 1, CommandKind::SetPriority, 255);
const auto rejected = send(runtime, guest, invalid);
require(rejected.receipt->status == DispatchStatus::Completed);
require(rejected.receipt->command_status != CommandStatus::Accepted);
const auto prior = runtime.latest();
require(send(runtime, guest, invalid).receipt == rejected.receipt);
require(runtime.latest() == prior);
auto conflict = invalid;
std::get<CommandPayload>(conflict.payload).value = 1;
require(send(runtime, guest, conflict).receipt->status == DispatchStatus::Conflict);
require(send(runtime, host, pause).receipt == result.receipt);
require(runtime.latest()->next_requests == (std::array<std::uint64_t, 2>{2, 2}));
auto resume = envelope(*initial, 2, CommandKind::SetPaused, 0);
require(send(runtime, host, resume).receipt->command_status == CommandStatus::Accepted);
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 0);
require(clock->advance(50ms).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
}
Test RuntimeTests::test_readers_and_save_capture_progress_during_real_worker_tick() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
WorkerPoolOptions workers;
workers.before_execute = [gate](std::size_t) { gate->block(); };
SimulationRuntime runtime(colony(2, std::move(workers)), {.clock = clock});
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto before = runtime.latest();
const auto saved = bytes(*before->world);
require(clock->advance(50ms).has_value());
runtime.notify_clock();
gate->wait();
auto reader = std::async(std::launch::async, [&] {
const auto snapshot = runtime.snapshot_for_save();
require(snapshot.has_value() && *snapshot == before);
return bytes(*runtime.latest()->world);
});
require(reader.wait_for(1s) == std::future_status::ready);
require(reader.get() == saved);
gate->release();
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
require(bytes(*before->world) == saved);
}
Test RuntimeTests::test_tick_and_capture_failures_keep_previous_publication_and_recover() {
for (const bool stage_failure : {false, true}) {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto fail = std::make_shared<std::atomic<bool>>(false);
WorkerPoolOptions workers;
if (stage_failure) workers.before_execute = [fail](std::size_t) {
if (fail->exchange(false)) throw std::runtime_error("stage failure");
};
RuntimeOptions options{.clock = clock};
options.observer = [fail, stage_failure](RuntimePhase phase) {
if (!stage_failure && phase == RuntimePhase::BeforeCapture && fail->exchange(false)) {
throw std::runtime_error("snapshot preparation failure");
}
};
SimulationRuntime runtime(colony(2, std::move(workers)), std::move(options));
const auto previous = runtime.latest();
fail->store(true);
require(clock->advance(50ms).has_value());
require(fence(runtime).outcome == RuntimeOutcome::Faulted);
require(runtime.view().state == RuntimeState::Faulted && runtime.view().failure);
require(runtime.latest() == previous && !runtime.snapshot_for_save());
auto command = envelope(*previous, 1, CommandKind::SetPaused, 1);
require(send(runtime, host, command).outcome == RuntimeOutcome::Faulted);
auto ticket = runtime.begin_load();
require(ticket.has_value());
auto replacement = colony();
const auto installed = finished(admitted([&] { return runtime.try_install(*ticket, replacement); }));
require(installed.outcome == RuntimeOutcome::Completed && !replacement.world);
require(runtime.view().state == RuntimeState::Running && !runtime.view().failure);
require(runtime.latest()->identity.session != previous->identity.session);
require(send(runtime, host, command).receipt->status == DispatchStatus::StaleSession);
require(clock->advance(50ms).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
}
}
Test RuntimeTests::test_failed_command_keeps_committed_receipts_and_settles_queue() {
auto gate = std::make_shared<Gate>();
auto armed = std::make_shared<std::atomic<bool>>(false);
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.clock = clock, .dispatcher = {.mutation_observer = command_observer}};
options.observer = [gate, armed](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture && armed->load()) gate->block();
};
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); fail_after_mutation.store(false); });
const auto first = envelope(*runtime.latest(), 1, CommandKind::SetPaused, 1);
const auto accepted = send(runtime, host, first);
const auto committed = runtime.latest();
fail_after_mutation.store(true);
auto second = envelope(*committed, 2, CommandKind::SetPriority, 1);
require(send(runtime, host, second).outcome == RuntimeOutcome::Faulted);
require(runtime.latest() == committed);
require(runtime.lookup(host, first) == accepted.receipt);
require(!runtime.lookup(host, second));
require(send(runtime, host, first).receipt == accepted.receipt);
require(send(runtime, host, second).outcome == RuntimeOutcome::Faulted);
require(!runtime.snapshot_for_save());
require(fence(runtime).outcome == RuntimeOutcome::Faulted);
const auto ticket = runtime.begin_load();
auto replacement = colony();
require(finished(admitted([&] { return runtime.try_install(*ticket, replacement); })).outcome == RuntimeOutcome::Completed);
armed->store(true);
const auto before = runtime.latest();
auto change = envelope(*before, 1, CommandKind::SetPaused, 1);
auto pending = admitted([&] { return runtime.try_submit(host, change); });
gate->wait();
require(runtime.latest() == before && !runtime.lookup(host, change));
armed->store(false);
gate->release();
require(finished(std::move(pending)).receipt->command_status == CommandStatus::Accepted);
}
Test RuntimeTests::test_newer_load_supersedes_preparing_candidate_and_fences_old_commands() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.clock = clock};
options.observer = [gate](RuntimePhase phase) { if (phase == RuntimePhase::BeforeInstallCapture) gate->block(); };
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto previous = runtime.latest();
const auto first = runtime.begin_load();
auto earlier = colony();
auto installing = admitted([&] { return runtime.try_install(*first, earlier); });
gate->wait();
const auto second = runtime.begin_load();
require(second.has_value());
gate->release();
require(finished(std::move(installing)).outcome == RuntimeOutcome::Superseded);
require(runtime.latest() == previous);
auto newer = colony();
require(finished(admitted([&] { return runtime.try_install(*second, newer); })).outcome == RuntimeOutcome::Completed);
require(runtime.latest()->identity.world == previous->identity.world);
require(runtime.latest()->identity.session != previous->identity.session);
auto stale = envelope(*previous, 1, CommandKind::SetPaused, 1);
require(send(runtime, host, stale).receipt->status == DispatchStatus::StaleSession);
auto reused = colony();
require(finished(admitted([&] { return runtime.try_install(*second, reused); })).outcome == RuntimeOutcome::Superseded);
}
Test RuntimeTests::test_invalid_install_preserves_healthy_world_and_ticket_scope() {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto fail = std::make_shared<std::atomic<bool>>(false);
RuntimeOptions options{.clock = clock};
options.observer = [fail](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeInstallCapture && fail->load()) throw std::bad_alloc();
};
SimulationRuntime runtime(colony(), std::move(options));
const auto previous = runtime.latest();
auto invalid = colony();
invalid.world_id = {};
auto ticket = runtime.begin_load();
require(finished(admitted([&] { return runtime.try_install(*ticket, invalid); })).outcome == RuntimeOutcome::InvalidCandidate);
require(runtime.latest() == previous && runtime.view().state == RuntimeState::Running);
fail->store(true);
auto valid = colony();
require(finished(admitted([&] { return runtime.try_install(*ticket, valid); })).outcome == RuntimeOutcome::InvalidCandidate);
require(runtime.latest() == previous && runtime.snapshot_for_save());
fail->store(false);
require(clock->advance(50ms).has_value());
static_cast<void>(fence(runtime));
require(runtime.latest()->world->tick() == 1);
}
Test RuntimeTests::test_capacity_and_shutdown_settle_accepted_work() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.capacity = 2, .clock = clock};
options.observer = [gate](RuntimePhase phase) { if (phase == RuntimePhase::BeforeCapture) gate->block(); };
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto before = runtime.latest();
auto command = envelope(*before, 1, CommandKind::SetPaused, 1);
auto active = admitted([&] { return runtime.try_submit(host, command); });
gate->wait();
auto queued = admitted([&] { return runtime.synchronize(); });
auto full = runtime.synchronize();
require(full.admission == RuntimeAdmission::Busy && !full.completion.valid());
auto candidate = colony();
auto ticket = runtime.begin_load();
require(runtime.try_install(*ticket, candidate).admission == RuntimeAdmission::Busy && candidate.world);
auto stopped = std::async(std::launch::async, [&] { runtime.shutdown(); });
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (runtime.view().state != RuntimeState::Closed) {
require(std::chrono::steady_clock::now() < deadline);
std::this_thread::yield();
}
gate->release();
require(finished(std::move(active)).outcome == RuntimeOutcome::Closed);
require(finished(std::move(queued)).outcome == RuntimeOutcome::Closed);
require(stopped.wait_for(5s) == std::future_status::ready);
stopped.get();
runtime.shutdown();
require(runtime.latest() == before);
require(runtime.try_submit(host, command).admission == RuntimeAdmission::Closed);
require(runtime.begin_load().error() == RuntimeAdmission::Closed);
require(!runtime.snapshot_for_save());
}
Test RuntimeTests::test_command_capture_failure_settles_queued_mutations() {
auto gate = std::make_shared<Gate>();
auto fail = std::make_shared<std::atomic<bool>>(false);
auto clock = std::make_shared<Void::Time::ManualClock>();
RuntimeOptions options{.clock = clock};
options.observer = [gate, fail](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture && fail->load()) {
gate->block();
throw std::bad_alloc();
}
};
SimulationRuntime runtime(colony(), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto first = envelope(*runtime.latest(), 1, CommandKind::SetPaused, 1);
const auto accepted = send(runtime, host, first);
const auto committed = runtime.latest();
const auto second = envelope(*committed, 2, CommandKind::SetPriority, 1);
fail->store(true);
auto active = admitted([&] { return runtime.try_submit(host, second); });
gate->wait();
auto third = envelope(*committed, 3, CommandKind::SetPaused, 0);
auto queued = admitted([&] { return runtime.try_submit(host, third); });
auto repeat = admitted([&] { return runtime.try_submit(host, first); });
require(runtime.lookup(host, first) == accepted.receipt);
require(!runtime.lookup(host, second));
gate->release();
require(finished(std::move(active)).outcome == RuntimeOutcome::Faulted);
require(finished(std::move(queued)).outcome == RuntimeOutcome::Faulted);
require(finished(std::move(repeat)).receipt == accepted.receipt);
require(runtime.latest() == committed && !runtime.snapshot_for_save());
}
Test RuntimeTests::test_exhausted_clock_faults_without_spinning() {
auto clock = std::make_shared<Void::Time::ManualClock>();
require(clock->set(Void::Time::MonotonicClock::time_point::max()).has_value());
SimulationRuntime runtime(colony(), {.clock = clock});
require(fence(runtime).outcome == RuntimeOutcome::Faulted);
require(runtime.latest()->world->tick() == 0);
require(runtime.view().failure != nullptr);
}
} // namespace
+393
View File
@@ -0,0 +1,393 @@
#include "settlement/core/save_service.hpp"
#include <Void/Testing/Suite.hpp>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <fstream>
#include <iterator>
#include <latch>
#include <memory>
#include <stdexcept>
#include <thread>
#include <utility>
#include <vector>
namespace {
using namespace std::chrono_literals;
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
struct TemporaryDirectory {
std::filesystem::path path;
TemporaryDirectory() {
const auto token = Void::Uuid::v4().to_string();
path = std::filesystem::temp_directory_path() / ("settlement-save-test-" + token);
require(std::filesystem::create_directory(path), "test directory was not exclusively created");
}
~TemporaryDirectory() {
std::error_code error;
std::filesystem::remove_all(path, error);
}
};
struct Reader {
HANDLE handle{INVALID_HANDLE_VALUE};
Reader(const std::filesystem::path& path, DWORD sharing)
: handle(CreateFileW(path.c_str(), GENERIC_READ, sharing, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr)) {
require(handle != INVALID_HANDLE_VALUE, "cannot open test reader");
}
~Reader() { CloseHandle(handle); }
std::string read() const {
LARGE_INTEGER beginning{};
require(SetFilePointerEx(handle, beginning, nullptr, FILE_BEGIN), "cannot rewind test reader");
std::string bytes;
std::array<char, 8192> buffer;
for (;;) {
DWORD count = 0;
require(ReadFile(handle, buffer.data(), static_cast<DWORD>(buffer.size()), &count, nullptr),
"test read failed");
if (count == 0) return bytes;
bytes.append(buffer.data(), count);
}
}
};
std::string read(const std::filesystem::path& path) {
return Reader(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE).read();
}
void write(const std::filesystem::path& path, const std::string& bytes) {
std::ofstream file(path, std::ios::binary);
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
file.close();
require(static_cast<bool>(file), "cannot write test fixture");
}
Void::Uuid::Uuid session() {
Void::Uuid::Uuid id;
id.bytes[0] = 42;
return id;
}
SaveRequest request(const std::filesystem::path& path, std::string bytes, std::uint64_t tick = 9) {
return {path, tick, session(), [bytes = std::move(bytes)] { return bytes; }};
}
SaveResult completed(SaveSubmission& submission) {
require(submission.admission == SaveAdmission::Accepted && submission.request_id != 0,
"request was not accepted");
require(submission.completion.wait_for(10s) == std::future_status::ready, "save did not complete");
auto result = submission.completion.get();
require(result.request_id == submission.request_id, "completion identity changed");
return result;
}
void only_files(const TemporaryDirectory& directory, std::size_t count) {
const auto actual = static_cast<std::size_t>(std::distance(
std::filesystem::directory_iterator(directory.path), std::filesystem::directory_iterator{}));
require(actual == count, "unexpected file or staging file left in test directory");
}
// Every wait has an explicit causal signal. The timeout is only a deadlock
// watchdog; it never creates the ordering being tested.
struct Gate {
std::promise<void> entered;
std::future<void> arrival{entered.get_future()};
std::promise<void> released;
std::shared_future<void> release{released.get_future().share()};
std::atomic<bool> opened{false};
void wait() {
entered.set_value();
require(release.wait_for(10s) == std::future_status::ready, "test gate timed out");
}
void await_entry() {
require(arrival.wait_for(10s) == std::future_status::ready, "writer did not reach test gate");
}
void open() {
if (!opened.exchange(true)) released.set_value();
}
~Gate() { open(); }
};
struct [[= Void::Testing::name("SaveServiceTests")]]
SaveServiceTests : Void::Testing::Suite<SaveServiceTests> {
[[= Void::Testing::tag("save-slot")]] Test unicode_create_replace_and_open_reader();
[[= Void::Testing::tag("save-slot")]] Test prepublication_faults_preserve_slot_and_siblings();
[[= Void::Testing::tag("save-slot")]] Test partial_staging_is_never_visible();
[[= Void::Testing::tag("save-slot")]] Test fifo_bound_snapshot_lifetime_and_shutdown_drain();
[[= Void::Testing::tag("save-slot")]] Test failed_producer_does_not_stop_writer();
[[= Void::Testing::tag("save-slot")]] Test invalid_missing_parent_and_sharing_failure();
[[= Void::Testing::tag("save-slot")]] Test concurrent_submission_identity_matches_publication_order();
[[= Void::Testing::tag("save-slot")]] Test empty_file_and_size_limit();
[[= Void::Testing::tag("save-slot")]] Test self_shutdown_is_rejected_without_closing_service();
};
Test SaveServiceTests::unicode_create_replace_and_open_reader() {
TemporaryDirectory directory;
const auto path = directory.path / L"\u0441\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435-\u96ea.bin";
SaveService service;
const std::string old_bytes("old\0save", 8);
auto first = service.try_submit(request(path, old_bytes, 17));
const auto created = completed(first);
require(created.succeeded() && created.visible_on_disk && !created.durability_unknown,
"first save not published");
require(created.tick == 17 && created.session == session(), "snapshot metadata was not preserved");
std::string new_bytes(200000, 'x');
new_bytes[65536] = '\0';
new_bytes.back() = 'z';
bool retry_after_reader_closes = false;
{
Reader old_reader(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
auto second = service.try_submit(request(path, new_bytes));
const auto replacement = completed(second);
require(second.request_id > first.request_id, "save identity did not increase");
require(old_reader.read() == old_bytes, "open reader saw partial or replaced old file bytes");
if (replacement.succeeded()) {
require(replacement.visible_on_disk && !replacement.durability_unknown,
"successful replacement not reported as visible");
require(read(path) == new_bytes, "fresh reader did not see complete binary replacement");
} else {
// Wine 11 returns ERROR_ACCESS_DENIED (5), even with delete sharing.
// Windows/filesystem open-handle restrictions may reject publication;
// atomic visibility does not promise replacement under every lock.
require(replacement.error == SaveError::Io && replacement.phase == SavePhase::Publish &&
(replacement.native_error == ERROR_ACCESS_DENIED ||
replacement.native_error == ERROR_SHARING_VIOLATION) &&
!replacement.visible_on_disk && !replacement.durability_unknown,
"replacement failed outside the permitted sharing/access boundary");
require(read(path) == old_bytes, "rejected replacement changed the existing slot");
require(replacement.cleanup_error == 0 && replacement.retained_staging_file.empty(),
"rejected replacement did not clean its staging file");
only_files(directory, 1);
retry_after_reader_closes = true;
}
}
if (retry_after_reader_closes) {
auto retry = service.try_submit(request(path, new_bytes));
require(completed(retry).succeeded(), "next replacement failed after the reader closed");
}
require(read(path) == new_bytes, "fresh reader did not see complete binary replacement");
service.shutdown();
only_files(directory, 1);
}
Test SaveServiceTests::prepublication_faults_preserve_slot_and_siblings() {
const std::array phases{SavePhase::Materialize, SavePhase::CreateStage, SavePhase::WriteStage,
SavePhase::FlushStage, SavePhase::CloseStage, SavePhase::Publish,
SavePhase::Published};
for (const auto failed_phase : phases) {
TemporaryDirectory directory;
const auto path = directory.path / L"slot.bin";
const auto sibling = directory.path / L".settlement-save-unrelated.tmp";
write(path, "previous complete generation");
write(sibling, "unrelated sibling");
std::size_t writes = 0;
SaveService service({.fault_hook = [&](SavePhase phase) -> std::uint32_t {
if (phase != failed_phase) return 0;
if (phase == SavePhase::WriteStage && ++writes == 1) return 0;
return ERROR_DISK_FULL;
}});
const std::string bytes(150000, 'n');
auto submitted = service.try_submit(request(path, bytes));
const auto failed = completed(submitted);
service.shutdown();
const bool published = failed_phase == SavePhase::Published;
require(failed.error == SaveError::Injected && failed.phase == failed_phase &&
failed.native_error == ERROR_DISK_FULL, "incorrect phase failure reporting");
require(failed.visible_on_disk == published && failed.durability_unknown == published,
"failure incorrectly reported publication or rollback");
require(read(path) == (published ? bytes : "previous complete generation"),
"failure exposed incomplete data or lost previous slot");
require(read(sibling) == "unrelated sibling", "cleanup removed an unowned staging sibling");
require(failed.cleanup_error == 0 && failed.retained_staging_file.empty(), "cleanup failed");
only_files(directory, 2);
}
}
Test SaveServiceTests::partial_staging_is_never_visible() {
TemporaryDirectory directory;
const auto path = directory.path / L"slot.bin";
write(path, "old");
auto gate = std::make_shared<Gate>();
std::size_t writes = 0;
SaveService service({.fault_hook = [gate, &writes](SavePhase phase) -> std::uint32_t {
if (phase == SavePhase::WriteStage && ++writes == 2) gate->wait();
return 0;
}});
const std::string bytes(150000, 'n');
auto submitted = service.try_submit(request(path, bytes));
gate->await_entry();
require(read(path) == "old", "partial staging replaced old slot");
require(submitted.completion.wait_for(0s) == std::future_status::timeout, "gate did not block writer");
gate->open();
require(completed(submitted).succeeded() && read(path) == bytes, "complete generation was not published");
}
Test SaveServiceTests::fifo_bound_snapshot_lifetime_and_shutdown_drain() {
TemporaryDirectory directory;
const auto path = directory.path / L"slot.bin";
auto gate = std::make_shared<Gate>();
auto snapshot = std::make_shared<const std::string>("captured tick 123");
std::weak_ptr<const std::string> lifetime = snapshot;
SaveService service({.capacity = 2});
SaveRequest immutable{path, 123, session(), [snapshot, gate] { gate->wait(); return *snapshot; }};
auto first = service.try_submit(immutable);
immutable.produce = {};
snapshot.reset();
gate->await_entry();
require(!lifetime.expired(), "queued save did not retain immutable snapshot");
// This producer cannot run until the first is released. Admission itself
// must finish while that writer is blocked (without a disk/producer lock).
auto caller = std::async(std::launch::async, [&] { return service.try_submit(request(path, "newer", 124)); });
require(caller.wait_for(2s) == std::future_status::ready, "submission waited on the writer");
auto second = caller.get();
require(second.admission == SaveAdmission::Accepted && second.request_id == first.request_id + 1,
"second FIFO request not admitted");
std::atomic<std::size_t> rejected_invocations{0};
SaveRequest third{path, 125, session(), [&] { ++rejected_invocations; return "not accepted"; }};
const auto rejected = service.try_submit(third);
require(rejected.admission == SaveAdmission::Busy && rejected.request_id == 0 &&
!rejected.completion.valid() && static_cast<bool>(third.produce), "capacity did not include running request");
std::promise<void> shutdown_started;
auto starting = shutdown_started.get_future();
auto draining = std::async(std::launch::async, [&] { shutdown_started.set_value(); service.shutdown(); });
starting.get();
const auto deadline = std::chrono::steady_clock::now() + 2s;
SaveAdmission while_draining;
do {
while_draining = service.try_submit(third).admission;
if (while_draining == SaveAdmission::Closed) break;
std::this_thread::yield();
} while (std::chrono::steady_clock::now() < deadline);
require(while_draining == SaveAdmission::Closed, "shutdown held admission lock while draining");
require(draining.wait_for(0s) == std::future_status::timeout, "shutdown did not wait for accepted work");
gate->open();
require(draining.wait_for(10s) == std::future_status::ready, "shutdown failed to drain");
draining.get();
require(completed(first).succeeded() && completed(second).succeeded(), "accepted saves lost during shutdown");
require(read(path) == "newer", "older FIFO request overwrote newer save");
require(lifetime.expired(), "completed save unnecessarily retained its snapshot");
require(rejected_invocations == 0, "rejected producer was invoked");
require(service.try_submit(third).admission == SaveAdmission::Closed, "shutdown did not close admission");
}
Test SaveServiceTests::failed_producer_does_not_stop_writer() {
TemporaryDirectory directory;
const auto path = directory.path / L"slot.bin";
write(path, "old");
SaveService service;
SaveRequest broken{path, 1, session(), []() -> std::string { throw std::runtime_error("producer failure"); }};
auto first = service.try_submit(broken);
const auto failed = completed(first);
require(failed.error == SaveError::ProducerFailed && failed.phase == SavePhase::Materialize &&
!failed.visible_on_disk && read(path) == "old", "producer failure changed the slot");
auto second = service.try_submit(request(path, "recovered"));
require(completed(second).succeeded() && read(path) == "recovered", "writer stopped after producer failure");
service.shutdown();
only_files(directory, 1);
}
Test SaveServiceTests::invalid_missing_parent_and_sharing_failure() {
TemporaryDirectory directory;
SaveService service;
auto relative = request(L"relative.bin", "bytes");
require(service.try_submit(relative).admission == SaveAdmission::InvalidRequest, "relative path accepted");
auto nil = request(directory.path / L"nil.bin", "bytes");
nil.session = {};
require(service.try_submit(nil).admission == SaveAdmission::InvalidRequest, "nil session accepted");
auto absent = service.try_submit(request(directory.path / L"missing" / L"slot.bin", "bytes"));
const auto absent_result = completed(absent);
require(absent_result.error == SaveError::Io && absent_result.phase == SavePhase::CreateStage &&
!absent_result.visible_on_disk, "missing parent was not rejected by the writer");
const auto path = directory.path / L"locked.bin";
write(path, "locked previous generation");
{
Reader lock(path, FILE_SHARE_READ);
auto blocked = service.try_submit(request(path, "replacement"));
const auto result = completed(blocked);
require(result.error == SaveError::Io && result.phase == SavePhase::Publish &&
result.native_error != 0 && !result.visible_on_disk && !result.durability_unknown,
"sharing failure was not reported before publication");
require(lock.read() == "locked previous generation", "sharing failure modified existing file");
}
auto retry = service.try_submit(request(path, "replacement"));
require(completed(retry).succeeded() && read(path) == "replacement", "sharing failure stopped writer");
service.shutdown();
only_files(directory, 1);
}
Test SaveServiceTests::concurrent_submission_identity_matches_publication_order() {
TemporaryDirectory directory;
const auto path = directory.path / L"slot.bin";
SaveService service({.capacity = 16});
constexpr std::size_t callers = 8;
std::latch start(callers);
std::array<SaveSubmission, callers> submissions;
std::array<std::thread, callers> threads;
for (std::size_t index = 0; index < callers; ++index) {
threads[index] = std::thread([&, index] {
const auto input = request(path, std::to_string(index));
start.arrive_and_wait();
do {
submissions[index] = service.try_submit(input);
if (submissions[index].admission == SaveAdmission::Busy) std::this_thread::yield();
} while (submissions[index].admission == SaveAdmission::Busy);
});
}
for (auto& thread : threads) thread.join();
service.shutdown();
std::array<std::uint64_t, callers> ids;
std::size_t newest = 0;
for (std::size_t index = 0; index < callers; ++index) {
require(completed(submissions[index]).succeeded(), "concurrent save failed");
ids[index] = submissions[index].request_id;
if (ids[index] > ids[newest]) newest = index;
}
require(read(path) == std::to_string(newest), "publication order disagreed with acceptance identity");
std::ranges::sort(ids);
for (std::size_t index = 0; index < callers; ++index) require(ids[index] == index + 1, "duplicate or missing identity");
only_files(directory, 1);
}
Test SaveServiceTests::empty_file_and_size_limit() {
TemporaryDirectory directory;
const auto path = directory.path / L"slot.bin";
SaveService service({.max_bytes = 3});
auto empty = service.try_submit(request(path, ""));
require(completed(empty).succeeded() && read(path).empty(), "empty save failed");
auto large = service.try_submit(request(path, "four"));
const auto rejected = completed(large);
require(rejected.error == SaveError::TooLarge && !rejected.visible_on_disk && read(path).empty(),
"oversized generation modified slot");
service.shutdown();
only_files(directory, 1);
}
Test SaveServiceTests::self_shutdown_is_rejected_without_closing_service() {
TemporaryDirectory directory;
const auto path = directory.path / L"slot.bin";
SaveService service;
SaveRequest recursive{path, 1, session(), [&]() -> std::string { service.shutdown(); return "unreachable"; }};
auto first = service.try_submit(recursive);
require(completed(first).error == SaveError::ProducerFailed, "writer self-join did not fail safely");
auto second = service.try_submit(request(path, "still running"));
require(completed(second).succeeded(), "self-join closed service");
}
} // namespace
+407
View File
@@ -0,0 +1,407 @@
#include "settlement/core/command_dispatcher.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <array>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
namespace {
using namespace settlement;
using Void::Testing::expect_throw;
using Void::Testing::Test;
constexpr TrustedClient host{colony_host};
constexpr TrustedClient guest{2};
thread_local std::optional<CommandMutationPhase> injected_failure;
void observe_mutation(CommandMutationPhase phase) {
if (injected_failure == phase) throw std::runtime_error("injected command mutation failure");
}
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
SessionIdentity session_identity(std::uint8_t incarnation = 1) {
Void::Uuid::Uuid world;
world.bytes.back() = 41;
Void::Uuid::Uuid session;
session.bytes.back() = incarnation;
return {world, session, 1};
}
CommandEnvelope envelope(std::uint64_t request, SessionPayload payload,
SessionIdentity identity = session_identity()) {
return {command_envelope_version, identity.world, identity.session, identity.city, request, payload};
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
std::unique_ptr<World> load_state(const std::string& bytes, std::size_t workers = 2) {
std::istringstream input(bytes, std::ios::binary);
return World::read_save(input, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
}
void require_completed(const DispatchReceipt& receipt, CommandStatus expected, std::uint64_t tick,
std::uint64_t revision) {
require(receipt == DispatchReceipt{DispatchStatus::Completed, expected, tick, revision},
"the completed result differs from the authoritative outcome");
}
struct [[= Void::Testing::name("SessionTests")]] SessionTests : Void::Testing::Suite<SessionTests> {
[[= Void::Testing::tag("session")]] Test test_session_configuration_requires_valid_identity_and_capacity();
[[= Void::Testing::tag("session")]] Test test_two_clients_replay_accepted_and_rejected_results();
[[= Void::Testing::tag("session")]] Test test_conflicting_reuse_checks_every_payload_field_and_context();
[[= Void::Testing::tag("session")]] Test test_transient_rejections_preserve_request_order();
[[= Void::Testing::tag("session")]] Test test_capacity_retains_all_old_receipts_for_each_client();
[[= Void::Testing::tag("session")]] Test test_rollback_fences_old_session_before_receipt_lookup();
[[= Void::Testing::tag("session")]] Test test_dispatch_is_identical_in_reference_and_worker_modes();
[[= Void::Testing::tag("session")]] Test test_legacy_cabin_placement_uses_the_same_ledger();
[[= Void::Testing::tag("session")]] Test test_ledger_can_be_staged_with_an_unpublished_world();
[[= Void::Testing::tag("session")]] Test test_exception_fences_uncommitted_receipts_and_preserves_old_results();
};
Test SessionTests::test_session_configuration_requires_valid_identity_and_capacity() {
auto invalid = session_identity();
invalid.world = {};
expect_throw<std::invalid_argument>([&] { CommandDispatcher dispatcher(invalid); });
invalid = session_identity();
invalid.session = {};
expect_throw<std::invalid_argument>([&] { CommandDispatcher dispatcher(invalid); });
invalid = session_identity();
invalid.city = 0;
expect_throw<std::invalid_argument>([&] { CommandDispatcher dispatcher(invalid); });
expect_throw<std::invalid_argument>([] { CommandDispatcher dispatcher(session_identity(), {0}); });
expect_throw<std::invalid_argument>([] {
CommandDispatcher dispatcher(session_identity(), {std::numeric_limits<std::size_t>::max()});
});
CommandDispatcher dispatcher(session_identity());
require(dispatcher.next_request(host) == 1 && dispatcher.next_request(guest) == 1 &&
dispatcher.next_request({0}) == 0 && !dispatcher.faulted(),
"new session sequence or client validation is incorrect");
}
Test SessionTests::test_two_clients_replay_accepted_and_rejected_results() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity());
const auto pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1});
const auto guest_pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 0});
const auto first_bed = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto second_bed = envelope(2, CommandPayload{CommandKind::PlaceBed, {17, 18}, 1});
const auto occupied = envelope(3, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto resume = envelope(3, CommandPayload{CommandKind::SetPaused, {}, 0});
const auto paused = dispatcher.dispatch(*world, host, pause);
const auto denied = dispatcher.dispatch(*world, guest, guest_pause);
const auto host_bed = dispatcher.dispatch(*world, host, first_bed);
const auto guest_bed = dispatcher.dispatch(*world, guest, second_bed);
const auto invalid = dispatcher.dispatch(*world, guest, occupied);
require_completed(paused, CommandStatus::Accepted, 0, 1);
require_completed(denied, CommandStatus::Unauthorized, 0, 1);
require_completed(host_bed, CommandStatus::Accepted, 0, 2);
require_completed(guest_bed, CommandStatus::Accepted, 0, 3);
require_completed(invalid, CommandStatus::InvalidTarget, 0, 3);
require_completed(dispatcher.dispatch(*world, host, resume), CommandStatus::Accepted, 0, 4);
for (int tick = 0; tick < 30; ++tick) world->step();
const auto before_retry = saved_state(*world);
require(dispatcher.dispatch(*world, host, pause) == paused &&
dispatcher.dispatch(*world, guest, guest_pause) == denied &&
dispatcher.dispatch(*world, host, first_bed) == host_bed &&
dispatcher.dispatch(*world, guest, second_bed) == guest_bed &&
dispatcher.dispatch(*world, guest, occupied) == invalid,
"a delayed retry changed its original outcome, tick or revision");
require(saved_state(*world) == before_retry && !world->paused(),
"a repeated operation applied its effects again");
const auto corrected = envelope(4, CommandPayload{CommandKind::PlaceBed, {18, 18}});
require_completed(dispatcher.dispatch(*world, guest, corrected), CommandStatus::Accepted, 30, 5);
require(world->next_command_sequence(1) == 4 && world->next_command_sequence(2) == 3 &&
dispatcher.next_request(host) == 4 && dispatcher.next_request(guest) == 5,
"dispatcher rejections changed the legacy accepted-command sequence");
require(dispatcher.lookup(guest, occupied) == invalid,
"reconnection to the same trusted slot lost a rejected result");
}
Test SessionTests::test_conflicting_reuse_checks_every_payload_field_and_context() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity());
const auto original = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto recorded = dispatcher.dispatch(*world, host, original);
const auto before = saved_state(*world);
const auto conflict = [&](CommandEnvelope changed) {
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::Conflict,
"changed payload reused a completed request");
require(saved_state(*world) == before && dispatcher.receipt_count(host) == 1,
"conflicting reuse changed the world or its original record");
};
auto changed = original;
++changed.city;
conflict(changed);
changed = original;
std::get<CommandPayload>(changed.payload).kind = CommandKind::SetForaging;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).cell.x;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).value;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).destination.y;
conflict(changed);
changed = original;
++std::get<CommandPayload>(changed.payload).resident;
conflict(changed);
changed = original;
changed.payload = LegacyCabinPayload{{5, 5}, {3, 3}, {4, 3}};
conflict(changed);
changed = original;
++changed.version;
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::UnsupportedVersion,
"cached result bypassed protocol validation");
changed = original;
changed.world.bytes.back() ^= 1;
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::WrongWorld,
"cached result bypassed world validation");
changed = original;
changed.session.bytes.back() ^= 1;
require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::StaleSession,
"cached result bypassed incarnation validation");
require(dispatcher.dispatch(*world, {0}, original).status == DispatchStatus::UnauthorizedClient &&
dispatcher.dispatch(*world, {3}, original).status == DispatchStatus::UnauthorizedClient &&
dispatcher.dispatch(*world, host, original) == recorded && saved_state(*world) == before,
"a transport identity error changed a retained result");
}
Test SessionTests::test_transient_rejections_preserve_request_order() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity());
const auto before = saved_state(*world);
auto command = envelope(0, CommandPayload{CommandKind::PlaceBed, {16, 18}});
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::InvalidRequest,
"request zero was accepted");
command.request = std::numeric_limits<std::uint64_t>::max();
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::OutOfOrder,
"request arithmetic wrapped at the uint64 boundary");
command.request = 2;
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::OutOfOrder &&
dispatcher.next_request(host) == 1 && !dispatcher.lookup(host, command),
"a missing request advanced the ledger");
command.request = 1;
command.session = {};
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::StaleSession,
"nil session was accepted");
command = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
command.world = {};
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::WrongWorld &&
saved_state(*world) == before,
"nil world or transient rejection changed state");
command = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
command.city = 9;
require_completed(dispatcher.dispatch(*world, host, command), CommandStatus::Unauthorized, 0, 0);
require(saved_state(*world) == before && dispatcher.next_request(host) == 2,
"city denial mutated state or failed to retain the rejection");
command.city = 1;
require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::Conflict,
"corrected city reused an already completed number");
command.request = 2;
require_completed(dispatcher.dispatch(*world, host, command), CommandStatus::Accepted, 0, 1);
const auto unknown = envelope(3, CommandPayload{static_cast<CommandKind>(255)});
require_completed(dispatcher.dispatch(*world, host, unknown), CommandStatus::InvalidTarget, 0, 1);
require(dispatcher.next_request(host) == 4 && world->next_command_sequence(1) == 2,
"unsupported action confused dispatcher and legacy sequences");
const auto extreme_room = envelope(4, CommandPayload{CommandKind::PlaceRoom,
{std::numeric_limits<std::int32_t>::min(), 0}, 0, {std::numeric_limits<std::int32_t>::max(), 4}});
const auto before_extreme = saved_state(*world);
require_completed(dispatcher.dispatch(*world, host, extreme_room), CommandStatus::InvalidTarget, 0, 1);
require(saved_state(*world) == before_extreme, "unbounded room coordinates reached legacy size arithmetic");
}
Test SessionTests::test_capacity_retains_all_old_receipts_for_each_client() {
auto world = make_first_colony(2);
CommandDispatcher dispatcher(session_identity(), {2});
const auto first = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto second = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto one = dispatcher.dispatch(*world, host, first);
const auto two = dispatcher.dispatch(*world, host, second);
require_completed(one, CommandStatus::Accepted, 0, 1);
require_completed(two, CommandStatus::InvalidTarget, 0, 1);
const auto before = saved_state(*world);
const auto third = envelope(3, CommandPayload{CommandKind::PlaceBed, {17, 18}});
require(dispatcher.dispatch(*world, host, third).status == DispatchStatus::Busy &&
dispatcher.dispatch(*world, host, third).status == DispatchStatus::Busy,
"full receipt ledger admitted a new effect");
require(dispatcher.next_request(host) == 3 && dispatcher.receipt_count(host) == 2 &&
dispatcher.dispatch(*world, host, first) == one && dispatcher.dispatch(*world, host, second) == two &&
saved_state(*world) == before,
"capacity backpressure evicted/reexecuted an old receipt");
require_completed(dispatcher.dispatch(*world, guest,
envelope(1, CommandPayload{CommandKind::PlaceBed, {17, 18}})), CommandStatus::Accepted, 0, 2);
require(dispatcher.next_request(guest) == 2 && dispatcher.receipt_count({0}) == 0,
"one client's retention capacity blocked another client");
}
Test SessionTests::test_rollback_fences_old_session_before_receipt_lookup() {
auto world = make_first_colony(2);
const auto early = saved_state(*world);
CommandDispatcher previous(session_identity());
const auto old = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}});
require_completed(previous.dispatch(*world, host, old), CommandStatus::Accepted, 0, 1);
for (int tick = 0; tick < 20; ++tick) world->step();
auto restored = load_state(early);
CommandDispatcher current(session_identity(2));
require(current.dispatch(*restored, host, old).status == DispatchStatus::StaleSession &&
current.lookup(host, old)->status == DispatchStatus::StaleSession &&
saved_state(*restored) == early && current.next_request(host) == 1,
"a request from before rollback changed or queried the new incarnation");
const auto fresh = envelope(1, std::get<CommandPayload>(old.payload), session_identity(2));
const auto accepted = current.dispatch(*restored, host, fresh);
require_completed(accepted, CommandStatus::Accepted, 0, 1);
const auto after = saved_state(*restored);
require(current.dispatch(*restored, host, fresh) == accepted && saved_state(*restored) == after,
"a retry in the new session executed twice");
}
Test SessionTests::test_dispatch_is_identical_in_reference_and_worker_modes() {
const auto initial = make_first_colony(2);
const auto bytes = saved_state(*initial);
constexpr std::array<std::size_t, 4> worker_counts{1, 2, 6, 12};
std::array<std::unique_ptr<World>, 4> worlds;
std::array dispatchers{CommandDispatcher(session_identity()), CommandDispatcher(session_identity()),
CommandDispatcher(session_identity()), CommandDispatcher(session_identity())};
for (std::size_t index = 0; index < worlds.size(); ++index) worlds[index] = load_state(bytes, worker_counts[index]);
const auto issue = [&](TrustedClient client, CommandEnvelope command, CommandStatus status) {
const auto expected = dispatchers[0].dispatch(*worlds[0], client, command);
require(expected.status == DispatchStatus::Completed && expected.command_status == status,
"reference command failed its expected domain check");
for (std::size_t index = 1; index < worlds.size(); ++index) {
require(dispatchers[index].dispatch(*worlds[index], client, command) == expected,
"dispatch receipt differs across worker modes");
}
};
issue(host, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::Accepted);
issue(guest, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::InvalidTarget);
issue(guest, envelope(2, CommandPayload{CommandKind::PlaceBed, {17, 18}, 1}), CommandStatus::Accepted);
issue(host, envelope(2, CommandPayload{CommandKind::PlaceBed, {18, 18}}), CommandStatus::Accepted);
issue(host, envelope(3, CommandPayload{CommandKind::SetForaging, {14, 12}, 1}), CommandStatus::Accepted);
for (int tick = 0; tick < 700; ++tick) {
if (tick == 30) {
issue(host, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::Accepted);
issue(guest, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::InvalidTarget);
}
worlds[0]->step();
const auto expected = saved_state(*worlds[0]);
for (std::size_t index = 1; index < worlds.size(); ++index) {
worlds[index]->step();
require(saved_state(*worlds[index]) == expected, "authoritative dispatch world diverged by worker count");
}
}
require(worlds[0]->scenario_progress().completed && worlds[0]->meals_eaten() >= 3,
"the dispatched colony failed to build and feed its residents");
}
Test SessionTests::test_legacy_cabin_placement_uses_the_same_ledger() {
World world(1, 10, 10);
CommandDispatcher dispatcher(session_identity());
const auto cabin = envelope(1, LegacyCabinPayload{{5, 5}, {3, 3}, {4, 3}});
const auto denied = dispatcher.dispatch(world, guest, cabin);
require_completed(denied, CommandStatus::Unauthorized, 0, 0);
const auto accepted = dispatcher.dispatch(world, host, cabin);
require_completed(accepted, CommandStatus::Accepted, 0, 1);
require(world.production_orders().size() == 6 && world.production_orders().back().recipe == RecipeId::BuildCabin,
"legacy placement did not queue its cabin and five material orders");
const auto bytes = saved_state(world);
require(dispatcher.dispatch(world, host, cabin) == accepted &&
dispatcher.dispatch(world, guest, cabin) == denied && saved_state(world) == bytes,
"legacy cabin retry was applied again");
auto occupied = cabin;
occupied.request = 2;
require_completed(dispatcher.dispatch(world, host, occupied), CommandStatus::InvalidTarget, 0, 1);
require(saved_state(world) == bytes && dispatcher.next_request(host) == 3,
"invalid legacy placement partially changed the world");
auto changed = cabin;
std::get<LegacyCabinPayload>(changed.payload).sawmill.x = 2;
require(dispatcher.dispatch(world, host, changed).status == DispatchStatus::Conflict,
"cabin workshop change bypassed payload conflict detection");
auto colony = make_first_colony(2);
CommandDispatcher active(session_identity());
require_completed(active.dispatch(*colony, host, cabin), CommandStatus::Unavailable, 0, 0);
}
Test SessionTests::test_ledger_can_be_staged_with_an_unpublished_world() {
auto world = make_first_colony(2);
CommandDispatcher committed(session_identity());
require_completed(committed.dispatch(*world, host,
envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1})), CommandStatus::Accepted, 0, 1);
const auto before = saved_state(*world);
auto candidate = load_state(before);
auto staged = committed;
const auto building = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
const auto prepared = staged.dispatch(*candidate, host, building);
require_completed(prepared, CommandStatus::Accepted, 0, 2);
require(!committed.lookup(host, building) && committed.next_request(host) == 2 &&
saved_state(*world) == before && saved_state(*candidate) != before,
"an unpublished candidate leaked its result or world state");
committed = std::move(staged);
world = std::move(candidate);
const auto published = saved_state(*world);
require(committed.dispatch(*world, host, building) == prepared && saved_state(*world) == published,
"a committed candidate lost its retained receipt");
}
Test SessionTests::test_exception_fences_uncommitted_receipts_and_preserves_old_results() {
for (const auto phase : {CommandMutationPhase::BeforeMutation, CommandMutationPhase::AfterMutation}) {
auto committed_world = make_first_colony(2);
CommandDispatcher committed(session_identity(), {8, observe_mutation});
const auto pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1});
const auto previous = committed.dispatch(*committed_world, host, pause);
require_completed(previous, CommandStatus::Accepted, 0, 1);
const auto committed_bytes = saved_state(*committed_world);
auto candidate = load_state(committed_bytes);
auto staged = committed;
const auto building = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}});
injected_failure = phase;
bool observed_failure = false;
try {
static_cast<void>(staged.dispatch(*candidate, host, building));
} catch (const std::runtime_error& error) {
observed_failure = std::string_view(error.what()) == "injected command mutation failure";
}
injected_failure.reset();
require(observed_failure && staged.faulted(), "an exceptional command did not fence the candidate");
require((saved_state(*candidate) != committed_bytes) == (phase == CommandMutationPhase::AfterMutation),
"the mutation observer did not bracket the actual game effect");
require(staged.lookup(host, pause) == previous && staged.dispatch(*candidate, host, pause) == previous,
"faulted state hid or reexecuted an earlier completed result");
require(staged.lookup(host, building)->status == DispatchStatus::Faulted &&
staged.dispatch(*candidate, host, building).status == DispatchStatus::Faulted,
"an uncommitted command became a replayable success");
const auto faulted_bytes = saved_state(*candidate);
require(staged.dispatch(*candidate, host,
envelope(3, CommandPayload{CommandKind::PlaceBed, {17, 18}})).status == DispatchStatus::Faulted &&
saved_state(*candidate) == faulted_bytes && staged.revision() == previous.revision,
"the faulted owner admitted another effect or committed a result revision");
require(saved_state(*committed_world) == committed_bytes && !committed.lookup(host, building) &&
committed.lookup(host, pause) == previous,
"a failed candidate leaked state or receipts into the publication");
candidate.reset();
auto restored = load_state(committed_bytes);
CommandDispatcher recovered(session_identity(2));
require(recovered.dispatch(*restored, host, building).status == DispatchStatus::StaleSession,
"recovery admitted an envelope from the retired candidate");
const auto fresh = envelope(1, building.payload, session_identity(2));
require_completed(recovered.dispatch(*restored, host, fresh), CommandStatus::Accepted, 0, 1);
}
}
} // namespace
+232
View File
@@ -0,0 +1,232 @@
#include "settlement/core/world.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <barrier>
#include <future>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
namespace {
using namespace settlement;
using Void::Testing::require;
using Void::Testing::Test;
static_assert(std::is_same_v<decltype(std::declval<const World&>().capture()),
std::shared_ptr<const World>>);
static_assert(std::is_move_constructible_v<World>);
static_assert(std::is_move_assignable_v<World>);
static_assert(!std::is_copy_constructible_v<World>);
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
void send(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
const auto receipt = world.apply_command(
{colony_host, world.next_command_sequence(colony_host), kind, cell, value});
require(receipt.status == CommandStatus::Accepted);
}
void compare_read_views(const World& source, const World& snapshot) {
require(bytes(snapshot) == bytes(source));
require(snapshot.seed() == source.seed());
require(snapshot.width() == source.width() && snapshot.height() == source.height());
require(snapshot.tick() == source.tick() && snapshot.worker_count() == source.worker_count());
require(snapshot.path_searches() == source.path_searches());
require(snapshot.path_nodes_visited() == source.path_nodes_visited());
require(snapshot.assignment_path_cache_hits() == source.assignment_path_cache_hits());
require(snapshot.jobs_completed() == source.jobs_completed());
require(snapshot.meals_eaten() == source.meals_eaten());
require(snapshot.scenario_active() == source.scenario_active());
require(snapshot.staged_beds() == source.staged_beds());
require(snapshot.paused() == source.paused());
require(snapshot.work_priority() == source.work_priority());
require(snapshot.carpenter_workshop() == source.carpenter_workshop());
for (std::uint8_t player = 1; player <= colony_player_slots; ++player) {
require(snapshot.next_command_sequence(player) == source.next_command_sequence(player));
}
for (int y = 0; y < source.height(); ++y) {
for (int x = 0; x < source.width(); ++x) {
require(snapshot.is_walkable({x, y}) == source.is_walkable({x, y}));
}
}
}
struct [[= Void::Testing::name("SnapshotTests")]] SnapshotTests : Void::Testing::Suite<SnapshotTests> {
[[= Void::Testing::tag("snapshot")]] Test test_independent_state_in_all_execution_modes();
[[= Void::Testing::tag("snapshot")]] Test test_mid_delivery_and_paused_command_state_survives_owner();
[[= Void::Testing::tag("snapshot")]] Test test_reader_runs_while_owner_advances();
[[= Void::Testing::tag("snapshot")]] Test test_capture_excludes_execution_callbacks_and_workers();
};
Test SnapshotTests::test_independent_state_in_all_execution_modes() {
constexpr std::array workers{1U, 2U, 6U};
for (const auto count : workers) {
const auto mode = count == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel;
World source(53, 12, 12, count, mode);
source.set_blocked({4, 4});
static_cast<void>(source.spawn_agent({1, 1}));
static_cast<void>(source.add_job({8, 8}, 3));
source.step();
const auto snapshot = source.capture();
compare_read_views(source, *snapshot);
require(source.agents().data() != snapshot->agents().data());
require(source.agents().front().route.data() != snapshot->agents().front().route.data());
require(source.jobs().data() != snapshot->jobs().data());
const auto expected = bytes(*snapshot);
const auto position = snapshot->agents().front().position;
const auto searches = snapshot->path_searches();
static_cast<void>(source.spawn_agent({2, 2}));
static_cast<void>(source.add_job({2, 7}, 1));
source.set_blocked({4, 4}, false);
for (int i = 0; i < 30; ++i) source.step();
require(bytes(*snapshot) == expected);
require(snapshot->agents().front().position == position);
require(snapshot->path_searches() == searches && !snapshot->is_walkable({4, 4}));
auto nested_snapshot = snapshot->capture();
compare_read_views(*snapshot, *nested_snapshot);
World moved(std::move(source));
require(moved.agents().size() == 2);
require(bytes(*snapshot) == expected);
}
}
Test SnapshotTests::test_mid_delivery_and_paused_command_state_survives_owner() {
auto source = make_first_colony(6);
send(*source, CommandKind::PlaceBed, {16, 18});
send(*source, CommandKind::PlaceBed, {17, 18}, 1);
send(*source, CommandKind::PlaceBed, {18, 18});
bool carrying = false;
for (int step = 0; step < 300 && !carrying; ++step) {
source->step();
carrying = source->assignment_path_cache_hits() > 0 &&
std::any_of(source->agents().begin(), source->agents().end(), [](const Agent& agent) {
return !agent.inventory.empty() && agent.production_index != no_entity_index;
});
}
require(carrying);
send(*source, CommandKind::SetPriority, {}, 1);
send(*source, CommandKind::SetPaused, {}, 1);
auto snapshot = source->capture();
compare_read_views(*source, *snapshot);
require(snapshot->paused() && snapshot->work_priority() == WorkPriority::FoodFirst);
require(source->storages().data() != snapshot->storages().data());
require(source->production_orders().data() != snapshot->production_orders().data());
bool nested_materials = false;
bool nested_routes = false;
bool nested_stacks = false;
for (std::size_t i = 0; i < source->production_orders().size(); ++i) {
const auto& live = source->production_orders()[i];
const auto& held = snapshot->production_orders()[i];
if (!live.materials.empty()) {
require(live.materials.data() != held.materials.data());
nested_materials = true;
}
for (std::size_t stop = 0; stop < live.delivery_stops.size(); ++stop) {
if (live.delivery_stops[stop].route_to_next.empty()) continue;
require(live.delivery_stops[stop].route_to_next.data() !=
held.delivery_stops[stop].route_to_next.data());
nested_routes = true;
}
}
for (std::size_t i = 0; i < source->storages().size(); ++i) {
if (source->storages()[i].items.empty()) continue;
require(source->storages()[i].items.data() != snapshot->storages()[i].items.data());
nested_stacks = true;
}
require(nested_materials && nested_routes && nested_stacks);
const auto expected = bytes(*snapshot);
const auto hits = snapshot->assignment_path_cache_hits();
const auto sequence = snapshot->next_command_sequence(colony_host);
send(*source, CommandKind::SetPaused, {}, 0);
for (int step = 0; step < 100; ++step) source->step();
source.reset();
require(bytes(*snapshot) == expected);
require(snapshot->paused() && snapshot->assignment_path_cache_hits() == hits);
require(snapshot->next_command_sequence(colony_host) == sequence);
std::istringstream first(expected, std::ios::binary);
std::istringstream second(expected, std::ios::binary);
auto serial = World::read_save(first, 1, ExecutionMode::SerialReference);
auto parallel = World::read_save(second, 2);
send(*serial, CommandKind::SetPaused, {}, 0);
send(*parallel, CommandKind::SetPaused, {}, 0);
for (int step = 0; step < 100; ++step) {
serial->step();
parallel->step();
require(bytes(*serial) == bytes(*parallel));
}
require(bytes(*snapshot) == expected);
}
Test SnapshotTests::test_reader_runs_while_owner_advances() {
auto source = make_first_colony(2);
send(*source, CommandKind::PlaceBed, {16, 18});
source->step();
const auto snapshot = source->capture();
const auto expected = bytes(*snapshot);
std::barrier rendezvous(2);
auto reader = std::async(std::launch::async, [snapshot, expected, &rendezvous] {
bool consistent = true;
for (int step = 0; step < 32; ++step) {
rendezvous.arrive_and_wait();
try {
consistent = consistent && bytes(*snapshot) == expected;
consistent = consistent && snapshot->tick() == 1 && snapshot->agents().size() == 3;
} catch (...) {
consistent = false;
}
rendezvous.arrive_and_wait();
}
return consistent;
});
// Drop this participant before joining the reader if an owner step fails.
auto release_reader = Void::Scope::on_exit([&] { rendezvous.arrive_and_drop(); });
for (int step = 0; step < 32; ++step) {
rendezvous.arrive_and_wait();
source->step();
rendezvous.arrive_and_wait();
}
release_reader.release();
require(reader.get());
require(source->tick() == 33 && bytes(*snapshot) == expected);
}
Test SnapshotTests::test_capture_excludes_execution_callbacks_and_workers() {
std::shared_ptr<const World> snapshot;
auto callback_state = std::make_shared<std::atomic<int>>(0);
std::weak_ptr<std::atomic<int>> weak_state = callback_state;
auto source = [&] {
WorkerPoolOptions options;
options.before_worker_start = [callback_state](std::size_t) { ++*callback_state; };
return std::make_unique<World>(61, 8, 8, 2, ExecutionMode::Parallel, std::move(options));
}();
static_cast<void>(source->spawn_agent({1, 1}));
static_cast<void>(source->add_job({6, 6}, 4));
auto unstarted = source->capture();
require(callback_state->load() == 0);
source->step();
require(callback_state->load() == 2);
snapshot = source->capture();
require(callback_state->load() == 2);
const auto expected = bytes(*snapshot);
callback_state.reset();
source.reset();
require(weak_state.expired());
require(snapshot->worker_count() == 2 && bytes(*snapshot) == expected);
require(unstarted->tick() == 0 && unstarted->agents().size() == 1);
}
} // namespace