Compare commits

..
44 changed files with 2615 additions and 99 deletions

No files matched your search

+7 -2
View File
@@ -23,7 +23,7 @@ function(add_void_library)
set(BUILD_SHARED_LIBS OFF)
set(VOID_ENABLE_TESTING OFF)
set(VOID_ENABLE_BENCHMARKS OFF)
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Text Time)
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Math Text Time)
set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON)
if(BUILD_TESTING)
list(APPEND VOID_ENABLED_MODULES Testing)
@@ -40,6 +40,8 @@ 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
@@ -58,7 +60,7 @@ target_include_directories(settlement_core
target_compile_features(settlement_core PUBLIC cxx_std_23)
target_link_libraries(settlement_core
PUBLIC Threads::Threads Void::Async Void::Core Void::Time
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Text
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Math Void::Text
)
if(MSVC)
@@ -112,8 +114,11 @@ endif()
if(BUILD_TESTING)
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
+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" Идёт засевать поле";
+12
View File
@@ -75,3 +75,15 @@ wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag
```
Далее в M01 входят исполнитель Void с проверкой отказов, манифесты правил, авторитетный диспетчер команд, фоновый такт, снимки и транзакционная загрузка/запись. Приёмка этих систем ведётся отдельными коммитами.
### Ветки разработки и запросы на слияние
Для этапов используются ветки `milestone/*`, для систем — `system/*`. По поручению пользователя ветка [integration/roadmap](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/src/branch/integration/roadmap) содержит `chore/integrate-void-library`, `chore/plans` и принятые изменения каждой ветки этапа и системы. После проверки совместной сборки ответственный обновляет накопительную ветку. Она служит для получения всей работы одним checkout.
У каждой опубликованной рабочей ветки есть свой запрос в `main`. Описание ссылается на более ранние запросы этой серии. При параллельной работе подписи ссылок указывают, какие изменения послужили базой и какие развивались независимо. Новые коммиты ветки попадают в уже открытый запрос. Первыми открыты [VoidLibrary #3](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/3), [план #4](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/4), [M00 #5](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/5), [M01 #6](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/6), [модули правил S19 #7](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/7), [исполнитель S01 #8](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/8), [диспетчер S16 #9](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) и [сохранения S15 #10](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/10).
В `2224299` вместе собраны снимки мира, диспетчер команд, служба записи и кодек контрольных точек. Windows x64 Release под Wine прошла 82 из 82 случаев ядра и 4 из 4 LAN. Отдельная ветка S15 на `db4ac30` прошла 59 из 59 и 4 из 4 соответственно. По трём прогонам на поле 80×80 с шестью потоками медианы p50/p95 захвата снимка составили 2/4 мкс для 50 жителей и 23/68 мкс для 500. После 32 тактов прогрева каждый прогон измерял 240 захватов. При подключении службы записи к окну лимит одного файла должен вмещать `max_checkpoint_bytes`. Частота тактов, отзывчивость окна во время записи и работа на физической Windows проверяются отдельно. [Проверка команд и записи](tasks/M01-V4.md) · [Проверка снимка и контрольной точки](tasks/M01-V5.md) · [Совместная сборка](tasks/M01-V6.md) · [План постоянных ссылок](tasks/M01-P3.md)
В `cf0cc2f` объединены проверенные коммиты S19 `de38aff` и S01 `68f91a2`. После объединения под Wine 11 прошли 51 из 51 теста ядра и 4 из 4 тестов LAN, включая формат сохранений 13 и протокол 11. Независимый проверяющий сверил обе родительские версии, наследование параметров компиляции и встроенную реализацию SHA-256. [План владельца симуляции](tasks/M01-P2.md) · [Проверка библиотеки](tasks/M01-R2.md) · [Разбор отказов](tasks/M01-F2.md) · [Принятые контракты](tasks/M01-F3.md) · [Проверка S01 и S19](tasks/M01-V2.md) · [Проверка интеграции](tasks/M01-V3.md)
Срез S06 сохранил ссылки на склады и источники при удалении более раннего элемента. Два контрольных набора из 738 386 и 393 857 байтов совпали со старой сборкой в последовательном режиме и на 2/6/12 потоках. Второй набор включает разбор склада во время многоэтапной доставки. Изменения опубликованы отдельно в [S06 #11](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11). В `4ba64f7` также вошла фоновая подготовка старых и новых сохранений. В объединённой Windows x64-сборке под Wine прошли 106 тестов ядра и 4 LAN. Публичный аналог ограниченного чтения в Windows отслеживается в [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). [Проверка двух компонентов](tasks/M01-V8.md) · [Интеграционная проверка](tasks/M01-V9.md)
+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 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 @@
# 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.
+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 @@
# 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 @@
# 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.
+4
View File
@@ -25,6 +25,10 @@
### Переход к авторитетному такту
Ядро выполняет такты по 50 мс в отдельном потоке. На каждой завершённой границе `SimulationRuntime` публикует независимый снимок и квитанции приказов. Пока идёт новый такт, читатели могут продолжать работу с прежней версией. Остановка игрового времени сохраняет возможность отдать приказ. Результат загрузки заменяет мир после повторной проверки номера запроса и инкарнации, в том числе при откате того же сохранения. [Интерфейс владельца](../../../engine/include/settlement/core/simulation_runtime.hpp) · [Тесты такта и отказов](../../../tests/runtime_tests.cpp)
Селектор `--tag runtime` под Wine выполнил десять проверок. Среди них — 20 тактов за секунду ручных часов, чтение предыдущего снимка при задержанном рабочем задании и возврат к управляемой партии после отказа публикации. Независимая проверка и общая сборка охватили 92 случая ядра и 4 LAN. Дальнейшая приёмка M01 проверяет действия игрока через окно, обмен со старым LAN-клиентом и постоянные ссылки при удалении объектов. [Техническая проверка](../../agent-workflow/tasks/M01-V7.md)
Выделить одну воспроизводимую партию прототипа и записать последовательность приказов. Сначала пропустить её через очередь авторитетного мира и дать окну читать последний завершённый снимок. Далее заменить один участок независимого расчёта, сверить результат каждого такта, затем подключить следующий. Так первое расхождение привязано к конкретной стадии. Для суммы запасов, состояния задания и номера команды выводить в отчёт также идентификатор первого отличающегося объекта.
Проверить для нынешнего `WorkerPool` исполнителя `Void::Async::ThreadExecutor` с `FuturePool`. На частичном отказе запуска уже созданные потоки должны штатно завершиться. При заполненной очереди логическая работа остаётся в такте до исполнения. При одновременных заявках на предмет ожидаемый победитель определяется правилами арбитража. Доступность API и управляемое воспроизведение отказов записать до удаления прежнего пути. Эталонный последовательный исполнитель — новый тестовый режим. Исторический тест, отклоняющий конфигурацию с одним рабочим потоком, остаётся свидетельством поведения прототипа.
+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` и указать ссылку в задаче и коде.
- Два заказа запрашивают последнюю единицу ресурса. Только один получает резерв, свободный запас остаётся неотрицательным.
+6
View File
@@ -25,6 +25,12 @@
## Границы интерфейсов
`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` — предлагаемые новые интерфейсы. Запрос содержит слот и желаемую операцию. Снимок привязан к одному завершённому такту. Манифест описывает все необходимые блоки и контрольные суммы. Кандидат загрузки предоставляет результат проверки до замены мира. Завершение операции возвращает идентификатор запроса, состояние и диагностическую причину ошибки.
+14
View File
@@ -10,6 +10,18 @@
На Windows x64 под Wine прошли 9 сценариев для манифестов. Разбор JSON, версии, граф и хеш использованы из закреплённой VoidLibrary. Для замены локального разрешения наборов библиотечным сервисом повторить проверки транзитивных зависимостей, перестановок, конфликтов и идентичности. [Запрос в Void/Library](https://git.faumaray.com/Void/Library/issues/4)
## Выбор исполняемого профиля колонии
Первый выбор механики использует два существующих способа постройки кровати. Профиль по умолчанию собирает основание из дерева или камня, затем отдельно доставляет ткань для постели и подушки. Дополнительный пакет `settlement.plankbeds@1.0.0` задаёт простую кровать из одной доски. Для неё жители сначала выполняют распил за 12 рабочих тактов, затем собирают кровать за 14. Команды отдельной кровати и меблированной комнаты используют выбранный способ. [Профиль и создание колонии](../../../engine/include/settlement/core/colony_profile.hpp) · [Игровые проверки](../../../tests/profile_tests.cpp)
Компилятор профиля проверяет точный состав, версии и SHA-256 реализованных пакетов, затем связывает проверенные поля определения рецепта с начальной конфигурацией мира. Фабрика возвращает мир вместе с его манифестом и постоянным UUID. Настройка выполняется при запуске сценария. Поля демонстрационного определения доски в исходном пакете сохраняют прежнее содержимое. Общее исполнение произвольных данных рецепта относится к S19-W02.
Два исходных пакета и их канонический манифест закреплены проверкой с отпечатком `06d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1`, полученным из ядра до добавления профилей. Выбор по умолчанию включает эти два пакета. Дополнительный профиль разрешает их вместе с пакетом простых кроватей.
Старое сохранение с исходным манифестом может содержать любой из двух способов постройки, включая неактивный сценарий. Проверка загрузки сохраняет этот способ и манифест. Для дополнительного пакета требуется сохранённый способ простых кроватей. Изменённый пакет, неизвестная комбинация или сочетание дополнительного пакета с поэтапной сборкой получает диагностический отказ до замены партии. Общие кодеки остаются доступными для каталогов вызывающего приложения. Прежний LAN11 допускает точный исходный манифест. Интерфейс выбора профиля подключается через S18.
Семь случаев `--tag profile` прошли в Windows x64 под Wine. Оба профиля завершили цель с тремя кроватями и едой, проверены меблированная комната, материал в переноске, продолжение после загрузки и одинаковые контрольные точки на последовательном эталоне и 2/6/12 потоках. Сохранён подлинный файл схемы 1 с исходным манифестом и простой сборкой. Общая сборка прошла 113 тестов ядра и 4 LAN. Все 738 386 байтов прежней траектории совпали с исходной сборкой во всех четырёх режимах. Нативная Windows и подключение выбора в окно проверяются отдельно.
## Исходное состояние
Предметы, профессии, рецепты и команды прототипа определяются C++-типами, а стартовая партия создаётся кодом. В проверенной CMake-конфигурации подключены `Void::Binary`, `Void::Core` и `Void::Testing`. Скриптовый runtime в этот перечень не входит. План вводит новые определения контента и границу расширения. [Текущая конфигурация сборки](../../../CMakeLists.txt)
@@ -28,6 +40,8 @@
Долговременное состояние обработчика представляет собой проверяемые сериализуемые значения с явной схемой. Продолжение события хранит идентификатор шага, данные и запланированный такт. Персистентные coroutine-стеки, нативные замыкания и произвольная память интерпретатора в формат сохранения не входят. Сам обработчик выполняется с фиксированным входом и возвращает предлагаемые изменения.
Состояние обработчика получает ключ пакета, обработчика и версии схемы. Продолжение имеет постоянный идентификатор, детерминированные данные и назначенный такт. Предложения связываются с исходной ревизией снимка и инкарнацией. Владелец проверяет их в устойчивом порядке и одной операцией применяет новое состояние, продвижение генератора случайности, расписание и игровые изменения. Отказ либо устаревшая инкарнация отбрасывают весь этот результат. Исполнение Lua вводится в S19-W03.
Игровой API задаёт детерминированный порядок коллекций, отдельные потоки случайных чисел и правила числовых значений. Авторитетные решения используют разрешённые целочисленные либо явно квантованные величины. Прикладное API запрещает неупорядоченную итерацию для последовательности игровых изменений. Время берётся из номера такта. Вызовы системы, сети, произвольных файлов и нативных расширений недоступны исполняемому игровому скрипту.
Каждый обработчик ограничен по инструкциям, памяти, размеру результата и стоимости вызванных функций хоста. Счётчик Lua-инструкций дополняется ограничением работы C++-функций, поскольку эта работа выполняется вне счётчика интерпретатора. Состояние обработчика и предложения применяются атомарно. Ошибка отбрасывает его незавершённый результат и ставит авторитетное продвижение на безопасную границу с диагностикой. Состав правил мира сохраняется. [Стадии симуляции](S01.md)
+10
View File
@@ -33,6 +33,16 @@
## Первое применение правила в 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)
@@ -16,6 +16,7 @@
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 =
@@ -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
+17 -8
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;
@@ -237,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;
@@ -260,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;
@@ -282,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;
@@ -317,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;
};
@@ -413,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;
@@ -443,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;
@@ -463,6 +468,8 @@ private:
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);
@@ -492,6 +499,8 @@ private:
};
inline constexpr std::int32_t first_colony_map_size = 32;
[[nodiscard]] std::unique_ptr<World> make_first_colony(std::size_t workers);
[[nodiscard]] std::unique_ptr<World> make_first_colony(
std::size_t workers, BedConstructionMode beds = BedConstructionMode::Staged,
ExecutionMode mode = ExecutionMode::Parallel);
} // namespace settlement
+2 -3
View File
@@ -16,7 +16,6 @@
namespace settlement {
namespace {
constexpr std::string_view magic = "STHCHKPT";
constexpr std::size_t header_size = 24;
constexpr std::size_t digest_size = 32;
constexpr std::size_t fixed_metadata_size = 68;
@@ -173,7 +172,7 @@ std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
}
std::string bytes(header_size + metadata_size + body.size() + digest_size, '\0');
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}));
put_bytes(writer, wire_bytes(magic));
put_bytes(writer, wire_bytes(checkpoint_signature));
put(writer, checkpoint_version);
put(writer, static_cast<std::uint32_t>(metadata_size));
put(writer, static_cast<std::uint64_t>(body.size()));
@@ -210,7 +209,7 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
fail(CheckpointError::InvalidFrame, "frame", "Checkpoint is incomplete.");
}
Void::Binary::Reader header(wire_bytes(bytes).first(header_size));
if (!std::ranges::equal(get_bytes(header, magic.size(), "magic"), wire_bytes(magic))) {
if (!std::ranges::equal(get_bytes(header, checkpoint_signature.size(), "magic"), wire_bytes(checkpoint_signature))) {
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
}
if (get<std::uint32_t>(header, "version") != checkpoint_version) {
+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
+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;
}
+4 -1
View File
@@ -386,7 +386,10 @@ std::expected<std::vector<RulePackage>, RulesDiagnostic> builtin_rule_packages()
if (!first) return std::unexpected{first.error()};
auto second = load_rule_package("builtin/colony", colony);
if (!second) return std::unexpected{second.error()};
return std::vector<RulePackage>{std::move(*first), std::move(*second)};
constexpr std::string_view plankbeds = R"({"schema":1,"id":"settlement.plankbeds","version":"1.0.0","dependencies":[{"id":"settlement.colony","version":"1.0.0"}],"exclusive_capabilities":[],"definitions":[{"id":"settlement.plankbeds:bed","kind":"recipe","data":{"assembly":"plank","input":"settlement.colony:board","input_count":1,"saw_work_ticks":12,"work_ticks":14},"references":["settlement.colony:board"]}]})";
auto third = load_rule_package("builtin/plankbeds", plankbeds);
if (!third) return std::unexpected{third.error()};
return std::vector<RulePackage>{std::move(*first), std::move(*second), std::move(*third)};
}
std::expected<RulesManifest, RulesDiagnostic> default_rules_manifest() {
+79 -44
View File
@@ -1,6 +1,7 @@
#include "settlement/core/world.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
@@ -134,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");
@@ -298,6 +312,24 @@ 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_) +
static_cast<std::size_t>(position.x);
@@ -401,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;
}
@@ -418,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;
}
@@ -572,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;
@@ -628,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;
}
@@ -674,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;
@@ -706,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;
}
@@ -793,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();
@@ -870,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:
@@ -1244,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;
@@ -1285,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;
@@ -1341,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) {
@@ -1354,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);
@@ -1367,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 :
@@ -1376,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);
@@ -1436,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;
@@ -1449,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;
@@ -1533,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);
@@ -1554,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;
@@ -1566,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 &&
@@ -1648,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;
}
}
@@ -1717,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;
@@ -1731,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;
@@ -1740,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;
+82 -27
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 &&
+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
+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);
+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
+7
View File
@@ -218,6 +218,13 @@ Test RulesTests::test_builtin_default_and_known_digest() {
const auto first = checked(default_rules_manifest());
const auto second = checked(default_rules_manifest());
require(first == second && first.packages().size() == 2, "default rules were not reproducible");
// Recorded by profile-baseline.exe against the compiled pre-profile core.
require(rules_digest_hex(first.fingerprint()) ==
"06d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1",
"default profile fingerprint changed");
require(first.canonical_json() ==
R"({"packages":[{"id":"settlement.colony","sha256":"08e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089","version":"1.0.0"},{"id":"settlement.core","sha256":"61b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab7124188d337f","version":"1.0.0"}],"schema":1})",
"default canonical manifest changed");
const auto empty = load(package("game.core"));
require(rules_digest_hex(empty.identity().content_sha256) == "f6d1f704ccbb3ec707d2e1ba7b0db27dab8494b7787eeee10f1449dabee1477a", "package SHA-256 differs from the canonical-byte known vector");
require(empty.definitions().empty(), "empty package gained a definition");