From 4f42488d54193a770e7ef7b98df157aa2a96fc9d Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:01:43 +0300 Subject: [PATCH 01/10] Define durable custody contracts shared by the world and checkpoint codec --- docs/agent-workflow/tasks/S06-03.md | 48 +++++++++ engine/include/settlement/core/custody.hpp | 115 +++++++++++++++++++++ engine/include/settlement/core/world.hpp | 54 +++++++++- 3 files changed, 212 insertions(+), 5 deletions(-) create mode 100644 docs/agent-workflow/tasks/S06-03.md create mode 100644 engine/include/settlement/core/custody.hpp diff --git a/docs/agent-workflow/tasks/S06-03.md b/docs/agent-workflow/tasks/S06-03.md new file mode 100644 index 0000000..91fc49b --- /dev/null +++ b/docs/agent-workflow/tasks/S06-03.md @@ -0,0 +1,48 @@ +# Track real item ownership from sources through worksite and cancellation + +Task ID: S06-03 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Exclusive s06 worktree f6493e2 has checked pickups (3c997ed), durable ProductionId, current14, S18 snapshot client. docs/plan/custody.md and root M01-F8/P5 contain binding full model. Existing World loses physical cargo on arrival at a construction site; its recipes and storage share ItemStack, and historical source leases continue until production completion. S15 peer independently captures authentic historical fixtures and implements codec. + +## 2. Objective and deliverables +Implement authoritative physical ownership and bounded reservation/transfer lifecycle on every current inventory-affecting game path: grant/stock, extraction, meals, crafting, construction, return and demolition. Provide frozen in-memory data/validation contracts early for S15, raw13 representability for S16 and cancel/resume for S04. Do not publish a half-integrated version. + +## 3. Scope and non-goals +Existing modeled item types/jobs/recipes only. No regions, filters/marketplace, scripts, new graphics or custom database. World and actual operation record are the source of truth. Authoritative persistent codec, command adapters/live LAN and UI are separate owned work packages. + +## 4. Files to inspect +Read docs/plan/custody.md, plans S04/S06 and root F8/P5 (root and s06). Read entire world.hpp/world.cpp incl assign/step, stock/sources/idle/meal/all recipes, inventory_transaction, writer/validation in world_save.cpp, current schema2 and capture/runtime/old replay tests. F8 corrections on held old source IDs, work_remaining=0 and unsupported legacy states apply. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/include/settlement/core/inventory_transaction.hpp and engine/src/inventory_transaction.cpp; NEW engine/include/settlement/core/custody.hpp and engine/src/custody.cpp or narrow related source files for actual World operations; NEW tests/custody_tests.cpp; CMakeLists.txt limited to own implementation/tests; docs/plan/systems/S06.md +S15 exclusively owns all world_save/checkpoint/fixture changes, S04 later command dispatcher/cancel UI, S16 LAN. You may declare WorldSaveFormat::Current15 and agreed in-memory migration/validation seam in owned header. Never write other branches/Git/remote/Serena/children; other workers share filesystem. + +## 6. Implementation or investigation approach +Separate recipe requirements from owned stacks. Embed one nonzero durable StackId per nonempty owner/item slot. Full move into empty retains ID; splitting allocates once; merging keeps destination ID; move matching ReservationIds and keep other source reservations. World-owned counters 0 none, MAX exhausted, plan all required IDs/counts/physical capacity/balance entries/receipt storage and allocations before effect, with nonthrow final commit. Single physical count per storage/resident/ProductionId input; caches exclusively updated/rebuilt from claims. Restore snapshot copies without stale pointers. Source/sink tracking Opening+Grant+Harvest+RecipeOutput equals live+RecipeInput+Meal+Installation+StorageDemolition. Use Void::Numeric and existing #7/#8, avoid O(N²) global scans in hot step. Preserve real original source and timing/game decisions in normal v13 trajectories. + +## 7. Interfaces and data contracts +AgentId+positive durable next_admission (starts 1) keys admission; distinct tagged key namespace from TransferId+ordinal. On admission record exact request and issued transfer and increment next_admission together; pre-admission refusal unchanged. Persistent next available IDs avoid reuse; active single execution per worker. 4096 global receipts in commit order, each canonical typed input and outcome <=1024 bytes each, no opaque hash-only comparison or arbitrary route payloads. Normalized source/material lines max actual recipe units (cabin five positive units across different storages), bounded stock kinds, typed data. Retained duplicate same bytes gets exact result, conflict distinct payload, evicted old sequence Stale, future unissued rejected. Retired receipt references may identify no-longer-live objects but must be in issued ranges. Prefer compact immutable shared payloads/COW for retained snapshots; account memory/time at full retention. + +## 8. Dependencies and integration +Reservations distinct for exact item+owner, output capacity, worksite, harvest/tending. Input-backed output slot links the actual ReservationId in the same store; never counted or backed twice. Preserve old origin-storage lease until work finishes for Move/Demolish Busy. Worksite arrival moves real goods into order input, consumed only at stage completion. Research genuine existing guarantees and send actual frozen declarations immediately to root, including explicit entries/interfaces for S15 legacy migration, strict modern full validation and pure legacy representability. S04 needs World::cancel_production(ProductionId) and World::resume_production(ProductionId) or equivalent typed result. S16 needs pure preflight that correctly recognizes ALL unsupported modern states incl single canceled plank/stone-block, absent destination, partial mixed return and suspended site. + +## 9. Edge cases security and performance +On cancel pre-pickup release claims; in-transit/at-site cargo remains with same transfer/worker until all types actually deposited, with meaningful blocked reason and persistent no-destination status. Partial return exact, do not allow meals/rest/new jobs while carrying. Canceled staged bed after prior installation or already built recurring loom remains suspended under same ID/occupancy; explicit resume continues retained phase without duplicated inputs. Installed/completed final objects refuse cancel. Historical demolish/move occupied semantics continue. Completion with zero remaining and temporary refusal is a valid modern pending phase; never unsigned-decrement 0 on retry, new ordinal on actual retry; reject legacy projection if not exact. Before destroying stock record exact reason/qty and preflight replenishment production IDs as in S04. + +## 10. Acceptance criteria +1. Live single ownership and conservation for all current paths including partial splits/merge, last item, storage disappearance and worksite delivery before consumption; exact conditional refusals and repeat/eviction/conflict. 2. Cancel/return at each stage incl full/no storage and suspended partial bed/installed loom resume; actual normal World operations. 3. Snapshot immutability and deterministic serial/2/6/12, old raw13 corpora remain exact. 4. Tests for zero/MAX/overflow, duplicate/cross-owner and exhaustion, last active worker and terminal failure. 5. Frozen schema integration passes with S15 before public delivery; provide measured 500 resident, ~10K stack/2K order and full/empty 4096 receipt state costs where technically applicable. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s06-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Focused new custody tag and CTest -V; both existing byte regression probes in temp dir; S15 tests/migration validation added after interface merge. Capture p50/p95/size and actual benchmark workload/environment (5ms p95 initial Wine capture budget, disclose measured values). Use s06-custody-* logs. Keep fixtures and user saves private/isolated. + +## 12. Constraints and stop conditions +Send concrete C++ data declarations/API seam before broad implementation so S15 can progress; do not generate or edit schema15 on disk yourself. Preserve public Inventory/Storage read-facing APIs and existing behavior relied on by old tests. Never ship/claim completion until integrated codec and cancellation boundaries; alert parent on needed scope/ownership or two failed same-cause attempts. No children/Git/remote. + +## 13. Authorization and decisions +User authorizes complete roadmap. Root accepts compact bounded retention, embedded single-owner stacks and verified F8 corrections; normal multi-stage behavior and legacy bytes remain mandatory. Root integrates and publishes only fully verified compatible state. + +## 14. Return format +Return S06-03 status, frozen seam early, actual source/operations/remaining integrations, tests/goldens/perf logs. Clearly identify original old boundary vs actual strengthened ownership and any native limitations. diff --git a/engine/include/settlement/core/custody.hpp b/engine/include/settlement/core/custody.hpp new file mode 100644 index 0000000..89ab8c7 --- /dev/null +++ b/engine/include/settlement/core/custody.hpp @@ -0,0 +1,115 @@ +#pragma once + +#include +#include +#include + +namespace settlement { + +enum class ItemType : std::uint8_t; +using StackId = std::uint64_t; +using ReservationId = std::uint64_t; +using TransferId = std::uint64_t; + +// Recipe quantities are not property and never carry an identity. +struct ItemAmount { + ItemType type{}; + std::uint32_t count = 0; + bool operator==(const ItemAmount&) const = default; +}; +enum class OwnerKind : std::uint8_t { None, Storage, Resident, Production }; +struct StockOwner { + OwnerKind kind = OwnerKind::None; + std::uint64_t id = 0; + bool operator==(const StockOwner&) const = default; +}; +enum class ReservationKind : std::uint8_t { Item, Capacity, Worksite, Harvest, Tending }; +struct Reservation { + ReservationId id = 0; + ReservationKind kind = ReservationKind::Item; + StockOwner owner{}; + StackId stack = 0; + ItemType item{}; + std::uint32_t count = 0; + ReservationId backing = 0; + std::uint64_t origin_storage = 0; + bool operator==(const Reservation&) const = default; +}; +enum class TransferKind : std::uint8_t { Production, Harvest, Tending, Meal, Return }; +enum class CustodyStatus : std::uint8_t { + Accepted, Conflict, Stale, Future, Invalid, Busy, Capacity, Exhausted, Overflow, NoDestination +}; +enum class CustodyOperation : std::uint8_t { Admit, Pickup, Deliver, Complete, Cancel, Return, Harvest, Eat, Tend }; +enum class CustodyKeyKind : std::uint8_t { Admission, Operation }; +struct CustodyKey { + CustodyKeyKind kind = CustodyKeyKind::Admission; + std::uint64_t id = 0; // AgentId for admission, TransferId for operation. + std::uint64_t ordinal = 0; + bool operator==(const CustodyKey&) const = default; +}; +struct CustodyLine { + std::uint64_t storage = 0; + ItemType item{}; + std::uint32_t count = 0; + bool operator==(const CustodyLine&) const = default; +}; +inline constexpr std::size_t custody_material_limit = 5; +inline constexpr std::size_t custody_reservation_limit = 8; +inline constexpr std::size_t custody_receipt_limit = 4096; +struct CustodyRequest { + CustodyKey key{}; + CustodyOperation operation = CustodyOperation::Admit; + TransferKind kind = TransferKind::Production; + std::uint64_t production = 0; + std::uint64_t source = 0; + std::uint64_t destination = 0; + std::array lines{}; + std::uint8_t line_count = 0; + bool operator==(const CustodyRequest&) const = default; +}; +struct CustodyEffect { + StockOwner owner{}; + StackId stack = 0; + ItemType item{}; + std::uint32_t count = 0; + bool operator==(const CustodyEffect&) const = default; +}; +struct CustodyResult { + CustodyStatus status = CustodyStatus::Invalid; + TransferId transfer = 0; + std::array reservations{}; + std::array effects{}; + std::uint8_t reservation_count = 0; + std::uint8_t effect_count = 0; + bool terminal = false; + bool operator==(const CustodyResult&) const = default; +}; +struct CustodyReceipt { + CustodyRequest request{}; + CustodyResult result{}; +}; +struct TransferExecution { + TransferId id = 0; + TransferKind kind = TransferKind::Production; + std::uint64_t production = 0; + std::uint64_t source = 0; + std::uint64_t destination = 0; + std::uint64_t next_operation = 1; + std::array reservations{}; + std::uint8_t reservation_count = 0; + CustodyStatus blocked = CustodyStatus::Accepted; +}; +struct ItemBalance { + std::uint64_t opening = 0; + std::uint64_t grant = 0; + std::uint64_t harvest = 0; + std::uint64_t recipe_output = 0; + std::uint64_t recipe_input = 0; + std::uint64_t meal = 0; + std::uint64_t installation = 0; + std::uint64_t demolition = 0; +}; + +static_assert(sizeof(CustodyRequest) <= 1024 && sizeof(CustodyResult) <= 1024); + +} // namespace settlement diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index d450b3c..8434381 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -13,6 +13,7 @@ #include #include "settlement/core/worker_pool.hpp" +#include "settlement/core/custody.hpp" namespace settlement { @@ -22,7 +23,12 @@ using ResourceNodeId = std::uint64_t; using StorageId = std::uint64_t; using ProductionId = std::uint64_t; -enum class WorldSaveFormat : std::uint32_t { Legacy13 = 13, Current14 = 14 }; +enum class WorldSaveFormat : std::uint32_t { Legacy13 = 13, Current14 = 14, Current15 = 15 }; + +class UnsupportedLegacyState : public std::runtime_error { +public: + UnsupportedLegacyState() : std::runtime_error("state has no exact legacy representation") {} +}; // Raised only by a complete production-ID preflight, before any domain effects. class ProductionCapacityError : public std::overflow_error { @@ -47,7 +53,8 @@ enum class AgentState : std::uint8_t { GoingToEat, Eating, GoingToSleep, - Sleeping + Sleeping, + Returning }; enum class JobState : std::uint8_t { @@ -237,9 +244,13 @@ public: void add(ItemType type, std::uint32_t count = 1) noexcept; void remove(ItemType type, std::uint32_t count = 1) noexcept; [[nodiscard]] ItemType first_item() const noexcept; - + [[nodiscard]] StackId stack_id(ItemType type) const noexcept; private: + friend class World; + friend struct WorldSaveCodec; + void set_stack_id(ItemType type, StackId id) noexcept; std::array counts_{}; + std::array stack_ids_{}; }; struct Agent { @@ -260,6 +271,9 @@ struct Agent { bool resting_on_ground = false; Profession profession = Profession::Generalist; + std::uint64_t next_admission = 1; + std::optional execution; + [[nodiscard]] bool hungry() const noexcept { return hunger >= hunger_threshold; } [[nodiscard]] bool tired() const noexcept { return fatigue >= fatigue_threshold; } }; @@ -292,6 +306,7 @@ struct ItemStack { ItemType type = ItemType::None; std::uint32_t count = 0; std::uint32_t reserved = 0; + StackId id = 0; }; struct Storage { @@ -351,6 +366,8 @@ struct ProductionOrder { AgentId bed_owner = 0; BedBase bed_base = BedBase::Wood; BedStage bed_stage = BedStage::Legacy; + Inventory input; + bool suspended = false; [[nodiscard]] ItemType bed_material() const noexcept { if (bed_stage == BedStage::Legacy) return ItemType::Plank; @@ -382,6 +399,12 @@ struct WorldState { std::uint64_t next_resource_node_id_ = 1; std::uint64_t next_storage_id_ = 1; ProductionId next_production_id_ = 1; + StackId next_stack_id_ = 1; + ReservationId next_reservation_id_ = 1; + TransferId next_transfer_id_ = 1; + std::array item_balances_{}; + std::vector> custody_receipts_; + std::size_t custody_receipt_cursor_ = 0; std::vector blocked_; std::vector agents_; std::vector jobs_; @@ -417,12 +440,19 @@ public: StorageKind kind = StorageKind::Materials); void stock_storage(std::uint64_t id, ItemType type, std::uint32_t count); void enable_hunger() noexcept; + [[nodiscard]] CommandStatus cancel_production(ProductionId id); + [[nodiscard]] CommandStatus resume_production(ProductionId id); + [[nodiscard]] bool legacy_representable() const noexcept; + void validate_custody() const; + [[nodiscard]] CustodyResult custody_request(const CustodyRequest& request); + [[nodiscard]] const auto& item_balances() const noexcept { return item_balances_; } + [[nodiscard]] const auto& custody_receipts() const noexcept { return custody_receipts_; } void queue_production(GridPosition position, RecipeId recipe); [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; [[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept; - [[nodiscard]] std::array construction_materials(RecipeId recipe, BedBase base) const; + [[nodiscard]] std::array construction_materials(RecipeId recipe, BedBase base) const; [[nodiscard]] RecipeId room_construction_recipe(RecipeId part) const noexcept; - [[nodiscard]] std::array carpentry_materials(RecipeId recipe) const; + [[nodiscard]] std::array carpentry_materials(RecipeId recipe) const; [[nodiscard]] std::optional carpenter_workshop() const noexcept { if (!scenario_active_) return std::nullopt; return scenario_sawmill_; @@ -475,6 +505,20 @@ public: private: friend struct WorldSaveCodec; + void migrate_legacy_custody(); + [[nodiscard]] bool admit_custody(Agent& agent, TransferKind kind, ProductionId production, + ResourceNodeId source, StorageId destination, const std::vector& materials); + void finish_custody(Agent& agent) noexcept; + void advance_return(Agent& agent); + [[nodiscard]] bool pickup_custody(Agent& agent, Storage& source, + const std::vector& materials, bool reserve_output); + [[nodiscard]] bool deliver_custody(Agent& agent, Inventory& destination, StockOwner owner); + [[nodiscard]] bool deposit_custody(Agent& agent, Storage& destination, ItemType type, std::uint32_t count); + void record_custody(std::shared_ptr receipt) noexcept; + [[nodiscard]] std::shared_ptr prepare_custody( + Agent& agent, CustodyOperation operation, CustodyStatus status = CustodyStatus::Accepted, + StorageId source = 0, StorageId destination = 0); + void commit_custody(Agent& agent, std::shared_ptr receipt) noexcept; struct CaptureTag {}; World(CaptureTag, const World& source); struct PathResult { From f1b8d41bb49641be04998410335f5166cee3010a Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:10:35 +0300 Subject: [PATCH 02/10] Persist item custody and restore in-flight work from historical saves --- CMakeLists.txt | 1 + docs/agent-workflow/tasks/S15-04.md | 48 ++ engine/include/settlement/core/checkpoint.hpp | 6 +- engine/src/checkpoint.cpp | 7 +- engine/src/world_save.cpp | 353 +++++++++++- tests/checkpoint_tests.cpp | 6 +- tests/custody_migration_tests.cpp | 214 +++++++ tests/fixtures/custody_v14/README.md | 7 + tests/fixtures/custody_v14/capture.cpp | 59 ++ tests/fixtures/custody_v14/fixtures.hpp | 541 ++++++++++++++++++ 10 files changed, 1226 insertions(+), 16 deletions(-) create mode 100644 docs/agent-workflow/tasks/S15-04.md create mode 100644 tests/custody_migration_tests.cpp create mode 100644 tests/fixtures/custody_v14/README.md create mode 100644 tests/fixtures/custody_v14/capture.cpp create mode 100644 tests/fixtures/custody_v14/fixtures.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e6f933..7f926fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -121,6 +121,7 @@ if(BUILD_TESTING) add_executable(settlement_core_tests tests/checkpoint_tests.cpp tests/checkpoint_file_tests.cpp + tests/custody_migration_tests.cpp tests/core_tests.cpp tests/executor_tests.cpp tests/identity_tests.cpp diff --git a/docs/agent-workflow/tasks/S15-04.md b/docs/agent-workflow/tasks/S15-04.md new file mode 100644 index 0000000..a2d3d22 --- /dev/null +++ b/docs/agent-workflow/tasks/S15-04.md @@ -0,0 +1,48 @@ +# Migrate historical cargo and persist modern custody atomically + +Task ID: S15-04 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Isolated s15 worktree f6493e2. Stable read-only historical checkout /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14 at same ref, old Windows build available. Current published checkpoint schema2/body14, schema1/body1–13. S06-03 under construction in sibling s06 exclusively owns World types/normal transitions, will supply concrete data declarations via parent. Source-grounded M01-P5/F8, docs/plan/custody.md include full decisions. + +## 2. Objective and deliverables +Capture genuine old schema2/raw14 fixtures now, then implement canonical raw15/checkpoint3 encoding, strict validation, bounded migration of prior genuine worlds and before-output typed rejection of unrepresentable raw13 states. Complete end-to-end after root integrates S06 schema declarations into this worktree. + +## 3. Scope and non-goals +Persistence/codecs and validated restored state only. No World gameplay changes, command dispatcher, UI, net or new dependency. Data snapshots/custody/command semantics remain owned by sibling S06/S04. Do not invent temporary independent schema if peer interface pending; use that interval for golden collection and historical phase audit. + +## 4. Files to inspect +Read root/S06 docs plan/custody, M01-F8, old world_save.cpp full validator and historical fields, checkpoint.hpp/.cpp, checkpoint_files.cpp, world.hpp current14, new custody declarations when supplied, existing tests/checkpoint*, identity/production_identity/replay/snapshot/quantity, pinned Binary budgets and hash. Fixtures old source and golden corpus/probe helpers in /tmp/stoneheart-milestones.xprJ2SVp. S15-03 already version/size-safe reader/write service. + +## 5. Write ownership and coordination +Write scope: engine/src/world_save.cpp; optional NEW engine/src/custody_save.cpp/internal header for supported codec; engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; engine/src/checkpoint_files.cpp only as genuinely required; tests/checkpoint_tests.cpp/tests/checkpoint_file_tests.cpp/tests/snapshot_tests.cpp only for schema/current snapshot checks; NEW tests/custody_migration_tests.cpp and concise frozen fixture data if needed; CMakeLists.txt limited to registering owned codec/test sources; docs/plan/systems/S15.md +Do not change world.hpp/world.cpp (S06 owner), dispatcher or LAN/app. Other agents work in sibling checkouts; never revert their work. Root will integrate S06 headers when ready. No Git/remote/children or shared Serena switch. + +## 6. Implementation or investigation approach +First capture authentic schema2/raw14 from old binary before peer edits. Include fixed seed/UUID, actual legacy Working worksite after pickup, between stops/hauled product, normal/direct order, staged simple as applicable. Preserve original bytes or minimal readable hex fixture + provenance+SHA and exercise actual decode; do not generate expected old bytes using new writer. Parse/check input under historical schema first; preserve true unused/complete routes. For versions before 5 preserve sleep normalization, versions1–8 historical footer/different fields. Old Working delivery order with stops cleared/no resident material reconstructs exactly validated input at ProductionId; direct SawPlank/CutStoneBlock/WeaveCloth inputs stay in storage; post-carpentry output belongs to resident, no active production link. Meal and tending phases distinct. Allocate migrated IDs deterministically by owner kind/ID/item, active execution by AgentId. Opening balance computed only after implicit site stock reconstructed. Migrated active admission generation1,next2, no fabricated receipt, inactive next1. + +## 7. Interfaces and data contracts +Explicit schema table 1→body1..13, 2→14, 3→15 with digest before decoding, no version-constant-only dropping v2. Strict authenticated body15 data includes all counters/IDs, owner stacks incl site, live execution+claims/capacity backing and source leases, saved phase/pending completion/suspended partials, opening/source/sink totals, exact canonical creation+ordinal receipt ring incl bounds/retired refs. Enforce sorted unique live identities, ID nonzero/less-than valid highwater, one owner, references/counts/claim capacity and valid reservations; historical receipts may name retired IDs below issued highwater, never demand liveness of those refs. Reject modern missing/inconsistent states; no rematerializing missing modern data. Original current14 vs Legacy13 outputs must remain available as defined. Use shared S06 pure validation/projection method where feasible; avoid duplicate simulation/codec rules. + +## 8. Dependencies and integration +Raw13 projection performs complete legacy representability check BEFORE first externally written byte incl single Plank/StoneBlock canceled orderless haul, mixed cargo, missing dropoff, suspended residual bed/loom, zero-completion pending or other modern combinations. Signal typed UnsupportedLegacyState from agreed core type for S16. Preserve valid historical reserved counts/source storage leases, stops and route metadata, actual frozen old byte corpora exact. Modern persistent codec must save unsupported-on-LAN states safely. Parent handles per-worktree header merge; report exact needed seam early. Avoid a 128MiB scratch copy just to detect unsupported states when pure preflight suffices. + +## 9. Edge cases security and performance +Strict 128 MiB body/existing size limits/1M collection caps and exact 4096 receipts, <=1024 bytes each request/result, checked iteration/preallocation budget/count arithmetic before allocation. No hash-only conflict comparison. Tests fully authenticated malformed data for wrong outer/body pair, duplicates and mismatched counters/balances, dangling live vs valid historical refs, embedded wrong epoch, exhausted IDs, canonical order. Preserve existing file/owner transaction semantics and background service. Avoid O(N²) owner/claim lookups and full defensive copies in hot paths. + +## 10. Acceptance criteria +1. Tests load authentic old fixtures (old1–14 layout as supported) at real phases then continue to same economic/gameplay outcome, including original current14. 2. Canonical full modern equality over save/load mid transfers/suspension/return and replay, retained snapshots include new state. 3. Host-facing raw13 rejected states write zero bytes while normal golden projections match. 4. Every malformed candidate rejected without affecting active world/data. 5. All cross-branch integration, Wine CTest and focused migration tests; native caveat. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s15-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. For historical capture use immutable /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14 headers/source and matching prechange runtime library; save evidence/probe/hash under /tmp, freeze meaningful fixtures in tests where necessary. Later CTest -V/targeted custody migration/current/old golden probes and git diff --check; s15-custody-* logs. + +## 12. Constraints and stop conditions +If core declarations are not frozen, deliver authentic fixtures and precise needed interfaces now; do not guess incompatible wire layout or edit S06 files. Root coordinates compile/integration. No standalone incomplete publication. After two failed same-cause fixes escalate with evidence. + +## 13. Authorization and decisions +User authorizes full roadmap, file compatibility and Gitea milestones. Root accepts 1–3 outer + 1–15 body migration and all F8 constraints. Server/client adverse input validation is defensive, with no external communication. Root owns all public actions. + +## 14. Return format +Return S15-04 progress including authentic prechange fixture SHA early, actual agreed storage schema/constraints, changed paths/tests/golden behaviors; mark native/combined gates explicitly. diff --git a/engine/include/settlement/core/checkpoint.hpp b/engine/include/settlement/core/checkpoint.hpp index caf7e2b..cb57b41 100644 --- a/engine/include/settlement/core/checkpoint.hpp +++ b/engine/include/settlement/core/checkpoint.hpp @@ -15,7 +15,7 @@ namespace settlement { -inline constexpr std::uint32_t checkpoint_version = 2; +inline constexpr std::uint32_t checkpoint_version = 3; 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; @@ -47,10 +47,10 @@ struct WorldCheckpoint { RulesManifest rules; }; -// Both schemas store magic, schema, metadata length and body length, then world UUID, +// All schemas store magic, schema, metadata length and body length, then world UUID, // city, tick, rules fingerprint and the sorted complete package closure. Each // package stores its ID, exact version and SHA-256. The body uses World's save -// codec: schema 1 accepts legacy bodies 1–13; schema 2 requires body 14. +// codec: schema 1 accepts bodies 1–13; schema 2 requires 14; schema 3 requires 15. // A final SHA-256 covers every preceding byte. Integers are little-endian. // The caller holds a stable World for the entire synchronous encode operation. [[nodiscard]] std::expected encode_checkpoint( diff --git a/engine/src/checkpoint.cpp b/engine/src/checkpoint.cpp index 81da2e6..7ccb480 100644 --- a/engine/src/checkpoint.cpp +++ b/engine/src/checkpoint.cpp @@ -165,7 +165,7 @@ std::expected encode_checkpoint( fail(CheckpointError::LimitExceeded, "metadata_length", "Checkpoint metadata exceeds 64 KiB."); } std::ostringstream stream(std::ios::binary); - world.write_save(stream, WorldSaveFormat::Current14); + world.write_save(stream, WorldSaveFormat::Current15); auto body = std::move(stream).str(); if (body.size() > max_checkpoint_body_bytes) { fail(CheckpointError::LimitExceeded, "body_length", "Checkpoint world exceeds 128 MiB."); @@ -213,7 +213,7 @@ std::expected decode_checkpoint( fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match."); } const auto schema = get(header, "version"); - if (schema != 1 && schema != checkpoint_version) { + if (schema != 1 && schema != 2 && schema != 3) { fail(CheckpointError::UnsupportedVersion, "version", "Checkpoint schema is not supported."); } const auto metadata_size = get(header, "metadata_length"); @@ -270,7 +270,8 @@ std::expected decode_checkpoint( Void::Binary::Reader body_header(wire_bytes(body).subspan(8, 4)); const auto body_version = get(body_header, "world.version"); if ((schema == 1 && (body_version < 1 || body_version > 13)) || - (schema == 2 && body_version != 14)) { + (schema == 2 && body_version != 14) || + (schema == 3 && body_version != 15)) { fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint schema and world version do not match."); } std::ispanstream stream(std::span{body.data(), body.size()}); diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index 4a72d2e..ce895e6 100644 --- a/engine/src/world_save.cpp +++ b/engine/src/world_save.cpp @@ -18,7 +18,7 @@ namespace settlement { namespace { constexpr std::string_view signature = "SETTLERS"; -constexpr std::uint32_t save_version = 14; +constexpr std::uint32_t save_version = 15; constexpr std::uint32_t last_legacy_footer_version = 8; constexpr std::size_t max_records = 1'000'000; constexpr std::size_t max_save_bytes = 128 * 1024 * 1024; @@ -86,6 +86,11 @@ public: } } + void allocate(std::size_t count, std::size_t size) { + require_save(count <= max_save_bytes / size && + allocations_.consume_field(count * size).has_value(), "Save allocation budget exceeded."); + } + void set_version(std::uint32_t version) { legacy_footer_ = version <= last_legacy_footer_version; } @@ -104,6 +109,7 @@ private: std::istream& stream_; std::size_t bytes_ = 0; // Legacy footers cover the signature and version, which are read first. + Void::Binary::DecodeBudget allocations_{{max_save_bytes, max_save_bytes, 64}}; bool legacy_footer_ = true; std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis; }; @@ -115,6 +121,7 @@ void sequence(Archive& archive, Vector& values, std::size_t limit, Visit visit) archive.field(length); require_save(length <= limit, "Save contains too many records."); if constexpr (Archive::reading) { + archive.allocate(length, sizeof(typename Vector::value_type)); for (std::uint32_t i = 0; i < length; ++i) { values.emplace_back(); visit(values.back()); @@ -371,10 +378,192 @@ struct WorldSaveCodec { } } - static void validate(const World& world); + template + static void custody(Archive& archive, State& world); + static void validate(const World& world, bool modern = false); }; -void WorldSaveCodec::validate(const World& world) { +namespace { + +template +void owner_fields(Archive& archive, Owner& owner) { + archive.field(owner.kind); + archive.field(owner.id); + require_save(owner.kind <= OwnerKind::Production, "Unknown custody owner."); + require_save((owner.kind == OwnerKind::None) == (owner.id == 0), "Invalid custody owner identity."); +} + +template +void claim_fields(Archive& archive, Claim& claim) { + archive.field(claim.id); + archive.field(claim.kind); + owner_fields(archive, claim.owner); + archive.field(claim.stack); + archive.field(claim.item); + archive.field(claim.count); + archive.field(claim.backing); + archive.field(claim.origin_storage); + require_save(claim.kind <= ReservationKind::Tending && claim.item <= ItemType::Loom, + "Unknown reservation kind or item."); + require_save(claim.id != 0 || claim == Reservation{}, "Noncanonical released reservation."); +} + +template +void request_fields(Archive& archive, Request& request) { + // These are exact tagged little-endian fields, never an object image or hash. + std::uint16_t size = static_cast(44 + 13 * request.line_count); + archive.field(size); + require_save(size <= 1024, "Custody request exceeds 1024 bytes."); + archive.field(request.key.kind); + archive.field(request.key.id); + archive.field(request.key.ordinal); + archive.field(request.operation); + archive.field(request.kind); + archive.field(request.production); + archive.field(request.source); + archive.field(request.destination); + archive.field(request.line_count); + require_save(request.line_count <= custody_material_limit && size == 44 + 13 * request.line_count, + "Noncanonical custody request length."); + require_save(request.key.kind <= CustodyKeyKind::Operation && request.operation <= CustodyOperation::Tend && + request.kind <= TransferKind::Return && request.key.id != 0 && request.key.ordinal != 0 && + ((request.key.kind == CustodyKeyKind::Admission) == (request.operation == CustodyOperation::Admit)), + "Invalid custody request tag or key."); + for (std::size_t i = 0; i < request.line_count; ++i) { + auto& line = request.lines[i]; + archive.field(line.storage); + archive.field(line.item); + archive.field(line.count); + require_save(line.storage != 0 && line.item > ItemType::None && line.item <= ItemType::Loom && line.count != 0, + "Invalid custody request line."); + } + for (std::size_t i = request.line_count; i < request.lines.size(); ++i) { + require_save(request.lines[i] == CustodyLine{}, "Noncanonical unused request line."); + } +} + +template +void result_fields(Archive& archive, Result& result) { + std::uint16_t size = static_cast(12 + 8 * result.reservation_count + 22 * result.effect_count); + archive.field(size); + require_save(size <= 1024, "Custody result exceeds 1024 bytes."); + archive.field(result.status); + archive.field(result.transfer); + archive.field(result.reservation_count); + archive.field(result.effect_count); + flag(archive, result.terminal); + require_save(result.status <= CustodyStatus::NoDestination && + result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count && + size == 12 + 8 * result.reservation_count + 22 * result.effect_count, + "Noncanonical custody result length or tag."); + for (std::size_t i = 0; i < result.reservation_count; ++i) archive.field(result.reservations[i]); + for (std::size_t i = result.reservation_count; i < result.reservations.size(); ++i) { + require_save(result.reservations[i] == 0, "Noncanonical unused result reservation."); + } + for (std::size_t i = 0; i < result.effect_count; ++i) { + auto& effect = result.effects[i]; + owner_fields(archive, effect.owner); + archive.field(effect.stack); + archive.field(effect.item); + archive.field(effect.count); + require_save(effect.owner.kind != OwnerKind::None && effect.stack != 0 && + effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.count != 0, + "Invalid custody result effect."); + } + for (std::size_t i = result.effect_count; i < result.effects.size(); ++i) { + require_save(result.effects[i] == CustodyEffect{}, "Noncanonical unused result effect."); + } +} + +} // namespace + +template +void WorldSaveCodec::custody(Archive& archive, State& world) { + archive.field(world.next_stack_id_); + archive.field(world.next_reservation_id_); + archive.field(world.next_transfer_id_); + const auto inventory = [&](auto& value, bool quantities) { + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto type = static_cast(i); + auto count = value.item_count(type); + if (quantities) archive.field(count); + auto id = value.stack_id(type); + archive.field(id); + require_save((id == 0) == (count == 0), "Noncanonical custody stack identity."); + if constexpr (Archive::reading) { + if (quantities && count != 0) value.add(type, count); + value.set_stack_id(type, id); + } + } + }; + for (auto& storage : world.storages_) { + for (auto& stack : storage.items) archive.field(stack.id); + } + for (auto& agent : world.agents_) { + inventory(agent.inventory, false); + archive.field(agent.next_admission); + bool present = agent.execution.has_value(); + flag(archive, present); + if constexpr (Archive::reading) { if (present) agent.execution.emplace(); } + if (!present) continue; + auto& execution = *agent.execution; + archive.field(execution.id); + archive.field(execution.kind); + archive.field(execution.production); + archive.field(execution.source); + archive.field(execution.destination); + archive.field(execution.next_operation); + archive.field(execution.blocked); + archive.field(execution.reservation_count); + require_save(execution.kind <= TransferKind::Return && execution.blocked <= CustodyStatus::NoDestination && + execution.reservation_count <= custody_reservation_limit, "Invalid custody execution fields."); + for (std::size_t i = 0; i < execution.reservation_count; ++i) claim_fields(archive, execution.reservations[i]); + for (std::size_t i = execution.reservation_count; i < execution.reservations.size(); ++i) { + require_save(execution.reservations[i] == Reservation{}, "Noncanonical unused reservation."); + } + } + for (auto& order : world.production_orders_) { + inventory(order.input, true); + flag(archive, order.suspended); + } + for (auto& balance : world.item_balances_) { + archive.field(balance.opening); + archive.field(balance.grant); + archive.field(balance.harvest); + archive.field(balance.recipe_output); + archive.field(balance.recipe_input); + archive.field(balance.meal); + archive.field(balance.installation); + archive.field(balance.demolition); + } + auto count = static_cast(world.custody_receipts_.size()); + require_save(world.custody_receipts_.size() <= custody_receipt_limit, "Too many custody receipts."); + archive.field(count); + require_save(count <= custody_receipt_limit, "Too many custody receipts."); + if constexpr (Archive::reading) { + archive.allocate(count, sizeof(CustodyReceipt) + sizeof(std::shared_ptr)); + world.custody_receipts_.reserve(count); + for (std::uint32_t i = 0; i < count; ++i) { + auto receipt = std::make_shared(); + request_fields(archive, receipt->request); + result_fields(archive, receipt->result); + world.custody_receipts_.push_back(std::move(receipt)); + } + world.custody_receipt_cursor_ = 0; + } else { + require_save(count == custody_receipt_limit ? world.custody_receipt_cursor_ < count : + world.custody_receipt_cursor_ == 0, "Invalid custody receipt cursor."); + for (std::size_t i = 0; i < count; ++i) { + const auto index = (i + world.custody_receipt_cursor_) % count; + const auto& receipt = world.custody_receipts_[index]; + require_save(receipt != nullptr, "Missing custody receipt."); + request_fields(archive, receipt->request); + result_fields(archive, receipt->result); + } + } +} + +void WorldSaveCodec::validate(const World& world, bool modern) { const auto invalid = [](bool good) { require_save(good, "Save contains inconsistent simulation state."); }; const auto inside = [&](GridPosition p) { return p.x >= 0 && p.x < world.width_ && p.y >= 0 && p.y < world.height_; @@ -466,6 +655,21 @@ void WorldSaveCodec::validate(const World& world) { invalid(resident != world.agents_.end() && resident->id == order.bed_owner); bed_owners.push_back(order.bed_owner); } + if (modern) { + invalid(order.materials.size() <= custody_material_limit && + order.collected_stops <= order.delivery_stops.size()); + for (const auto& material : order.materials) { + static_cast(item_index(material.type)); + invalid(material.count > 0 && world.find_storage(material.storage_id) != nullptr); + } + StorageId previous_stop = 0; + for (const auto& stop : order.delivery_stops) { + invalid(stop.storage_id > previous_stop && world.find_storage(stop.storage_id) != nullptr); + previous_stop = stop.storage_id; + valid_route(stop.route_to_next); + } + continue; + } if (order.state != JobState::InProgress) { invalid(order.materials.empty() && order.delivery_stops.empty() && order.collected_stops == 0); continue; @@ -551,7 +755,7 @@ void WorldSaveCodec::validate(const World& world) { std::vector rest_destinations; for (const auto& agent : world.agents_) { using enum AgentState; - invalid(agent.state <= Sleeping && agent.route_cursor <= agent.route.size() && agent.hunger <= max_hunger && + invalid(agent.state <= (modern ? Returning : Sleeping) && agent.route_cursor <= agent.route.size() && agent.hunger <= max_hunger && (world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue && (world.scenario_active_ || agent.fatigue == 0)); invalid(!agent.resting_on_ground || agent.state == Sleeping || agent.state == GoingToSleep); @@ -566,7 +770,7 @@ void WorldSaveCodec::validate(const World& world) { const bool has_storage = agent.storage_id != 0; invalid(!has_storage || world.find_storage(agent.storage_id) != nullptr); const bool carpentry = has_order && is_carpentry_recipe(production->recipe); - invalid(agent.haul_route.empty() || has_source || carpentry); + invalid(modern || agent.haul_route.empty() || has_source || carpentry); if (has_job) { invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() && (agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0); @@ -576,6 +780,11 @@ void WorldSaveCodec::validate(const World& world) { auto& claimed = job_claims[static_cast(job - world.jobs_.begin())]; invalid(claimed == 0); claimed = 1; + } else if (modern && agent.state != GoingToSleep && agent.state != Sleeping) { + invalid(!has_source || world.find_resource_node(agent.resource_node_id) != nullptr); + // Live property, claims, execution phase and zero-time pending work + // are checked together by the authoritative custody validator. + continue; } else if (has_order) { invalid(!has_storage && !has_source && agent.work_remaining > 0); const auto order_index = static_cast(production - world.production_orders_.data()); @@ -657,6 +866,7 @@ void WorldSaveCodec::validate(const World& world) { for (std::size_t i = 0; i < world.jobs_.size(); ++i) { invalid((job_claims[i] != 0) == (world.jobs_[i].state == JobState::InProgress)); } + if (modern) { world.validate_custody(); return; } for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { invalid((order_claims[i] != 0) == (world.production_orders_[i].state == JobState::InProgress)); } @@ -674,10 +884,133 @@ void WorldSaveCodec::validate(const World& world) { } } +void World::migrate_legacy_custody() { + // This function runs only after historical fields, phases, reservations and + // (for versions 1–8) the historical footer have all passed validation. + next_stack_id_ = next_reservation_id_ = next_transfer_id_ = 1; + item_balances_ = {}; + custody_receipts_.clear(); + custody_receipt_cursor_ = 0; + for (auto& order : production_orders_) { + if (order.state == JobState::InProgress && delivers_materials(order.recipe) && order.delivery_stops.empty()) { + for (const auto& material : order.materials) order.input.add(material.type, material.count); + } + } + const auto identity = [&](ItemType item, std::uint32_t count) { + require_save(next_stack_id_ != std::numeric_limits::max(), "Migrated stack identities exhausted."); + auto& opening = item_balances_[item_index(item)].opening; + require_save(count <= std::numeric_limits::max() - opening, "Migrated opening balance overflow."); + opening += count; + return next_stack_id_++; + }; + // Stable owner-kind / owner-ID / item order, independent of worker count. + for (auto& storage : storages_) { + for (auto& stack : storage.items) stack.id = identity(stack.type, stack.count); + } + const auto identify_inventory = [&](Inventory& inventory) { + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + if (const auto count = inventory.item_count(item)) inventory.set_stack_id(item, identity(item, count)); + } + }; + for (auto& agent : agents_) identify_inventory(agent.inventory); + for (auto& order : production_orders_) identify_inventory(order.input); + + for (auto& agent : agents_) { + agent.next_admission = 1; + agent.execution.reset(); + const bool active = agent.production_id != 0 || agent.resource_node_id != 0 || + agent.state == AgentState::Hauling || agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating; + if (!active) continue; + TransferExecution execution; + execution.id = next_transfer_id_++; + execution.production = agent.production_id; + execution.source = agent.resource_node_id; + execution.destination = agent.storage_id; + const auto add = [&](Reservation claim) -> ReservationId { + require_save(execution.reservation_count < custody_reservation_limit && + next_reservation_id_ != std::numeric_limits::max(), + "Migrated reservation limit exceeded."); + claim.id = next_reservation_id_++; + execution.reservations[execution.reservation_count++] = claim; + return claim.id; + }; + const auto storage_stack = [&](StorageId storage, ItemType item) -> StackId { + const auto& items = storages_[record_index(storages_, storage)].items; + const auto found = std::lower_bound(items.begin(), items.end(), item, + [](const auto& stack, ItemType target) { return stack.type < target; }); + require_save(found != items.end() && found->type == item, "Missing migrated reserved stock."); + return found->id; + }; + ReservationId capacity_backing = 0; + if (agent.production_id != 0) { + execution.kind = TransferKind::Production; + const auto& order = production_orders_[record_index(production_orders_, agent.production_id)]; + const bool delivery = delivers_materials(order.recipe); + const bool at_site = delivery && order.delivery_stops.empty(); + if (!is_construction(order.recipe) || is_carpentry_recipe(order.recipe)) { + execution.destination = order.materials.front().storage_id; + } + for (const auto& material : order.materials) { + StockOwner owner{OwnerKind::Storage, material.storage_id}; + StackId stack = 0; + if (at_site) { + owner = {OwnerKind::Production, order.id}; + stack = order.input.stack_id(material.type); + } else if (delivery) { + const auto stop = std::lower_bound(order.delivery_stops.begin(), order.delivery_stops.end(), material.storage_id, + [](const auto& entry, StorageId id) { return entry.storage_id < id; }); + if (static_cast(stop - order.delivery_stops.begin()) < order.collected_stops) { + owner = {OwnerKind::Resident, agent.id}; + stack = agent.inventory.stack_id(material.type); + } + } + if (owner.kind == OwnerKind::Storage) stack = storage_stack(material.storage_id, material.type); + const auto claim = add({0, ReservationKind::Item, owner, stack, material.type, material.count, 0, material.storage_id}); + if (!capacity_backing && execution.destination == material.storage_id && owner.kind == OwnerKind::Storage) { + capacity_backing = claim; + } + } + add({0, ReservationKind::Worksite, {OwnerKind::Production, order.id}, 0, {}, 1}); + } else if (agent.resource_node_id != 0) { + execution.kind = agent.storage_id ? TransferKind::Harvest : TransferKind::Tending; + add({0, agent.storage_id ? ReservationKind::Harvest : ReservationKind::Tending, {}, 0, {}, 1}); + } else if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) { + execution.kind = TransferKind::Meal; + execution.destination = 0; + if (agent.state == AgentState::GoingToEat) { + add({0, ReservationKind::Item, {OwnerKind::Storage, agent.storage_id}, + storage_stack(agent.storage_id, ItemType::Berries), ItemType::Berries, 1, 0, agent.storage_id}); + } else { + add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id}, + agent.inventory.stack_id(ItemType::Berries), ItemType::Berries, 1}); + } + } else { + execution.kind = TransferKind::Return; + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + if (const auto count = agent.inventory.item_count(item)) { + add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(item), item, count}); + } + } + } + if (execution.destination != 0) { + add({0, ReservationKind::Capacity, {OwnerKind::Storage, execution.destination}, 0, {}, 1, capacity_backing}); + } + agent.execution = execution; + agent.next_admission = 2; + } +} + void World::write_save(std::ostream& stream, WorldSaveFormat format) const { const auto version = static_cast(format); - require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14, + require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14 || + format == WorldSaveFormat::Current15, "Unsupported save output format."); + if (format != WorldSaveFormat::Current15 && !legacy_representable()) { + throw UnsupportedLegacyState{}; + } + if (format == WorldSaveFormat::Current15) WorldSaveCodec::validate(*this, true); SaveWriter archive(stream); for (char letter : signature) archive.field(letter); archive.field(version); @@ -685,6 +1018,7 @@ void World::write_save(std::ostream& stream, WorldSaveFormat format) const { archive.field(width_); archive.field(height_); WorldSaveCodec::body(archive, *this, version); + if (version >= 15) WorldSaveCodec::custody(archive, *this); } std::unique_ptr World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode, @@ -707,6 +1041,7 @@ std::unique_ptr World::read_save(std::istream& stream, std::size_t worker archive.field(height); auto world = std::make_unique(seed, width, height, workers, mode, std::move(worker_options)); WorldSaveCodec::body(archive, *world, version); + if (version >= 15) WorldSaveCodec::custody(archive, *world); archive.finish(); if (version < 5) { std::vector occupied_ground; @@ -723,7 +1058,11 @@ std::unique_ptr World::read_save(std::istream& stream, std::size_t worker } } } - WorldSaveCodec::validate(*world); + WorldSaveCodec::validate(*world, version >= 15); + if (version < 15) { + world->migrate_legacy_custody(); + world->validate_custody(); + } return world; } diff --git a/tests/checkpoint_tests.cpp b/tests/checkpoint_tests.cpp index 0c93483..9b3f688 100644 --- a/tests/checkpoint_tests.cpp +++ b/tests/checkpoint_tests.cpp @@ -180,8 +180,8 @@ Test CheckpointTests::test_authentic_v1_import_and_authenticated_schema_body_pai } auto imported = decoded(old_checkpoint(0), catalog); auto current = encoded(*imported.world, rules); - require(static_cast(current[8]) == 2 && - static_cast(current[layout(current).body_begin + 8]) == 14, + require(static_cast(current[8]) == 3 && + static_cast(current[layout(current).body_begin + 8]) == 15, "new checkpoint lacks the current schema/body pair"); auto false_legacy = current; change(false_legacy, 8, std::uint32_t{1}); rehash(false_legacy); @@ -211,7 +211,7 @@ Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes( require(saved_state(*restored.world) == before && saved_state(world) == before, "checkpoint changed the original or restored canonical state"); std::ostringstream modern(std::ios::binary); - world.write_save(modern, WorldSaveFormat::Current14); + world.write_save(modern, WorldSaveFormat::Current15); require(bytes.substr(layout(bytes).body_begin, modern.str().size()) == modern.str(), "checkpoint did not use the current world serialization"); require(before.substr(0, 8) == "SETTLERS" && static_cast(before[8]) == 13, diff --git a/tests/custody_migration_tests.cpp b/tests/custody_migration_tests.cpp new file mode 100644 index 0000000..230a3f9 --- /dev/null +++ b/tests/custody_migration_tests.cpp @@ -0,0 +1,214 @@ +#include "settlement/core/checkpoint.hpp" +#include "fixtures/custody_v14/fixtures.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { +using namespace settlement; +using Void::Testing::Test; +void require(bool condition, std::string_view message) { + if (!condition) throw std::runtime_error(std::string(message)); +} +std::string unhex(std::string_view hex) { + const auto digit = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; }; + std::string result; + for (std::size_t i = 0; i < hex.size(); i += 2) result.push_back(static_cast(digit(hex[i]) * 16 + digit(hex[i + 1]))); + return result; +} +std::string raw(const World& world, WorldSaveFormat format = WorldSaveFormat::Current15) { + std::ostringstream stream(std::ios::binary); world.write_save(stream, format); return stream.str(); +} +WorldCheckpoint load(std::string_view bytes, std::size_t workers = 1) { + const auto catalog = builtin_rule_packages(); + auto result = decode_checkpoint(bytes, *catalog, workers, + workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel); + if (!result) throw std::runtime_error(result.error().message); + return std::move(*result); +} +std::string save(const WorldCheckpoint& saved) { + auto result = encode_checkpoint(*saved.world, saved.world_id, saved.city, saved.rules); + if (!result) throw std::runtime_error(result.error().message); + return std::move(*result); +} +const custody_v14::Fixture& fixture(std::string_view name) { + for (const auto& entry : custody_v14::fixtures) if (entry.name == name) return entry; + throw std::runtime_error("missing historical fixture"); +} +std::size_t body_begin(std::string_view bytes) { + Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(), bytes.size()}).subspan(12)); + return 24 + reader.readLittle().value(); +} +template void change(std::string& bytes, std::size_t offset, T value) { + Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset)); + require(writer.writeLittle(value).has_value(), "mutation exceeded frame"); +} +void rehash(std::string& bytes) { + auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256); + require(hasher && hasher->update(std::string_view(bytes).substr(0,bytes.size()-32)), "hash failed"); + auto digest = hasher->finalize(); require(digest.has_value(), "hash finalization failed"); + std::memcpy(bytes.data()+bytes.size()-32, digest->data(), 32); +} +void reject(std::string bytes) { + rehash(bytes); + auto catalog = builtin_rule_packages(); + require(!decode_checkpoint(bytes,*catalog,1,ExecutionMode::SerialReference), "authenticated malformed custody was accepted"); +} +void legacy_reject(const World& world) { + for (auto format : {WorldSaveFormat::Legacy13, WorldSaveFormat::Current14}) { + std::ostringstream out(std::ios::binary); + bool failed = false; + try { world.write_save(out,format); } catch (const UnsupportedLegacyState&) { failed=true; } + require(failed && out.str().empty(), "unsupported projection wrote a prefix or lost typed error"); + } +} +struct [[= Void::Testing::name("CustodyMigrationTests")]] CustodyMigrationTests : Void::Testing::Suite { + [[= Void::Testing::tag("custody-migration")]] Test authentic_historical_phases_keep_eighty_tick_projection(); + [[= Void::Testing::tag("custody-migration")]] Test opening_stock_and_admission_are_reconstructed_without_receipts(); + [[= Void::Testing::tag("custody-migration")]] Test modern_frames_reject_identity_balance_and_pair_corruption(); + [[= Void::Testing::tag("custody-migration")]] Test cancellation_is_durable_and_legacy_refusal_is_before_output(); + [[= Void::Testing::tag("custody-migration")]] Test completed_receipts_keep_retired_stock_and_order_references(); + [[= Void::Testing::tag("custody-migration")]] Test single_finished_material_and_partial_return_use_modern_format(); + [[= Void::Testing::tag("custody-migration")]] Test suspended_sites_and_zero_completion_use_modern_format(); +}; +Test CustodyMigrationTests::authentic_historical_phases_keep_eighty_tick_projection() { + for (const auto& original : custody_v14::fixtures) { + const auto bytes=unhex(original.checkpoint); + const auto digest=Void::Crypto::sha256(std::string_view(bytes)); + require(digest.has_value(), "fixture hashing failed"); + const auto expected_digest=unhex(original.sha256); + require(std::ranges::equal(*digest,std::as_bytes(std::span{expected_digest.data(),expected_digest.size()})), "historical fixture SHA differs"); + for (auto workers : {1U,2U,6U,12U}) { + auto restored=load(bytes,workers); + require(raw(*restored.world,WorldSaveFormat::Current14)==bytes.substr(body_begin(bytes),bytes.size()-body_begin(bytes)-32), original.name); + for (std::size_t tick=0;tickstep(); + roundtrip.world->step(); + require(raw(*roundtrip.world)==raw(*restored.world), "modern continuation diverged"); + } + } + } +} +Test CustodyMigrationTests::opening_stock_and_admission_are_reconstructed_without_receipts() { + for(const auto& original:custody_v14::fixtures) { + auto restored=load(unhex(original.checkpoint)); const auto& world=*restored.world; + world.validate_custody(); + require(world.custody_receipts().empty(),"migration invented historical receipts"); + const auto& actor=world.agents().front(); + require(actor.execution && actor.next_admission==2 && actor.execution->next_operation==1,"active legacy admission was not marked consumed"); + CustodyRequest retry;retry.key={CustodyKeyKind::Admission,actor.id,1}; + require(restored.world->custody_request(retry).status==CustodyStatus::Stale,"migrated admission was executed again"); + if(original.name=="cabin-working") { + const auto& input=world.production_orders().front().input; + require(input.item_count(ItemType::Plank)==3&&input.item_count(ItemType::StoneBlock)==2&&actor.inventory.empty(),"implicit worksite stock was not restored"); + require(world.item_balances()[2].opening==3&&world.item_balances()[3].opening==2,"opening was measured before worksite restoration"); + } + if(original.name.starts_with("direct-")) require(world.production_orders().front().input.empty(),"direct recipe debited input during migration"); + } +} +Test CustodyMigrationTests::modern_frames_reject_identity_balance_and_pair_corruption() { + auto restored=load(unhex(fixture("cabin-before-pickup").checkpoint)); + const auto good=save(restored), before=raw(*restored.world); + const auto extension=body_begin(good)+raw(*restored.world,WorldSaveFormat::Current14).size(); + for(auto offset:{extension,extension+8,extension+16}) { + auto bad=good;change(bad,offset,std::uint64_t{0});reject(std::move(bad)); + } + auto duplicate=good;change(duplicate,extension+24+8,std::uint64_t{1});reject(std::move(duplicate)); + auto bad_balance=good; // Last 11*64 bytes before receipt count are the balance ledger. + const auto balance=good.size()-32-4-item_type_count*64; + change(bad_balance,balance,std::uint64_t{1});reject(std::move(bad_balance)); + for(auto schema:{1U,2U}){auto bad=good;change(bad,8,schema);reject(std::move(bad));} + auto false_three=unhex(fixture("cabin-working").checkpoint);change(false_three,8,3U);reject(std::move(false_three)); + require(raw(*restored.world)==before,"decoding corrupt candidate mutated active owner"); +} +Test CustodyMigrationTests::cancellation_is_durable_and_legacy_refusal_is_before_output() { + for(auto name:{"cabin-between-stops","cabin-to-site","cabin-working"}) { + auto restored=load(unhex(fixture(name).checkpoint)); + const auto id=restored.world->production_orders().front().id; + require(restored.world->cancel_production(id)==CommandStatus::Accepted,"cancel refused historical active construction"); + legacy_reject(*restored.world); + const auto bytes=save(restored);auto loaded=load(bytes); + require(save(loaded)==bytes,"return cargo lost in modern checkpoint"); + for(int tick=0;tick<80;++tick){restored.world->step();loaded.world->step();require(raw(*restored.world)==raw(*loaded.world),"return differed after restore");} + } +} +Test CustodyMigrationTests::completed_receipts_keep_retired_stock_and_order_references() { + auto restored=load(unhex(fixture("cabin-working").checkpoint)); + require(restored.world->cancel_production(restored.world->production_orders().front().id)==CommandStatus::Accepted,"fixture active order removal failed"); + require(!restored.world->custody_receipts().empty(),"fixture did not create cancellation receipt"); + const auto remembered=restored.world->custody_receipts().back(); + for(int tick=0;tick<80;++tick)restored.world->step(); + const auto bytes=save(restored);auto loaded=load(bytes); + require(loaded.world->custody_request(remembered->request)==remembered->result,"historical result was lost after referenced stock/order retirement"); +} +Test CustodyMigrationTests::single_finished_material_and_partial_return_use_modern_format() { + for (auto item : {ItemType::Plank, ItemType::StoneBlock}) { + auto metadata = load(unhex(fixture("cabin-working").checkpoint)); + auto world = std::make_unique(43,20,8,1,ExecutionMode::SerialReference); + const auto first=world->add_storage({3,3},20), second=world->add_storage({8,3},20); + world->stock_storage(first,item,1); + world->stock_storage(second,ItemType::Plank,item==ItemType::Plank?2:3); + world->stock_storage(second,ItemType::StoneBlock,item==ItemType::StoneBlock?1:2); + static_cast(world->spawn_agent({1,3}));world->queue_production({14,3},RecipeId::BuildCabin); + for(int tick=0;tick<10&&world->agents().front().inventory.empty();++tick)world->step(); + require(world->agents().front().inventory.item_count(item)==1,"fixture missed single-item pickup"); + require(world->cancel_production(world->production_orders().front().id)==CommandStatus::Accepted,"single cargo cancellation failed"); + legacy_reject(*world);metadata.world=std::move(world); + const auto encoded=save(metadata);require(save(load(encoded))==encoded,"single finished material did not roundtrip"); + } + for (bool partial : {false,true}) { + auto restored=load(unhex(fixture("cabin-working").checkpoint)); + restored.world->stock_storage(restored.world->storages()[0].id,ItemType::Wood,partial?19:20); + restored.world->stock_storage(restored.world->storages()[1].id,ItemType::Wood,20); + require(restored.world->cancel_production(restored.world->production_orders().front().id)==CommandStatus::Accepted,"full-store cancellation failed"); + for(int tick=0;tick<40;++tick)restored.world->step(); + require(restored.world->agents().front().inventory.item_count(ItemType::Plank)==(partial?2U:3U),"return did not respect exact available capacity"); + require(restored.world->agents().front().inventory.item_count(ItemType::StoneBlock)==2,"mixed return dropped second item"); + legacy_reject(*restored.world);const auto encoded=save(restored);require(save(load(encoded))==encoded,"partial or blocked return did not roundtrip"); + } +} +Test CustodyMigrationTests::suspended_sites_and_zero_completion_use_modern_format() { + for(bool bed:{false,true}) { + auto metadata=load(unhex(fixture("cabin-working").checkpoint)); + auto world=std::make_unique(43,20,8,1,ExecutionMode::SerialReference); + world->start_scenario({2,2});const auto storage=world->add_storage({3,3},20); + world->stock_storage(storage,ItemType::Wood,bed?1:2);static_cast(world->spawn_agent({1,3})); + if(bed)require(world->apply_command({1,1,CommandKind::PlaceBed,{6,3}}).status==CommandStatus::Accepted,"bed placement failed"); + else world->queue_production({6,3},RecipeId::BuildLoom); + for(int tick=0;tick<45;++tick)world->step(); + require(world->cancel_production(world->production_orders().front().id)==CommandStatus::Accepted,"residual site cancellation failed"); + require(world->production_orders().front().suspended,"residual site was not suspended"); + legacy_reject(*world);metadata.world=std::move(world); + const auto encoded=save(metadata);auto loaded=load(encoded);require(save(loaded)==encoded,"suspended site did not roundtrip"); + require(loaded.world->resume_production(loaded.world->production_orders().front().id)==CommandStatus::Accepted,"suspended site cannot resume after restore"); + } + auto metadata=load(unhex(fixture("cabin-working").checkpoint)); + auto encoded=save(metadata); + // The historical prefix is kept in raw15. Parse its first agent timer rather + // than relying on native object layout; this is a valid pending completion. + const auto body=body_begin(encoded); + Void::Binary::Reader reader(std::as_bytes(std::span{encoded.data(),encoded.size()}).subspan(body)); + require(reader.skip(20).has_value(),"missing dimensions"); + const auto width=reader.readLittle().value(),height=reader.readLittle().value(); + require(reader.skip(81+static_cast(width)*height+4+25).has_value(),"missing first agent"); + const auto route=reader.readLittle().value(); + require(reader.skip(static_cast(route)*8+8).has_value(),"missing first route"); + change(encoded,body+reader.position(),std::uint32_t{0});rehash(encoded); + auto pending=load(encoded);legacy_reject(*pending.world); + require(save(pending)==encoded,"pending zero timer did not roundtrip"); + pending.world->step();pending.world->validate_custody(); +} +} // namespace diff --git a/tests/fixtures/custody_v14/README.md b/tests/fixtures/custody_v14/README.md new file mode 100644 index 0000000..6a5adbf --- /dev/null +++ b/tests/fixtures/custody_v14/README.md @@ -0,0 +1,7 @@ +# Frozen schema 2 migration corpus + +`fixtures.hpp` contains 13 authentic checkpoints and FNV-1a hashes of 80 subsequent raw13 states for each. They were emitted by `capture.cpp`, compiled exclusively against source and headers at `f6493e2d1cdb9e07eb18b9901fd8878b5d3fa51e`, using the pinned VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, Windows x64 GCC 16.2 and Wine 11. Each fixture includes its full SHA-256. These bytes were captured before the custody implementation and are never regenerated by the current writer. + +Seed is 43. UUID is `91020304-0506-4708-890a-0b0c0d0e0f10`, city 7, built-in rules. The probe records exact states before pickup, between stops, approaching the worksite, Working with implicit consumed delivery, three direct recipes, finished carpenter cargo without a production link, harvesting, harvested cargo, both meal phases and tending. The `.continuation13` probe output stores 80 length-prefixed raw13 frames (32-bit little-endian lengths). + +Reproduce in a separate historical checkout at that exact commit, build its `settlement_core`, then compile this probe with that checkout's headers and library. Pass an existing directory prefix including its trailing separator. Do not use current headers or objects with the historical probe. The generated fixture header retains only checkpoints and per-tick hashes; complete raw frames and build logs are verification artifacts outside the repository. diff --git a/tests/fixtures/custody_v14/capture.cpp b/tests/fixtures/custody_v14/capture.cpp new file mode 100644 index 0000000..3a72b74 --- /dev/null +++ b/tests/fixtures/custody_v14/capture.cpp @@ -0,0 +1,59 @@ +#include "settlement/core/checkpoint.hpp" +#include +#include +#include +#include +#include +#include +using namespace settlement; +constexpr Void::Uuid::Uuid uuid{{0x91,2,3,4,5,6,0x47,8,0x89,10,11,12,13,14,15,16}}; +std::string prefix; +void capture(const World& world, const std::string& name) { + auto rules=default_rules_manifest(); auto data=encode_checkpoint(world,uuid,7,*rules); + if(!data) throw std::runtime_error(data.error().message); + std::ofstream(prefix+name+".checkpoint",std::ios::binary).write(data->data(),data->size()); + std::ofstream raw(prefix+name+".raw14",std::ios::binary); world.write_save(raw,WorldSaveFormat::Current14);raw.close(); + std::ofstream legacy(prefix+name+".raw13",std::ios::binary); world.write_save(legacy,WorldSaveFormat::Legacy13);legacy.close(); + const auto&a=world.agents().front(); + std::cout<write_save(frame,WorldSaveFormat::Legacy13); const auto bytes=frame.str(); std::uint32_t count=bytes.size(); continuation.write(reinterpret_cast(&count),4); continuation.write(bytes.data(),bytes.size()); copy->step();} +} +int main(int argc,char**argv){ + if(argc!=2)return 2;prefix=argv[1]; + World w(43,20,8,1,ExecutionMode::SerialReference); + auto a=w.add_storage({3,3},20),b=w.add_storage({8,3},20); + w.stock_storage(a,ItemType::Plank,3);w.stock_storage(b,ItemType::StoneBlock,2); + (void)w.spawn_agent({1,3}); w.queue_production({14,3},RecipeId::BuildCabin); + std::set seen; + for(unsigned i=0;i<80;++i){w.step();const auto&agent=w.agents().front();const auto&o=w.production_orders().front(); + std::string name; + if(agent.state==AgentState::FetchingMaterials)name="cabin-before-pickup"; + if(agent.state==AgentState::Hauling&&o.collected_stops==1)name="cabin-between-stops"; + if(agent.state==AgentState::Hauling&&o.collected_stops==2)name="cabin-to-site"; + if(agent.state==AgentState::Working)name="cabin-working"; + if(!name.empty()&&seen.insert(name).second)capture(w,name); + } + for(auto recipe:{RecipeId::SawPlank,RecipeId::CutStoneBlock,RecipeId::WeaveCloth}){ + World d(43,20,8,1,ExecutionMode::SerialReference);auto s=d.add_storage({3,3},20); + d.stock_storage(s,recipe==RecipeId::SawPlank?ItemType::Wood:recipe==RecipeId::CutStoneBlock?ItemType::Stone:ItemType::Flax,1); + (void)d.spawn_agent({2,3});d.queue_production({6,3},recipe); + for(int i=0;i<40;++i){d.step();if(d.agents().front().state==AgentState::Working){capture(d,"direct-"+std::to_string(int(recipe)));break;}} + } + World c(43,24,24,1,ExecutionMode::SerialReference);c.start_scenario({2,2});auto s=c.add_storage({3,3},20);c.stock_storage(s,ItemType::Wood,5); + const auto carpenter=c.spawn_agent({2,3}); (void)c.apply_command({1,1,CommandKind::AssignProfession,{},static_cast(Profession::Carpenter),{},carpenter});c.queue_production(*c.carpenter_workshop(),RecipeId::CraftWoodenDoor); + for(int i=0;i<120;++i){c.step();if(c.agents().front().state==AgentState::Hauling&&c.agents().front().production_id==0&&c.agents().front().inventory.item_count(ItemType::WoodenDoor)){capture(c,"carpenter-output");break;}} + + World h(43,20,8,1,ExecutionMode::SerialReference);(void)h.add_storage({14,3},20);(void)h.add_resource_node({3,3},ItemType::Wood,1);(void)h.spawn_agent({1,3}); + bool gathering=false,hauling=false; + for(int i=0;i<60;++i){h.step();if(!gathering&&h.agents().front().state==AgentState::Gathering){capture(h,"harvest-gathering");gathering=true;}if(!hauling&&h.agents().front().state==AgentState::Hauling){capture(h,"harvest-hauled");hauling=true;}} + World m(43,20,8,1,ExecutionMode::SerialReference);auto pantry=m.add_storage({14,3},20,StorageKind::Pantry);m.stock_storage(pantry,ItemType::Berries,5);(void)m.spawn_agent({1,3});m.enable_hunger(); + bool going=false,eating=false; + for(int i=0;i<220;++i){m.step();if(!going&&m.agents().front().state==AgentState::GoingToEat){capture(m,"meal-going");going=true;}if(!eating&&m.agents().front().state==AgentState::Eating){capture(m,"meal-eating");eating=true;}} + World t(43,20,8,1,ExecutionMode::SerialReference);t.start_scenario({2,2});(void)t.spawn_agent({1,3});(void)t.apply_command({1,1,CommandKind::PlaceTreePlot,{5,3}}); + bool tending=false; + for(int i=0;i<60;++i){t.step();if(t.agents().front().state==AgentState::Gathering&&t.agents().front().storage_id==0){capture(t,"tending");tending=true;break;}} + return seen.size()==4&&gathering&&hauling&&going&&eating&&tending?0:3; +} diff --git a/tests/fixtures/custody_v14/fixtures.hpp b/tests/fixtures/custody_v14/fixtures.hpp new file mode 100644 index 0000000..552f54e --- /dev/null +++ b/tests/fixtures/custody_v14/fixtures.hpp @@ -0,0 +1,541 @@ +// Frozen output of f6493e2d1cdb9e07eb18b9901fd8878b5d3fa51e; see capture.cpp. +#pragma once +#include +#include +#include +namespace custody_v14 { +struct Fixture { std::string_view name, sha256, checkpoint; std::array ticks; }; +inline constexpr std::array fixtures{{ + {"cabin-before-pickup", "6fb53ddaf7d666a5e5b0e899ffbad1d7137dea4e7a037fcf824f521cf5f0b531", + "53544843484b505402000000b6000000cf020000000000009102030405064708890a0b0c0d0e0f1007000000000000000100" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000001000000000000000500000000000000" + "2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000002000000030000000500000000" + "00000000020000000200000003000000030000000300000001000000000000001c0000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0100000000000000000000000000000000000000000002000000010000000000000003000000030000001400000000000000" + "0001000000030300000003000000020000000000000008000000030000001400000000000000000100000004020000000200" + "00000100000001000000000000000e0000000300000002010200000001000000000000000303000000020000000000000004" + "0200000002000000010000000000000005000000040000000300000005000000030000000600000003000000070000000300" + "0000080000000300000002000000000000000600000009000000030000000a000000030000000b000000030000000c000000" + "030000000d000000030000000e00000003000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000089063e25ca59b04935ace8779f45e200ab2acbca2dc88fec7e" + "c5f3504eda9248" + , { + 0x599836ebcd30a29fULL, 0xcaac4531bb7bcf12ULL, 0xe100830a1464be03ULL, 0x027cbdd51f3b01c8ULL, + 0x1df54a0c813e02d9ULL, 0x770d4f71d98b81f6ULL, 0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL, + 0x8373c6a20d010194ULL, 0xadddce31831e3cabULL, 0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL, + 0x2b7379835239007dULL, 0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, + 0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, + 0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, + 0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, + 0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, + 0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, + 0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, + 0x6681875fe5343f60ULL, 0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, + 0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, + 0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL, + 0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, + 0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, + 0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, + 0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, + 0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, + 0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, + 0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, + }}, + {"cabin-between-stops", "daca83d48f48b53f986305655017c01e4d40a73e7085d81088e5f71f7073ef4b", + "53544843484b505402000000b6000000b6020000000000009102030405064708890a0b0c0d0e0f1007000000000000000200" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000002000000000000000500000000000000" + "2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000400000000" + "0000000005000000040000000300000005000000030000000600000003000000070000000300000008000000030000000000" + "0000000000001c00000000000000000000000000000000000000000000000000000003000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000002000000" + "0100000000000000030000000300000014000000000000000000000000020000000000000008000000030000001400000000" + "00000000010000000402000000020000000100000001000000000000000e0000000300000002010200000001000000000000" + "0003030000000200000000000000040200000002000000010000000000000000000000020000000000000006000000090000" + "00030000000a000000030000000b000000030000000c000000030000000d000000030000000e000000030000000100000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "bfc296aeae849041ff62087240ac2f981e75d1791610f8f7c3bcc5e9792e6320" + , { + 0xcaac4531bb7bcf12ULL, 0xe100830a1464be03ULL, 0x027cbdd51f3b01c8ULL, 0x1df54a0c813e02d9ULL, + 0x770d4f71d98b81f6ULL, 0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL, 0x8373c6a20d010194ULL, + 0xadddce31831e3cabULL, 0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL, 0x2b7379835239007dULL, + 0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, 0xc3565d7aa175849dULL, + 0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, 0x94f2e4644ed7432dULL, + 0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, 0xdbb636c9dfd9f8edULL, + 0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, 0x8e8a57a7244dff5dULL, + 0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, 0xacd686b3f070f03dULL, + 0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, 0x0964e2e7b7e27f6dULL, + 0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, 0x6681875fe5343f60ULL, + 0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, 0x44d6d03be494df34ULL, + 0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, 0x75f2d8f87f7c8c38ULL, + 0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL, 0x6f153cf79c35aaecULL, + 0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, 0xdf427bdce3116ed0ULL, + 0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, 0x94a094811f7cac64ULL, + 0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, 0x1c546b250c06f528ULL, + 0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, 0x1576cf2428c013dcULL, + 0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, 0xf523c5258eda5e80ULL, + 0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, 0xd3790e018e3afe54ULL, + 0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, 0x049516be2922ab58ULL, + }}, + {"cabin-to-site", "86b61386600533badf032b4a17ac75c38a302f4c2b78fed37a38a76232360178", + "53544843484b505402000000b600000085020000000000009102030405064708890a0b0c0d0e0f1007000000000000000700" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000007000000000000000500000000000000" + "2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000008000000030000000400000000" + "000000000600000009000000030000000a000000030000000b000000030000000c000000030000000d000000030000000e00" + "00000300000000000000000000001c0000000000000000000000000000000000000000000000000000000300000002000000" + "0000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000" + "0000000002000000010000000000000003000000030000001400000000000000000000000002000000000000000800000003" + "000000140000000000000000000000000100000001000000000000000e000000030000000201020000000100000000000000" + "0303000000020000000000000004020000000200000001000000000000000000000002000000000000000000000002000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00232dd846a1a33102aa254a632f5ad28dd7c9da49baab15e4af6c417b21fe8b28" + , { + 0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL, 0x8373c6a20d010194ULL, 0xadddce31831e3cabULL, + 0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL, 0x2b7379835239007dULL, 0xb581902af1f964a5ULL, + 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, 0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL, + 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, 0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL, + 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, 0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL, + 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, 0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL, + 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, 0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL, + 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, 0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL, + 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, 0x6681875fe5343f60ULL, 0xe9be99df149af205ULL, + 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, 0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL, + 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, 0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL, + 0x259190664a78239aULL, 0x324e15c71a395c77ULL, 0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL, + 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, 0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL, + 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, 0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL, + 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, 0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL, + 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, 0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL, + 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, 0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL, + 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, 0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL, + 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, 0x049516be2922ab58ULL, 0x517ac5f58978ba7dULL, + 0xb433ce2bf41e42baULL, 0xc0f0538cc3df7b97ULL, 0xfdb77abd45dbca0cULL, 0x2fd00ed188d95a51ULL, + }}, + {"cabin-working", "f443380bc6ff9c74d2a24d80d0261b6cd9f7560796ae76548f2b7aa24e3ef505", + "53544843484b505402000000b60000003d020000000000009102030405064708890a0b0c0d0e0f1007000000000000000d00" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b0000000000000014000000080000000d000000000000000500000000000000" + "2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000100000001000000000000000e000000030000000200000000" + "000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000" + "0000000000000200000001000000000000000300000003000000140000000000000000000000000200000000000000080000" + "0003000000140000000000000000000000000100000001000000000000000e00000003000000020102000000010000000000" + "0000030300000002000000000000000402000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000009318a0b695a881878b8800d4ac312fa11b89fe3b0" + "62514839b4bc0b5ac25594" + , { + 0x2b7379835239007dULL, 0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, + 0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, + 0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, + 0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, + 0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, + 0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, + 0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, + 0x6681875fe5343f60ULL, 0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, + 0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, + 0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL, + 0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, + 0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, + 0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, + 0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, + 0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, + 0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, + 0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, + 0x049516be2922ab58ULL, 0x517ac5f58978ba7dULL, 0xb433ce2bf41e42baULL, 0xc0f0538cc3df7b97ULL, + 0xfdb77abd45dbca0cULL, 0x2fd00ed188d95a51ULL, 0xad56322b10d7616eULL, 0x8e557f49ef6553bbULL, + 0x6de4b9a28cb78df0ULL, 0x60a1833ddb5cc755ULL, 0xa2f7aabb8d634dd2ULL, 0xc918d2f939ee65afULL, + }}, + {"carpenter-output", "6a401e39d87c97a16fbe4e7bc4a5d7cc88f6f26b176b2551102e66aa14ace446", + "53544843484b505402000000b6000000bf030000000000009102030405064708890a0b0c0d0e0f1007000000000000001100" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000180000001800000011000000000000000400000000000000" + "0b00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000000" + "0000000200000002000000040000000000000000020000000300000002000000030000000300000000000000000000000000" + "0000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000001000000" + "0000000000000000000000000000000000000000000000003600110000050000000000000000010000000100000000000000" + "0300000003000000140000000100000000010000000103000000000000000100000001000000000000000200000002000000" + "0e02000000000000000000000000000000000000000000000000000001000000020000000200000001000000000000000000" + "000000000000010000000000000001abbc5e54e4c970fef93640a799432f9b3e1e0a0c462351d36c6d1bb3992b331b" + , { + 0xa6ec0093d932ebd8ULL, 0x87baf2e646efc9a5ULL, 0x1ab6ff5ac2d06a08ULL, 0x5b21ac6329697a51ULL, + 0x892f269f06860362ULL, 0x0ce6c8acfd0548abULL, 0x10128ab0047f29e4ULL, 0xcc8b9971929bb83dULL, + 0xb18f7c65729d2eaeULL, 0x6cff10cc2991c957ULL, 0xee671e7028e38f80ULL, 0x836fd8346ea210a9ULL, + 0x3b1e5c33e40d38baULL, 0xe2891c128cba04c3ULL, 0xab7996b49c542e9cULL, 0xfce08ee5878a2fb5ULL, + 0xc8857c8fb93a4a66ULL, 0x5bcafda5a7a0d4cfULL, 0x9068789e8a217ab8ULL, 0x731f33f4164b9621ULL, + 0xb33de24022b9c652ULL, 0x6bd1afe2193ce33bULL, 0xa1f25e81be2bc454ULL, 0x401ed1b4b68ba8cdULL, + 0xbf6fdd789c7567deULL, 0x277fa8b37cd738a7ULL, 0xe79f2e754b0372b0ULL, 0x5e5b4caafb0549f9ULL, + 0xede1e8920bdd2beaULL, 0x2545a8b9b6961593ULL, 0x68186f9c92fabe0cULL, 0xd7cc035c13ed6905ULL, + 0x85245577afe0d9d6ULL, 0x0bf76d05f70a191fULL, 0x016493e3d5aabc68ULL, 0x4e0aa86aa2aecf71ULL, + 0x6fdcbb28196055c2ULL, 0xb6fb2618e466474bULL, 0x68e55ff0b8ae7ec4ULL, 0x61f7a5cf724460ddULL, + 0x0a6251a626cc838eULL, 0x026b1d2a093a71f7ULL, 0xe1501a77a228e4a0ULL, 0x7658d43be7e765c9ULL, + 0x2e07583b5d528ddaULL, 0xd572181a05ff59e3ULL, 0xb30ae3ca1d51d9bcULL, 0xca772914473b3355ULL, + 0x03131d7a6972f2c6ULL, 0x296197d46751d86fULL, 0xcaf619893a5a2318ULL, 0x71139dc19b0aeac1ULL, + 0x443b4551b6f17632ULL, 0x69c619af9dfc37dbULL, 0xac222fcda9561bb4ULL, 0x86e7da1dcd2f53edULL, + 0x3bc4ef7c28f4c1beULL, 0xe06df1d434cfe647ULL, 0x275b095bac0978d0ULL, 0x9e1727915c0b5019ULL, + 0x34aaf0fb2280d70aULL, 0x6c0eb122cd39c0b3ULL, 0xaee17805a99e692cULL, 0xa5629d8ad39e6ca5ULL, + 0xbfb1f66260198236ULL, 0x90b9689924d6c63fULL, 0x0b94652fc0d513c8ULL, 0x4bff1238276e2411ULL, + 0x00da1e39ad9805a2ULL, 0x8491c047a4174aebULL, 0xe53a71f4452dd8a4ULL, 0x1ae5eef02a3d0e7dULL, + 0x86b763a9b34bdd6eULL, 0xbb59664ac1331f97ULL, 0x9a3e63985a219240ULL, 0x2f471d5c9fe01369ULL, + 0x2bfbc208e211e27aULL, 0xd36681e78abeae83ULL, 0xf9d3ec3333f584dcULL, 0x170e96d694ff8575ULL, + }}, + {"direct-0", "ae9fb9da88ee94c6e06905ab4dbedc291ad42fd81dfd8f5e7c1d23ffbe5b0ad4", + "53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000" + "0500000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000" + "0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000b00" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000" + "0300000003000000140000000000000000010000000101000000010000000100000001000000000000000600000003000000" + "0001010000000100000000000000010100000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000007a31faff08de99b99ec1e7f1a71b99f6c6bbf004087d" + "dd0b81acf4ca14acd130" + , { + 0xcb3aa5dfb03965c9ULL, 0xeabf911762701811ULL, 0x3267ff311c8f5285ULL, 0xc9a54b382b66e91dULL, + 0x3eadc9b41b6a79c1ULL, 0x88d52de6de23fa69ULL, 0xda6625e9c8402245ULL, 0xdf431e91a4cc8a4dULL, + 0x88968629292726d9ULL, 0x90616d8a80511ad1ULL, 0xefc3df7a957d1395ULL, 0x1e8ec6e4dc12bf8eULL, + 0xdaf77dfbd58cb967ULL, 0x611d034605ba46f0ULL, 0x2fe16de272eb1379ULL, 0xd3cfbd66bb79843aULL, + 0x91b047e412719a33ULL, 0x1a8b985c61eb123cULL, 0xf23946c97dcc7825ULL, 0x3f4e05a9cdb2c0f6ULL, + 0xbcc048eb14dcb00fULL, 0x08ff6dc7f49a22f8ULL, 0x4b90993f02ab24c1ULL, 0xb5988855fac97ae2ULL, + 0x737912d351c190dbULL, 0xfc54634ba13b08e4ULL, 0xd40211b8bd1c6ecdULL, 0x2116d0990d02b79eULL, + 0x514c488aa75ce6b7ULL, 0x63a50cfa36aa3f00ULL, 0xa636387144bb40c9ULL, 0xd657c71aec697c4aULL, + 0x9438519843619243ULL, 0x1d13a21092db0a4cULL, 0xf4c1507daebc7035ULL, 0xb5a2d0389f82ee46ULL, + 0x33151379e6acdd5fULL, 0x7f543856c66a5048ULL, 0x4e18a2f3339b1cd1ULL, 0xb820920a2bb972f2ULL, + 0x76011c8782b188ebULL, 0xfedc6cffd22b00f4ULL, 0xd68a1b6cee0c66ddULL, 0x976b9b27ded2e4eeULL, + 0x53d4523ed84cdec7ULL, 0xd9f9d789087a6c50ULL, 0xa8be422575ab38d9ULL, 0x4cac91a9be39a99aULL, + 0x0a8d1c271531bf93ULL, 0x93686c9f64ab379cULL, 0x6b161b0c808c9d85ULL, 0xb82ad9ecd072e656ULL, + 0x359d1d2e179cd56fULL, 0x81dc420af75a4858ULL, 0xc46d6d82056b4a21ULL, 0x2e755c98fd89a042ULL, + 0xec55e7165481b63bULL, 0x7531378ea3fb2e44ULL, 0x4cdee5fbbfdc942dULL, 0x99f3a4dc0fc2dcfeULL, + 0xe6b5cbc19f1c7697ULL, 0xf90e90312e69cee0ULL, 0x3b9fbba83c7ad0a9ULL, 0x6bc14a51e4290c2aULL, + 0x29a1d4cf3b212223ULL, 0xb27d25478a9a9a2cULL, 0x8a2ad3b4a67c0015ULL, 0x4b0c536f97427e26ULL, + 0xc87e96b0de6c6d3fULL, 0x14bdbb8dbe29e028ULL, 0xe382262a2b5aacb1ULL, 0x4d8a1541237902d2ULL, + 0x0b6a9fbe7a7118cbULL, 0x9445f036c9ea90d4ULL, 0x6bf39ea3e5cbf6bdULL, 0x2cd51e5ed69274ceULL, + 0xe93dd575d00c6ea7ULL, 0x6f635ac00039fc30ULL, 0x3e27c55c6d6ac8b9ULL, 0xe21614e0b5f9397aULL, + }}, + {"direct-1", "452313012591f9337c1410095355887d778a47c225d09b3fe550d9f8ec2cc67a", + "53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000" + "0500000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000" + "0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000f00" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000" + "0300000003000000140000000000000000010000000201000000010000000100000001000000000000000600000003000000" + "0101010000000100000000000000020100000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000d4e59fb1f410d7b6ab8e531ff066559d5d44677d61c6" + "544d069a18fd0269e030" + , { + 0x37ae3152f9978e76ULL, 0x57331c8aabce40beULL, 0x1351af3574563b7aULL, 0xaa8efb3c832dd212ULL, + 0xc09abf5a0172a736ULL, 0xdfcf4f278ad81e4eULL, 0xa5d66bbb835d0672ULL, 0xd5a638c8993d780aULL, + 0xf50a119c72854f86ULL, 0xfcd4f8fdc9af437eULL, 0xd0ad8f7eed43fc8aULL, 0x5030d7afa10ed4d2ULL, + 0x3d54d6a175847066ULL, 0x44cf6298a3dd292eULL, 0x0ad67f2c9c621152ULL, 0xcd445e1c36765956ULL, + 0x1d1b333928ab77cbULL, 0x8f20ad074bb134a4ULL, 0xf8c4a61402cfa309ULL, 0x2f038e4a264230aaULL, + 0x29580d1fd74f61dfULL, 0x9c67a99332277128ULL, 0x5bdb109eaa1bb50dULL, 0xaf0d290b75c64ffeULL, + 0xfee3fe2867fb6e73ULL, 0x70e977f68b012b4cULL, 0xda8d7103421f99b1ULL, 0x10cc593965922752ULL, + 0xbde40cbf69cf9887ULL, 0xf70d48c574378d30ULL, 0xb680afd0ec2bd115ULL, 0xcfcc67d067665166ULL, + 0x1fa33ced599b6fdbULL, 0x91a8b6bb7ca12cb4ULL, 0xfb4cafc833bf9b19ULL, 0xa55858d8f8125dfaULL, + 0x9facd7aea91f8f2fULL, 0x12bc742203f79e78ULL, 0x5e631a52db0bad1dULL, 0xb19532bfa6b6480eULL, + 0x016c07dc98eb6683ULL, 0x737181aabbf1235cULL, 0xdd157ab7730f91c1ULL, 0x872123c8376254a2ULL, + 0xc06c16739abf9097ULL, 0x6d6213544607ba80ULL, 0xb908b9851d1bc925ULL, 0x4621325f39367eb6ULL, + 0x95f8077c2b6b9d2bULL, 0x07fd814a4e715a04ULL, 0x71a17a57058fc869ULL, 0xa7e0628d2902560aULL, + 0xa234e162da0f873fULL, 0x15447dd634e79688ULL, 0xd4b7e4e1acdbda6dULL, 0x27e9fd4e7886755eULL, + 0x77c0d26b6abb93d3ULL, 0xe9c64c398dc150acULL, 0x536a454644dfbf11ULL, 0x89a92d7c68524cb2ULL, + 0x534d8ff6618f2867ULL, 0x8c76cbfc6bf71d10ULL, 0x4bea3307e3eb60f5ULL, 0x6535eb075f25e146ULL, + 0xb50cc024515affbbULL, 0x271239f27460bc94ULL, 0x90b632ff2b7f2af9ULL, 0x3ac1dc0fefd1eddaULL, + 0x35165ae5a0df1f0fULL, 0xa825f758fbb72e58ULL, 0xf3cc9d89d2cb3cfdULL, 0x46feb5f69e75d7eeULL, + 0x96d58b1390aaf663ULL, 0x08db04e1b3b0b33cULL, 0x727efdee6acf21a1ULL, 0x1c8aa6ff2f21e482ULL, + 0x55d599aa927f2077ULL, 0x02cb968b3dc74a60ULL, 0x4e723cbc14db5905ULL, 0xdb8ab59630f60e96ULL, + }}, + {"direct-4", "34fddc7587d05b995c207d9db896146154ace52dc152e62004efac370c1258ec", + "53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000200000000000000" + "0900000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002" + "0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000" + "0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000b00" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000" + "0300000003000000140000000000000000010000000701000000010000000100000001000000000000000600000003000000" + "0401010000000100000000000000070100000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000db4ee0a01a3bdbe2c73bce9fb3c27baca13e5aaa12a1" + "d06e25ec370dcebd6e75" + , { + 0x390c415e34d0166aULL, 0x554a4dca2da2d072ULL, 0x0a6d78876d939f76ULL, 0x3746c232f2e153feULL, + 0x1dac5cc0bc01befaULL, 0x2230655659c7bab2ULL, 0xc98216266ea8b8ceULL, 0xcb18300291d12896ULL, + 0x8c028e6e517d8faaULL, 0x15e0477b18051b22ULL, 0xcb03723857f5ea26ULL, 0x550bb6fd219fa238ULL, + 0x6cf696b2deed2d21ULL, 0xb5fe1220613db27aULL, 0x134d258ced91df3bULL, 0xca82240862b0591cULL, + 0x9e3eceaeb9118035ULL, 0xf8bc7d34089f3e3eULL, 0xd1d2bf535ea84f7fULL, 0xb666fe781169bcf0ULL, + 0x0e2358ec20130a79ULL, 0x572ad459a2638fd2ULL, 0xb479e7c62eb7bc93ULL, 0x6baee641a3d63674ULL, + 0x3f6b90e7fa375d8dULL, 0x6002defff95500f6ULL, 0xace5e1f9f03e4777ULL, 0x5793c0b1528f9a48ULL, + 0xe34b6141b0bd5a71ULL, 0xb8861bd4922daa8aULL, 0x15d52f411e81d74bULL, 0xcd0a2dbc93a0512cULL, + 0xa0c6d862ea017845ULL, 0xfb4486e8398f364eULL, 0x482789e230787ccfULL, 0x2cbbc906e339ea40ULL, + 0x8478237af1e337c9ULL, 0x59b2de0dd35387e2ULL, 0xb701f17a5fa7b4a3ULL, 0x6e36eff5d4c62e84ULL, + 0x41f39a9c2b27559dULL, 0xd657a98ecb252e46ULL, 0xaf6debae212e3f87ULL, 0xcde88b40245fc798ULL, + 0xe5d36af5e1ad5281ULL, 0x2edae66363fdd7daULL, 0x8c29f9cff052049bULL, 0x435ef84b65707e7cULL, + 0x171ba2f1bbd1a595ULL, 0x719951770b5f639eULL, 0x4aaf9396616874dfULL, 0x2f43d2bb1429e250ULL, + 0x87002d2f22d32fd9ULL, 0xd007a89ca523b532ULL, 0x2d56bc093177e1f3ULL, 0xe48bba84a6965bd4ULL, + 0xb848652afcf782edULL, 0xd8dfb342fc152656ULL, 0x25c2b63cf2fe6cd7ULL, 0xd07094f4554fbfa8ULL, + 0x78b4e478a87cea51ULL, 0x4def9f0b89ed3a6aULL, 0xab3eb2781641672bULL, 0x6273b0f38b5fe10cULL, + 0x36305b99e1c10825ULL, 0x90ae0a1f314ec62eULL, 0xdd910d1928380cafULL, 0xc2254c3ddaf97a20ULL, + 0x19e1a6b1e9a2c7a9ULL, 0xef1c6144cb1317c2ULL, 0x4c6b74b157674483ULL, 0x03a0732ccc85be64ULL, + 0xd75d1dd322e6e57dULL, 0x6bc12cc5c2e4be26ULL, 0x44d76ee518edcf67ULL, 0x63520e771c1f5778ULL, + 0x7b3cee2cd96ce261ULL, 0xc444699a5bbd67baULL, 0x21937d06e811947bULL, 0xd8c87b825d300e5cULL, + }}, + {"harvest-gathering", "2983ac00f777101dd7d71bd7379764ac32aa2330608fed9a4bf4dc1f2ee01426", + "53544843484b505402000000b600000069020000000000009102030405064708890a0b0c0d0e0f1007000000000000000200" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000002000000000000000200000000000000" + "0f00000000000000000000000000000000000000000000000002000000000000000100000000000000020000000000000002" + "0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000300000000" + "0000000002000000020000000300000003000000030000000200000000000000020000000100000000000000010000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000" + "0400000003000000050000000300000006000000030000000700000003000000080000000300000009000000030000000a00" + "0000030000000b000000030000000c000000030000000d000000030000000e00000003000000000000000000000000000000" + "0000000000000100000001000000000000000300000003000000010100000001000000010000000100000000000000000001" + "00000001000000000000000e0000000300000014000000010000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000006719c2fed4abf63ffe4456b03d95b13c12ef3078097d13e1a1b74a" + "bb30b5cf17" + , { + 0x4034a5761e22ecabULL, 0xf78178bf59b905d9ULL, 0x5fd5644d1fa59357ULL, 0xaa768617a1b90374ULL, + 0x6ceeba0f2fe9089dULL, 0xee339afe091ed342ULL, 0xaeb06ae4ea87af53ULL, 0x7b6079611fd6a880ULL, + 0xbbc9c0a6facb2499ULL, 0xe75c76afc2037eceULL, 0xec829e3d4f72762fULL, 0x07bfb4a042a471ecULL, + 0x55e6cc33aa390f75ULL, 0x3e52625e8b2045b6ULL, 0x4f7d9d5bcf978d4dULL, 0x303f84c95c235208ULL, + 0xb2896b1b8df536cfULL, 0xc0fc67ce76a32cbaULL, 0x421810bd51ac0c71ULL, 0x32d353a79afcd8dcULL, + 0x9dd13f2ee856f313ULL, 0xac443be1d104e8feULL, 0x61a1fa6a365c4a35ULL, 0xd6d4e506f73bbaf0ULL, + 0x51cc2c0b015adcd7ULL, 0x603f28bdea08d2c2ULL, 0x543c6dcbb870c959ULL, 0xfdbfa374e6fab424ULL, + 0x44669f6c836f5bfbULL, 0x52d99c1f6c1d51e6ULL, 0x6404d71cb094997dULL, 0x44c6be8a3d205e38ULL, + 0x06f612cf620661bfULL, 0x15690f824ab457aaULL, 0x9684b87125bd3761ULL, 0x873ffb5b6f0e03ccULL, + 0xb25878efc953ff43ULL, 0xc0cb75a2b201f52eULL, 0x7629342b17595665ULL, 0x2b418cbacb4ce5e0ULL, + 0x665365cbe257e907ULL, 0x74c6627ecb05def2ULL, 0xa8a9157f8c81f449ULL, 0x522c4b28bb0bdf14ULL, + 0x98d34720578086ebULL, 0xa74643d3402e7cd6ULL, 0xb8717ed084a5c46dULL, 0x9933663e11318928ULL, + 0x1b7d4c9043036defULL, 0x29f049432bb163daULL, 0xab0bf23206ba4391ULL, 0x9bc7351c500b0ffcULL, + 0x06c520a39d652a33ULL, 0x15381d568613201eULL, 0xca95dbdeeb6a8155ULL, 0x3fc8c67bac49f210ULL, + 0xbac00d7fb66913f7ULL, 0xc9330a329f1709e2ULL, 0xbd304f406d7f0079ULL, 0x66b384e99c08eb44ULL, + 0xad5a80e1387d931bULL, 0xbbcd7d94212b8906ULL, 0x292932be9169f41dULL, 0x09eb1a2c1df5b8d8ULL, + 0xcc1a6e7142dbbc5fULL, 0xda8d6b242b89b24aULL, 0x5ba9141306929201ULL, 0x4c6456fd4fe35e6cULL, + 0x777cd491aa2959e3ULL, 0x85efd14492d74fceULL, 0x3b4d8fccf82eb105ULL, 0xf065e85cac224080ULL, + 0x2b77c16dc32d43a7ULL, 0x39eabe20abdb3992ULL, 0x6dcd71216d574ee9ULL, 0x1750a6ca9be139b4ULL, + 0x5df7a2c23855e18bULL, 0x6c6a9f752103d776ULL, 0x7d95da72657b1f0dULL, 0x5e57c1dff206e3c8ULL, + }}, + {"harvest-hauled", "038b7ae299004c672e20cefb6c50ab9bacd6f83606ceca83d9d5edd20ff8cfad", + "53544843484b505402000000b600000059020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000200000000000000" + "0f00000000000000000000000000000000000000000000000002000000000000000100000000000000020000000000000002" + "0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000400000000" + "000000000b000000040000000300000005000000030000000600000003000000070000000300000008000000030000000900" + "0000030000000a000000030000000b000000030000000c000000030000000d000000030000000e0000000300000000000000" + "0000000000000000000000000000000001000000000000000100000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000001000000010000000000" + "0000030000000300000001000000000100000000000000010000000000000000000100000001000000000000000e00000003" + "0000001400000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000df9205984b13c7ea46ccd323ab458977e4ea273b047760dbebb30e7fd311d16f" + , { + 0x5fd5644d1fa59357ULL, 0xaa768617a1b90374ULL, 0x6ceeba0f2fe9089dULL, 0xee339afe091ed342ULL, + 0xaeb06ae4ea87af53ULL, 0x7b6079611fd6a880ULL, 0xbbc9c0a6facb2499ULL, 0xe75c76afc2037eceULL, + 0xec829e3d4f72762fULL, 0x07bfb4a042a471ecULL, 0x55e6cc33aa390f75ULL, 0x3e52625e8b2045b6ULL, + 0x4f7d9d5bcf978d4dULL, 0x303f84c95c235208ULL, 0xb2896b1b8df536cfULL, 0xc0fc67ce76a32cbaULL, + 0x421810bd51ac0c71ULL, 0x32d353a79afcd8dcULL, 0x9dd13f2ee856f313ULL, 0xac443be1d104e8feULL, + 0x61a1fa6a365c4a35ULL, 0xd6d4e506f73bbaf0ULL, 0x51cc2c0b015adcd7ULL, 0x603f28bdea08d2c2ULL, + 0x543c6dcbb870c959ULL, 0xfdbfa374e6fab424ULL, 0x44669f6c836f5bfbULL, 0x52d99c1f6c1d51e6ULL, + 0x6404d71cb094997dULL, 0x44c6be8a3d205e38ULL, 0x06f612cf620661bfULL, 0x15690f824ab457aaULL, + 0x9684b87125bd3761ULL, 0x873ffb5b6f0e03ccULL, 0xb25878efc953ff43ULL, 0xc0cb75a2b201f52eULL, + 0x7629342b17595665ULL, 0x2b418cbacb4ce5e0ULL, 0x665365cbe257e907ULL, 0x74c6627ecb05def2ULL, + 0xa8a9157f8c81f449ULL, 0x522c4b28bb0bdf14ULL, 0x98d34720578086ebULL, 0xa74643d3402e7cd6ULL, + 0xb8717ed084a5c46dULL, 0x9933663e11318928ULL, 0x1b7d4c9043036defULL, 0x29f049432bb163daULL, + 0xab0bf23206ba4391ULL, 0x9bc7351c500b0ffcULL, 0x06c520a39d652a33ULL, 0x15381d568613201eULL, + 0xca95dbdeeb6a8155ULL, 0x3fc8c67bac49f210ULL, 0xbac00d7fb66913f7ULL, 0xc9330a329f1709e2ULL, + 0xbd304f406d7f0079ULL, 0x66b384e99c08eb44ULL, 0xad5a80e1387d931bULL, 0xbbcd7d94212b8906ULL, + 0x292932be9169f41dULL, 0x09eb1a2c1df5b8d8ULL, 0xcc1a6e7142dbbc5fULL, 0xda8d6b242b89b24aULL, + 0x5ba9141306929201ULL, 0x4c6456fd4fe35e6cULL, 0x777cd491aa2959e3ULL, 0x85efd14492d74fceULL, + 0x3b4d8fccf82eb105ULL, 0xf065e85cac224080ULL, 0x2b77c16dc32d43a7ULL, 0x39eabe20abdb3992ULL, + 0x6dcd71216d574ee9ULL, 0x1750a6ca9be139b4ULL, 0x5df7a2c23855e18bULL, 0x6c6a9f752103d776ULL, + 0x7d95da72657b1f0dULL, 0x5e57c1dff206e3c8ULL, 0xe0a1a83223d8c88fULL, 0xef14a4e50c86be7aULL, + }}, + {"meal-eating", "6ef841c3978ffb1cc6c622485ae00f612b8df62e728a00998dff39c4cb23dd86", + "53544843484b505402000000b6000000e3010000000000009102030405064708890a0b0c0d0e0f1007000000000000009b00" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b0000000000000014000000080000009b000000000000000100000000000000" + "0e00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002" + "0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000100000001000000000000000e000000030000000700000000" + "0000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000000" + "000001000000000000000000000000000000000000000000000000000000000000000000000000000000c000000000000000" + "0000000000000100000001000000000000000e00000003000000140000000000000001010000000504000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000000000cbca12e9de2b541fa0a67c" + "950419717981e249938bede98f7bc5ac8b21bb41e4" + , { + 0x0eae6cbd44a5eb4cULL, 0x666bd2a801c60dc5ULL, 0xaa5ed34a6065dbaaULL, 0x0de79ba8983d3fb3ULL, + 0x99ab26421b611ba8ULL, 0xc09e84ec6875f729ULL, 0xec94b6b0b80ab7b5ULL, 0xf98239f36dc2c19dULL, + 0xd44d9d9512ae9821ULL, 0xa5f198ebe67c6949ULL, 0x6960ffccf032887dULL, 0x892b7289233b1e85ULL, + 0xa0d41230356d6121ULL, 0xccf5a29ed61d7299ULL, 0x38d1425618c651e5ULL, 0x47a8b158ccfd867dULL, + 0x227414fa71e95d01ULL, 0x997c1739f8dc3b99ULL, 0xb78777324f6d4d5dULL, 0x7cb5f0d7359af0d5ULL, + 0x07c728f9efefcf21ULL, 0xce1cfa5e52220209ULL, 0x84c0a7e6fb14fc35ULL, 0x91ae2b29b0cd061dULL, + 0x6c798ecb55b8dca1ULL, 0xb3700e5dd0287429ULL, 0x018cf103333cccfdULL, 0x96a9e7fb0ce72965ULL, + 0x390003667877a5a1ULL, 0x652193d51927b719ULL, 0x464fb7c802725cc5ULL, 0xdfd4a28f1007cafdULL, + 0xbaa00630b4f3a181ULL, 0x31a808703be68019ULL, 0x4fb36868927791ddULL, 0x14e1e20d78a53555ULL, + 0x9ff31a3032fa13a1ULL, 0x44f1d52f88f4cf69ULL, 0x70e806f3d8898ff5ULL, 0x7dd58a368e4199ddULL, + 0x6dfbe560e5e9e3a1ULL, 0x3f9fe0b7b9b7b4c9ULL, 0x030f4798c36dd3fdULL, 0x0d7ec2cc43b9f6c5ULL, + 0x3a8259fc08a8aca1ULL, 0x5148f2e1f69c4ad9ULL, 0xd27f8a21ec019d65ULL, 0xe156f924a038d1fdULL, + 0xa6c7653d92683541ULL, 0x1dcf677d195b13d9ULL, 0x3bdac7756fec259dULL, 0x166438a308d63c55ULL, + 0xa17570c5c32b1aa1ULL, 0x67cb422a255d4d89ULL, 0x0913f82a1b93d475ULL, 0x16017b6cd14bde5dULL, + 0x0627d69728f42821ULL, 0x37c35ea0f0a74c69ULL, 0x9b3b38cf0678187dULL, 0x30582fc6e02274e5ULL, + 0xd2ae4b324bb2f121ULL, 0xe974e41839a68f59ULL, 0xcaa3080b22f13505ULL, 0x7982ea5ae343167dULL, + 0x3ef35673d57279c1ULL, 0xb5fb58b35c655859ULL, 0xd406b8abb2f66a1dULL, 0xae9029d94be080d5ULL, + 0x39a161fc06355f21ULL, 0x8aa4af24c1c5cba9ULL, 0xb69ae0e9115a8c35ULL, 0x98d2751a6199af9dULL, + 0x739dd8bc06858621ULL, 0x6ff7c3243fcc3dc9ULL, 0x33672a0549825cfdULL, 0x287badb017120c85ULL, + 0x40244d5729444f21ULL, 0x96fbccd72f6d4719ULL, 0x02d76c8e72162665ULL, 0x11aedb91264d5afdULL, + }}, + {"meal-going", "2bf42eb752cdbb6d06a69cfe3f7eb68cbf0686d5ec855b986599b2f4b589390d", + "53544843484b505402000000b60000004b020000000000009102030405064708890a0b0c0d0e0f1007000000000000008f00" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b0000000000000014000000080000008f000000000000000100000000000000" + "0e00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002" + "0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000002000000030000000600000000" + "000000000d000000020000000300000003000000030000000400000003000000050000000300000006000000030000000700" + "000003000000080000000300000009000000030000000a000000030000000b000000030000000c000000030000000d000000" + "030000000e000000030000000100000000000000000000000000000000000000010000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b4000000" + "000000000000000000000100000001000000000000000e000000030000001400000000000000010100000005050000000100" + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000919d8854127c30" + "0dbea118a7d16c7f0c3044dd54f2148b20800d6204105412e3" + , { + 0xfd9dfc2a0c96299dULL, 0x055fa24bd46f74c7ULL, 0xc3a99a4764c3bac9ULL, 0x788d6816d3b41547ULL, + 0xabaedc2e42067cddULL, 0xad632a0f1d2c4b17ULL, 0xc9b73d3b4e831031ULL, 0x7d5bc37e22cdc2f7ULL, + 0xcc366163e21db0fdULL, 0xe24026ad5ef92427ULL, 0xa4867348eeb2b129ULL, 0x165dc919e3326217ULL, + 0x0eae6cbd44a5eb4cULL, 0x666bd2a801c60dc5ULL, 0xaa5ed34a6065dbaaULL, 0x0de79ba8983d3fb3ULL, + 0x99ab26421b611ba8ULL, 0xc09e84ec6875f729ULL, 0xec94b6b0b80ab7b5ULL, 0xf98239f36dc2c19dULL, + 0xd44d9d9512ae9821ULL, 0xa5f198ebe67c6949ULL, 0x6960ffccf032887dULL, 0x892b7289233b1e85ULL, + 0xa0d41230356d6121ULL, 0xccf5a29ed61d7299ULL, 0x38d1425618c651e5ULL, 0x47a8b158ccfd867dULL, + 0x227414fa71e95d01ULL, 0x997c1739f8dc3b99ULL, 0xb78777324f6d4d5dULL, 0x7cb5f0d7359af0d5ULL, + 0x07c728f9efefcf21ULL, 0xce1cfa5e52220209ULL, 0x84c0a7e6fb14fc35ULL, 0x91ae2b29b0cd061dULL, + 0x6c798ecb55b8dca1ULL, 0xb3700e5dd0287429ULL, 0x018cf103333cccfdULL, 0x96a9e7fb0ce72965ULL, + 0x390003667877a5a1ULL, 0x652193d51927b719ULL, 0x464fb7c802725cc5ULL, 0xdfd4a28f1007cafdULL, + 0xbaa00630b4f3a181ULL, 0x31a808703be68019ULL, 0x4fb36868927791ddULL, 0x14e1e20d78a53555ULL, + 0x9ff31a3032fa13a1ULL, 0x44f1d52f88f4cf69ULL, 0x70e806f3d8898ff5ULL, 0x7dd58a368e4199ddULL, + 0x6dfbe560e5e9e3a1ULL, 0x3f9fe0b7b9b7b4c9ULL, 0x030f4798c36dd3fdULL, 0x0d7ec2cc43b9f6c5ULL, + 0x3a8259fc08a8aca1ULL, 0x5148f2e1f69c4ad9ULL, 0xd27f8a21ec019d65ULL, 0xe156f924a038d1fdULL, + 0xa6c7653d92683541ULL, 0x1dcf677d195b13d9ULL, 0x3bdac7756fec259dULL, 0x166438a308d63c55ULL, + 0xa17570c5c32b1aa1ULL, 0x67cb422a255d4d89ULL, 0x0913f82a1b93d475ULL, 0x16017b6cd14bde5dULL, + 0x0627d69728f42821ULL, 0x37c35ea0f0a74c69ULL, 0x9b3b38cf0678187dULL, 0x30582fc6e02274e5ULL, + 0xd2ae4b324bb2f121ULL, 0xe974e41839a68f59ULL, 0xcaa3080b22f13505ULL, 0x7982ea5ae343167dULL, + 0x3ef35673d57279c1ULL, 0xb5fb58b35c655859ULL, 0xd406b8abb2f66a1dULL, 0xae9029d94be080d5ULL, + }}, + {"tending", "3827f807449b4eef713945b5e196e082e48e10d7971587e8281f3f858f76c475", + "53544843484b505402000000b600000004020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400" + "00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65" + "6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089" + "0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab" + "7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000" + "0500000000000000000000000000000000000000000000000102000000000000000100000000000000020000000000000001" + "0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000001000000010000000000000005000000030000000300000000" + "0000000004000000020000000300000003000000030000000400000003000000050000000300000004000000000000000500" + "0000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000002900040000000000000001000000010000000000000005000000" + "0300000001000000000600000001000000010200000000000000000000000000000000010000000200000002000000010000" + "00000000000000000000000000010000000000000001b4030ca9d1f16481a8e535b4d15d5386c3373d95462d4d421acb8c39" + "bffd838c" + , { + 0x40e38438faf94b0bULL, 0x14761863e62e2a4dULL, 0xe6cd2e9002d72edbULL, 0x05e511dfedbab179ULL, + 0xa31d1be8a64993d3ULL, 0x2689b1c58ae359daULL, 0x0a35fc84aa4f48c7ULL, 0xfcb493ac0b7a9ca0ULL, + 0xa5b6852baae0b5d5ULL, 0x475c01f9c9b77106ULL, 0x8f687924c6abc753ULL, 0xda1797bdf654a5fcULL, + 0x06e3f4bcdb5865e1ULL, 0xcfc208819fd468a2ULL, 0x8f5cf81cd325dcefULL, 0xab87d8ad5efdc448ULL, + 0x9596d5a2eab7763dULL, 0xc5aea624fbd7c04eULL, 0xd450e36c43ad31dbULL, 0xa28d719e4a7f7b04ULL, + 0x9397942622050189ULL, 0xed40d75b33713baaULL, 0x8b456815cce24137ULL, 0x914e242111a8c7d0ULL, + 0x2ccbce0483ab8405ULL, 0xbbfc27d8b7020bb6ULL, 0x332345807b3a2dc3ULL, 0x9762664544b614ecULL, + 0x80116ad6bde724d1ULL, 0x68fb7be5021b5cf2ULL, 0xfc7eb3a74944f05fULL, 0x67bda54ab54433f8ULL, + 0x58e78171ef50baedULL, 0x88ff51f4007104feULL, 0x59ed9f385b844e8bULL, 0x3d906a7dcfbe2e34ULL, + 0x1aacdcfefacfcfb9ULL, 0x7d5eec1f9d8fca7aULL, 0x4d8111fad96086a7ULL, 0x55025b12df1abec0ULL, + 0xc29ec7a141fddb35ULL, 0x8c1fa47cb9bc6066ULL, 0xd42c1ba7b6b0b6b3ULL, 0x0a89ff17710cfe1cULL, + 0x3d5c395e0c4893c1ULL, 0x130d1df7cee5a682ULL, 0xb9c9822e97a65f4fULL, 0xc26a3ddb3fe313e8ULL, + 0xcc0f1a441ba7a41dULL, 0xfc26eac62cc7ee2eULL, 0xefc098d519d6a5bbULL, 0xdfd2a9ccc358e324ULL, + 0xb07fd69bb92226e9ULL, 0x519a59517381094aULL, 0xa6b51d7ea30bb517ULL, 0xb43c43de5efdc2f0ULL, + 0x7016e37ab2bcc1e5ULL, 0xff473d4ee6134996ULL, 0x766e5af6aa4b6ba3ULL, 0xaccc3e6664a7b30cULL, + 0xc302fb492ed47b31ULL, 0x1fc6fc206a2749d2ULL, 0xb34a33e2b150dd3fULL, 0x6f49b0cbe9ae8d98ULL, + 0x8e54ca4832dab44dULL, 0x0caacdd834d6e0deULL, 0x810f8a2cdff9866bULL, 0xab721e2bcde3c154ULL, + 0x9d91429d9d844719ULL, 0xe0ad724af039639aULL, 0x74a2fcef5dd5be87ULL, 0xc2e40ec0dd4051e0ULL, + 0x5e61b8a44f430e15ULL, 0xb3418f713e319846ULL, 0x3c07f20dfe9e7413ULL, 0xa04712d2c81a5b3cULL, + 0x72c982344fd28d21ULL, 0x2caac15025f78162ULL, 0x558c7331a4eb922fULL, 0xfc64d6ec78b13188ULL, + }}, +}}; +} // namespace custody_v14 From 6c6f4e7857eebf236e657530e0736025f48223ec Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:10:35 +0300 Subject: [PATCH 03/10] Track transfers, reservations and item owners through colony work --- CMakeLists.txt | 2 + engine/src/custody.cpp | 606 ++++++++++++++++++++++++++++++++++++++++ engine/src/world.cpp | 249 ++++++++++++----- tests/custody_tests.cpp | 187 +++++++++++++ 4 files changed, 972 insertions(+), 72 deletions(-) create mode 100644 engine/src/custody.cpp create mode 100644 tests/custody_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e6f933..dae9f5f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,6 +39,7 @@ endif() find_package(Threads REQUIRED) add_library(settlement_core + engine/src/custody.cpp engine/src/checkpoint.cpp engine/src/checkpoint_files.cpp engine/src/colony_profile.cpp @@ -121,6 +122,7 @@ if(BUILD_TESTING) add_executable(settlement_core_tests tests/checkpoint_tests.cpp tests/checkpoint_file_tests.cpp + tests/custody_tests.cpp tests/core_tests.cpp tests/executor_tests.cpp tests/identity_tests.cpp diff --git a/engine/src/custody.cpp b/engine/src/custody.cpp new file mode 100644 index 0000000..8662c9b --- /dev/null +++ b/engine/src/custody.cpp @@ -0,0 +1,606 @@ +#include "settlement/core/world.hpp" +#include "settlement/core/inventory_transaction.hpp" +#include +#include +#include +#include +#include + +namespace settlement { +namespace { +constexpr auto maximum = std::numeric_limits::max(); +bool room(std::uint64_t next, std::uint64_t count) noexcept { + return next != 0 && count <= maximum - next; +} +auto stock(Storage& storage, ItemType item) { + return std::find_if(storage.items.begin(), storage.items.end(), [item](const auto& s) { return s.type == item; }); +} +void retarget(TransferExecution& execution, StockOwner from, StackId old_id, + StockOwner to, StackId new_id) noexcept { + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Item && claim.owner == from && claim.stack == old_id) { + claim.owner = to; + claim.stack = new_id; + } + } +} +CustodyRequest operation_request(const Agent& agent, CustodyOperation operation, + StorageId source, StorageId destination) { + CustodyRequest request; + request.key = {CustodyKeyKind::Operation, agent.execution->id, agent.execution->next_operation}; + request.operation = operation; + request.kind = agent.execution->kind; + request.production = agent.execution->production; + request.source = source; + request.destination = destination; + return request; +} +void effects(CustodyResult& result, const Inventory& inventory, StockOwner owner) { + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + if (inventory.item_count(item)) result.effects[result.effect_count++] = + {owner, inventory.stack_id(item), item, inventory.item_count(item)}; + } +} +} + +StackId Inventory::stack_id(ItemType type) const noexcept { + const auto i = static_cast(type); + return i > 0 && i <= stack_ids_.size() ? stack_ids_[i - 1] : 0; +} +void Inventory::set_stack_id(ItemType type, StackId id) noexcept { + const auto i = static_cast(type); + if (i > 0 && i <= stack_ids_.size()) stack_ids_[i - 1] = id; +} + +void World::record_custody(std::shared_ptr receipt) noexcept { + if (custody_receipts_.size() < custody_receipt_limit) custody_receipts_.push_back(std::move(receipt)); + else { + custody_receipts_[custody_receipt_cursor_] = std::move(receipt); + custody_receipt_cursor_ = (custody_receipt_cursor_ + 1) % custody_receipt_limit; + } +} +std::shared_ptr World::prepare_custody(Agent& agent, CustodyOperation operation, + CustodyStatus status, StorageId source, StorageId destination) { + if (!agent.execution || !room(agent.execution->next_operation, 1)) return {}; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, operation, source, destination); + receipt->result.status = status; + receipt->result.transfer = agent.execution->id; + return receipt; +} +void World::commit_custody(Agent& agent, std::shared_ptr receipt) noexcept { + agent.execution->blocked = receipt->result.status; + ++agent.execution->next_operation; + record_custody(std::move(receipt)); +} +CustodyResult World::custody_request(const CustodyRequest& request) { + // The scheduler issues operations. This endpoint recovers their exact result; + // it never admits unissued work through an out-of-order retry. + for (const auto& receipt : custody_receipts_) { + if (receipt->request.key == request.key) { + return receipt->request == request ? receipt->result : CustodyResult{CustodyStatus::Conflict}; + } + } + if (request.key.id == 0 || request.key.ordinal == 0) return {CustodyStatus::Invalid}; + if (request.key.kind == CustodyKeyKind::Admission) { + const auto actor = std::find_if(agents_.begin(), agents_.end(), [&](const auto& a) { return a.id == request.key.id; }); + if (actor == agents_.end()) return {CustodyStatus::Invalid}; + return {request.key.ordinal < actor->next_admission ? CustodyStatus::Stale : CustodyStatus::Future}; + } + if (request.key.kind != CustodyKeyKind::Operation) return {CustodyStatus::Invalid}; + for (const auto& agent : agents_) { + if (agent.execution && agent.execution->id == request.key.id) { + return {request.key.ordinal < agent.execution->next_operation ? CustodyStatus::Stale : CustodyStatus::Future}; + } + } + return {request.key.id < next_transfer_id_ ? CustodyStatus::Stale : CustodyStatus::Future}; +} + +bool World::admit_custody(Agent& agent, TransferKind kind, ProductionId production, + ResourceNodeId source, StorageId destination, const std::vector& materials) { + if (agent.execution || !room(next_transfer_id_, 1) || !room(agent.next_admission, 1) || + materials.size() > custody_material_limit) return false; + TransferExecution execution; + execution.id = next_transfer_id_; + execution.kind = kind; + execution.production = production; + execution.source = source; + execution.destination = destination; + auto next = next_reservation_id_; + const auto add = [&](Reservation claim) { + if (!room(next, 1) || execution.reservation_count == custody_reservation_limit) return false; + claim.id = next++; + execution.reservations[execution.reservation_count++] = claim; + return true; + }; + CustodyRequest request; + request.key = {CustodyKeyKind::Admission, agent.id, agent.next_admission}; + request.kind = kind; + request.production = production; + request.source = source; + request.destination = destination; + for (const auto& material : materials) { + auto& store = storage_by_id(material.storage_id); + const auto stack = stock(store, material.type); + if (material.count == 0 || stack == store.items.end() || stack->id == 0 || + stack->reserved > stack->count || material.count > stack->count - stack->reserved) return false; + if (!add({0, ReservationKind::Item, {OwnerKind::Storage, store.id}, stack->id, + material.type, material.count, 0, store.id})) return false; + request.lines[request.line_count++] = {store.id, material.type, material.count}; + } + if (production && !add({0, ReservationKind::Worksite, {OwnerKind::Production, production}, 0, {}, 1})) return false; + if (source && !add({0, kind == TransferKind::Tending ? ReservationKind::Tending : ReservationKind::Harvest, + {}, 0, {}, 1})) return false; + if (destination) { + auto& store = storage_by_id(destination); + ReservationId backing = 0; + if (production) { + // Every production output replaces claimed input in this exact store. + for (const auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Item && claim.origin_storage == destination) { + backing = claim.id; + break; + } + } + } + if (!backing && store.total_items() + store.reserved_slots >= store.capacity) return false; + if (!add({0, ReservationKind::Capacity, {OwnerKind::Storage, destination}, 0, {}, 1, backing})) return false; + } + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = request; + receipt->result = {CustodyStatus::Accepted, execution.id}; + receipt->result.reservation_count = execution.reservation_count; + for (std::size_t i = 0; i < execution.reservation_count; ++i) receipt->result.reservations[i] = execution.reservations[i].id; + // The caller has already allocated routes and material vectors. No operation + // below can throw; its existing cache increments follow immediately. + agent.execution = execution; + ++agent.next_admission; + ++next_transfer_id_; + next_reservation_id_ = next; + record_custody(std::move(receipt)); + return true; +} + +bool World::pickup_custody(Agent& agent, Storage& source, + const std::vector& materials, bool reserve_output) { + Storage planned_source = source; + Inventory planned_inventory = agent.inventory; + auto execution = *agent.execution; + auto next = next_stack_id_; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, CustodyOperation::Pickup, source.id, 0); + receipt->result = {CustodyStatus::Accepted, execution.id}; + const auto fail = [&](CustodyStatus status) { + receipt->result.status = status; + commit_custody(agent, receipt); + return false; + }; + if (!room(execution.next_operation, 1)) return false; + if (!withdraw_reserved_materials(planned_source, planned_inventory, materials, reserve_output)) return fail(CustodyStatus::Invalid); + for (const auto& stack : source.items) { + const auto remaining = planned_source.item_count(stack.type); + if (remaining == stack.count) continue; + auto id = agent.inventory.stack_id(stack.type); + if (!id) { + if (remaining) { + if (!room(next, 1)) return fail(CustodyStatus::Exhausted); + id = next++; + } else id = stack.id; + } + if (!id) return fail(CustodyStatus::Invalid); + planned_inventory.set_stack_id(stack.type, id); + retarget(execution, {OwnerKind::Storage, source.id}, stack.id, {OwnerKind::Resident, agent.id}, id); + if (execution.kind == TransferKind::Meal) for (auto& claim : execution.reservations) { + if (claim.kind == ReservationKind::Item) claim.origin_storage = 0; + } + } + if (reserve_output) { + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == source.id) claim.backing = 0; + } + } + effects(receipt->result, planned_inventory, {OwnerKind::Resident, agent.id}); + source.items.swap(planned_source.items); + source.reserved_slots = planned_source.reserved_slots; + agent.inventory = planned_inventory; + agent.execution = execution; + next_stack_id_ = next; + commit_custody(agent, receipt); + return true; +} + +bool World::deliver_custody(Agent& agent, Inventory& destination, StockOwner owner) { + auto planned = destination; + auto execution = *agent.execution; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, CustodyOperation::Deliver, 0, 0); + receipt->result = {CustodyStatus::Accepted, execution.id}; + if (!room(execution.next_operation, 1)) return false; + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto type = static_cast(i); + const auto count = agent.inventory.item_count(type); + if (!count) continue; + if (!Void::Numeric::checked_add(planned.item_count(type), count)) { + receipt->result.status = CustodyStatus::Overflow; + commit_custody(agent, receipt); + return false; + } + auto id = planned.stack_id(type); + if (!id) id = agent.inventory.stack_id(type); + planned.add(type, count); + planned.set_stack_id(type, id); + retarget(execution, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(type), owner, id); + } + effects(receipt->result, planned, owner); + destination = planned; + agent.inventory = {}; + agent.execution = execution; + commit_custody(agent, receipt); + return true; +} + +bool World::deposit_custody(Agent& agent, Storage& destination, ItemType type, std::uint32_t count) { + if (!count || count > agent.inventory.item_count(type) || !destination.accepts(type)) return false; + auto planned = destination; + auto inventory = agent.inventory; + auto next = next_stack_id_; + auto execution = *agent.execution; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, execution.kind == TransferKind::Return ? CustodyOperation::Return : CustodyOperation::Deliver, 0, destination.id); + receipt->request.lines[0] = {destination.id, type, count}; + receipt->request.line_count = 1; + receipt->result = {CustodyStatus::Accepted, execution.id}; + if (!room(execution.next_operation, 1)) return false; + auto slots = planned.reserved_slots; + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == destination.id && !claim.backing) { + if (slots < claim.count) return false; + slots -= claim.count; + claim = {}; + } + } + if (planned.total_items() + slots + count > planned.capacity) return false; + auto target = stock(planned, type); + StackId id = 0; + if (target != planned.items.end()) { + const auto amount = Void::Numeric::checked_add(target->count, count); + if (!amount) return false; + target->count = *amount; + id = target->id; + } else { + id = inventory.stack_id(type); + if (count < inventory.item_count(type)) { + if (!room(next, 1)) return false; + id = next++; + } + planned.items.push_back({type, count, 0, id}); + std::sort(planned.items.begin(), planned.items.end(), [](const auto& a, const auto& b) { return a.type < b.type; }); + } + inventory.remove(type, count); + receipt->result.effects[0] = {{OwnerKind::Storage, destination.id}, id, type, planned.item_count(type)}; + receipt->result.effect_count = 1; + receipt->result.terminal = inventory.empty(); + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Item && claim.owner == StockOwner{OwnerKind::Resident, agent.id} && claim.item == type) { + if (claim.count <= count) claim = {}; + else claim.count -= count; + } + } + destination.items.swap(planned.items); + destination.reserved_slots = slots; + agent.inventory = inventory; + agent.execution = execution; + next_stack_id_ = next; + commit_custody(agent, receipt); + return true; +} + +void World::finish_custody(Agent& agent) noexcept { agent.execution.reset(); } + +bool World::legacy_representable() const noexcept { + for (const auto& order : production_orders_) if (order.suspended) return false; + for (const auto& agent : agents_) { + if (agent.state == AgentState::Returning || (agent.execution && agent.execution->kind == TransferKind::Return && agent.state != AgentState::Hauling)) return false; + if ((agent.state == AgentState::Working || agent.state == AgentState::Gathering || agent.state == AgentState::Eating) && agent.work_remaining == 0) return false; + if (agent.production_id == 0 && !agent.inventory.empty()) { + const auto type = agent.inventory.first_item(); + if (agent.state == AgentState::Eating) { + if (type != ItemType::Berries || agent.inventory.item_count(type) != 1) return false; + } else if (agent.state != AgentState::Hauling || agent.storage_id == 0 || + type == ItemType::Plank || type == ItemType::StoneBlock || type == ItemType::Cloth || + agent.inventory.item_count(type) != 1) return false; + for (std::size_t i = 1; i <= item_type_count; ++i) { + if (static_cast(i) != type && agent.inventory.item_count(static_cast(i))) return false; + } + } + } + return true; +} + +CommandStatus World::cancel_production(ProductionId id) { + auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; }); + if (it == production_orders_.end()) return CommandStatus::InvalidTarget; + if (it->state == JobState::Completed || it->suspended) return CommandStatus::Busy; + auto actor = std::find_if(agents_.begin(), agents_.end(), [id](const auto& a) { return a.production_id == id; }); + const bool retain = it->recipe == RecipeId::WeaveCloth || + (it->recipe == RecipeId::BuildBed && (it->bed_stage == BedStage::Bedding || it->bed_stage == BedStage::Pillow)); + if (actor != agents_.end()) { + if (!actor->execution) return CommandStatus::Busy; + auto inventory = actor->inventory; + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + const auto count = it->input.item_count(item); + if (!Void::Numeric::checked_add(inventory.item_count(item), count)) return CommandStatus::Busy; + if (count) { + if (!inventory.stack_id(item)) inventory.set_stack_id(item, it->input.stack_id(item)); + inventory.add(item, count); + } + } + auto receipt = std::const_pointer_cast(prepare_custody(*actor, CustodyOperation::Cancel)); + if (!receipt) return CommandStatus::Busy; + effects(receipt->result, inventory, {OwnerKind::Resident, actor->id}); + receipt->result.terminal = inventory.empty(); + for (auto& claim : actor->execution->reservations) { + if (!claim.id) continue; + if (claim.kind == ReservationKind::Item && claim.owner.kind == OwnerKind::Storage) { + auto& store = storage_by_id(claim.owner.id); + stock(store, claim.item)->reserved -= claim.count; + } else if (claim.kind == ReservationKind::Capacity && !claim.backing) { + storage_by_id(claim.owner.id).reserved_slots -= claim.count; + } + claim = {}; + } + actor->execution->reservation_count = 0; + actor->execution->kind = TransferKind::Return; + actor->execution->production = 0; + actor->execution->source = 0; + actor->execution->destination = 0; + actor->inventory = inventory; + actor->production_id = 0; + actor->storage_id = 0; + actor->work_remaining = 0; + actor->route.clear(); + actor->route_cursor = 0; + actor->haul_route.clear(); + actor->state = inventory.empty() ? AgentState::Idle : AgentState::Returning; + commit_custody(*actor, receipt); + if (inventory.empty()) finish_custody(*actor); + } + if (retain) { + it->input = {}; + it->materials.clear(); + it->delivery_stops.clear(); + it->collected_stops = 0; + it->state = JobState::Available; + it->suspended = true; + } else production_orders_.erase(it); + return CommandStatus::Accepted; +} +CommandStatus World::resume_production(ProductionId id) { + auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; }); + if (it == production_orders_.end()) return CommandStatus::InvalidTarget; + if (!it->suspended || it->state != JobState::Available) return CommandStatus::Busy; + it->suspended = false; + return CommandStatus::Accepted; +} +void World::advance_return(Agent& agent) { + if (agent.route_cursor < agent.route.size()) return; + agent.route.clear(); + agent.route_cursor = 0; + const auto type = agent.inventory.first_item(); + if (type == ItemType::None) { agent.state = AgentState::Idle; finish_custody(agent); return; } + for (auto& store : storages_) { + if (!store.accepts(type) || store.total_items() + store.reserved_slots >= store.capacity) continue; + auto path = assignment_path(agent.position, store.position); + if (!path.reachable) continue; + if (!path.positions.empty()) { + agent.route = std::move(path.positions); + agent.execution->blocked = CustodyStatus::Accepted; + return; + } + const auto free = store.capacity - store.total_items() - store.reserved_slots; + const auto count = static_cast(std::min(free, agent.inventory.item_count(type))); + if (!deposit_custody(agent, store, type, count)) return; + if (agent.inventory.empty()) { agent.state = AgentState::Idle; finish_custody(agent); } + return; + } + agent.execution->blocked = CustodyStatus::NoDestination; +} + +void World::validate_custody() const { + const auto require = [](bool condition) { if (!condition) throw std::runtime_error("inconsistent custody state"); }; + require(next_stack_id_ && next_reservation_id_ && next_transfer_id_); + struct Physical { StockOwner owner; ItemType item; std::uint32_t count; std::uint64_t claimed = 0; }; + std::unordered_map physical; + std::unordered_map> reserved; + std::unordered_map slots; + std::unordered_map workers; + std::array live{}; + const auto add = [&](StockOwner owner, ItemType item, std::uint32_t count, StackId id) { + require((count == 0) == (id == 0)); + if (!count) return; + require(item > ItemType::None && item <= ItemType::Loom && id < next_stack_id_); + require(physical.emplace(id, Physical{owner, item, count}).second); + auto& total = live[static_cast(item) - 1]; + const auto amount = Void::Numeric::checked_add(total, std::uint64_t{count}); + require(amount.has_value()); total = *amount; + }; + const auto add_inventory = [&](const Inventory& inventory, StockOwner owner) { + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + add(owner, item, inventory.item_count(item), inventory.stack_id(item)); + } + }; + for (const auto& store : storages_) { + auto previous = ItemType::None; + for (const auto& stack : store.items) { + require(stack.type > previous && stack.count && store.accepts(stack.type) && stack.reserved <= stack.count); + previous = stack.type; + add({OwnerKind::Storage, store.id}, stack.type, stack.count, stack.id); + } + require(store.total_items() + store.reserved_slots <= store.capacity); + } + for (const auto& actor : agents_) add_inventory(actor.inventory, {OwnerKind::Resident, actor.id}); + for (const auto& order : production_orders_) add_inventory(order.input, {OwnerKind::Production, order.id}); + std::unordered_map actors; + std::unordered_map producers; + for (const auto& actor : agents_) { + require(actors.emplace(actor.id, &actor).second); + if (actor.production_id) require(producers.emplace(actor.production_id, &actor).second); + } + std::set transfers; + std::set reservation_ids; + std::set work_sites; + std::set backed; + for (const auto& actor : agents_) { + require(actor.next_admission != 0 && actor.route_cursor <= actor.route.size()); + if (!actor.execution) { + require(actor.inventory.empty() && actor.production_id == 0 && actor.resource_node_id == 0 && + actor.state != AgentState::Returning && actor.state != AgentState::Hauling && + actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat); + continue; + } + const auto& execution = *actor.execution; + require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second && + execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 && + execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination); + require(execution.production == actor.production_id && execution.source == actor.resource_node_id); + if (execution.kind == TransferKind::Return) { + require(!actor.inventory.empty() && !actor.production_id && !actor.resource_node_id && actor.work_remaining == 0); + require((actor.state == AgentState::Returning && !actor.storage_id) || + (actor.state == AgentState::Hauling && actor.storage_id && find_storage(actor.storage_id) && + execution.destination == actor.storage_id)); + } else if (execution.kind == TransferKind::Meal) { + require(actor.state == AgentState::GoingToEat || actor.state == AgentState::Eating); + require(execution.production == 0 && execution.source == 0 && execution.destination == 0); + } else if (execution.kind == TransferKind::Harvest || execution.kind == TransferKind::Tending) { + require(actor.state == AgentState::Travelling || actor.state == AgentState::Gathering || actor.state == AgentState::Hauling); + require(execution.production == 0 && (execution.kind != TransferKind::Tending || actor.storage_id == 0)); + } else { + require(actor.state == AgentState::Travelling || actor.state == AgentState::Working || + actor.state == AgentState::FetchingMaterials || actor.state == AgentState::Hauling); + if (execution.production) require(find_production(execution.production) != nullptr); + else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item())); + } + for (std::size_t index = 0; index < custody_reservation_limit; ++index) { + const auto& claim = execution.reservations[index]; + if (claim.id == 0) { require(claim == Reservation{}); continue; } + require(index < execution.reservation_count && claim.id < next_reservation_id_ && + reservation_ids.insert(claim.id).second && claim.kind <= ReservationKind::Tending && claim.count); + if (claim.kind == ReservationKind::Item) { + auto entry = physical.find(claim.stack); + require(entry != physical.end() && entry->second.owner == claim.owner && entry->second.item == claim.item); + require(!claim.backing); + if (claim.origin_storage) require(find_storage(claim.origin_storage) != nullptr); + else require(claim.owner.kind == OwnerKind::Resident && + (execution.kind == TransferKind::Meal || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling))); + require(claim.owner.kind != OwnerKind::Resident || claim.owner.id == actor.id); + require(claim.owner.kind != OwnerKind::Production || claim.owner.id == actor.production_id); + auto& amount = entry->second.claimed; + require(claim.count <= entry->second.count - amount); + amount += claim.count; + if (claim.owner.kind == OwnerKind::Storage) { + require(claim.owner.id == claim.origin_storage); + reserved[claim.owner.id][static_cast(claim.item) - 1] += claim.count; + } + } else if (claim.kind == ReservationKind::Capacity) { + require(claim.owner.kind == OwnerKind::Storage && claim.owner.id == execution.destination && + find_storage(claim.owner.id) && !claim.stack && claim.item == ItemType::None && !claim.origin_storage && claim.count == 1); + if (claim.backing) { + const auto input = std::find_if(execution.reservations.begin(), execution.reservations.end(), + [&](const auto& c) { return c.id == claim.backing; }); + require(input != execution.reservations.end() && input->kind == ReservationKind::Item && + input->owner == claim.owner && input->count >= claim.count && backed.insert(claim.backing).second); + } else slots[claim.owner.id] += claim.count; + } else if (claim.kind == ReservationKind::Worksite) { + require(claim.owner == StockOwner{OwnerKind::Production, execution.production} && execution.production && + !claim.stack && claim.item == ItemType::None && claim.count == 1 && !claim.backing && !claim.origin_storage); + require(work_sites.insert(execution.production).second); + } else { + require(claim.owner == StockOwner{} && !claim.stack && claim.item == ItemType::None && + claim.count == 1 && !claim.backing && !claim.origin_storage && execution.source && find_resource_node(execution.source)); + workers[execution.source] += claim.count; + } + } + } + for (const auto& store : storages_) { + require(slots[store.id] == store.reserved_slots); + for (const auto& stack : store.items) require(reserved[store.id][static_cast(stack.type) - 1] == stack.reserved); + } + for (const auto& node : resource_nodes_) require(workers[node.id] == node.reserved_workers); + for (const auto& order : production_orders_) { + require(order.state <= JobState::Completed); + if (order.state == JobState::InProgress) { + require(!order.suspended && work_sites.contains(order.id) && !order.materials.empty()); + const auto found_actor = producers.find(order.id); + require(found_actor != producers.end()); + const auto actor = found_actor->second; + if (delivers_materials(order.recipe) && actor->state == AgentState::Working) { + std::array expected{}; + for (const auto& line : order.materials) { + require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count); + const auto i = static_cast(line.type) - 1; + const auto amount = Void::Numeric::checked_add(expected[i], line.count); + require(amount.has_value()); expected[i] = *amount; + } + for (std::size_t i = 0; i < item_type_count; ++i) require(order.input.item_count(static_cast(i + 1)) == expected[i]); + require(actor->inventory.empty()); + } else require(order.input.empty()); + } else require(order.input.empty() && order.materials.empty() && order.delivery_stops.empty()); + if (order.suspended) require(order.state == JobState::Available && + (order.recipe == RecipeId::WeaveCloth || (order.recipe == RecipeId::BuildBed && + (order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)))); + } + for (std::size_t i = 0; i < item_type_count; ++i) { + const auto& b = item_balances_[i]; + std::uint64_t in = 0, out = live[i]; + for (const auto value : {b.opening, b.grant, b.harvest, b.recipe_output}) { + const auto amount = Void::Numeric::checked_add(in, value); require(amount.has_value()); in = *amount; + } + for (const auto value : {b.recipe_input, b.meal, b.installation, b.demolition}) { + const auto amount = Void::Numeric::checked_add(out, value); require(amount.has_value()); out = *amount; + } + require(in == out); + } + require(custody_receipts_.size() <= custody_receipt_limit && + (custody_receipts_.size() == custody_receipt_limit ? custody_receipt_cursor_ < custody_receipt_limit : custody_receipt_cursor_ == 0)); + std::set> keys; + for (const auto& receipt : custody_receipts_) { + require(static_cast(receipt)); + const auto& request = receipt->request; + const auto& result = receipt->result; + require(request.key.kind <= CustodyKeyKind::Operation && request.key.id && request.key.ordinal && + request.kind <= TransferKind::Return && request.operation <= CustodyOperation::Tend && + request.line_count <= custody_material_limit && request.production < next_production_id_ && + request.destination < next_storage_id_ && keys.emplace(request.key.kind, request.key.id, request.key.ordinal).second); + if (request.key.kind == CustodyKeyKind::Admission) { + require(request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit); + const auto actor = actors.find(request.key.id); + if (actor != actors.end()) require(request.key.ordinal < actor->second->next_admission); + } else require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit); + for (std::size_t i = 0; i < custody_material_limit; ++i) { + const auto& line = request.lines[i]; + if (i >= request.line_count) require(line == CustodyLine{}); + else require(line.storage && line.storage < next_storage_id_ && line.item > ItemType::None && line.item <= ItemType::Loom && line.count); + } + require(result.status <= CustodyStatus::NoDestination && result.transfer && result.transfer < next_transfer_id_ && + result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count); + for (std::size_t i = 0; i < custody_reservation_limit; ++i) require(i < result.reservation_count ? + result.reservations[i] > 0 && result.reservations[i] < next_reservation_id_ : result.reservations[i] == 0); + for (std::size_t i = 0; i < item_type_count; ++i) { + const auto& effect = result.effects[i]; + if (i >= result.effect_count) { require(effect == CustodyEffect{}); continue; } + require(effect.stack && effect.stack < next_stack_id_ && effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.owner.id); + if (effect.owner.kind == OwnerKind::Storage) require(effect.owner.id < next_storage_id_); + else if (effect.owner.kind == OwnerKind::Resident) require(effect.owner.id < next_agent_id_); + else { require(effect.owner.kind == OwnerKind::Production); require(effect.owner.id < next_production_id_); } + } + } +} +} // namespace settlement diff --git a/engine/src/world.cpp b/engine/src/world.cpp index 9b3d106..221d60b 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -58,33 +58,33 @@ std::uint16_t initial_hunger(AgentId id) { } struct Recipe { - std::array ingredients; + std::array ingredients; ItemType output; std::uint32_t ticks; }; const Recipe& recipe_for(RecipeId id) { - static constexpr Recipe saw{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::Plank, 12}; - static constexpr Recipe cut{{ItemStack{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16}; - static constexpr Recipe cabin{{ItemStack{ItemType::Plank, 3}, ItemStack{ItemType::StoneBlock, 2}}, + static constexpr Recipe saw{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::Plank, 12}; + static constexpr Recipe cut{{ItemAmount{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16}; + static constexpr Recipe cabin{{ItemAmount{ItemType::Plank, 3}, ItemAmount{ItemType::StoneBlock, 2}}, ItemType::None, 28}; - static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14}; - static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12}; - static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6}; - static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9}; - static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; - static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10}; - static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}}, + static constexpr Recipe bed{{ItemAmount{ItemType::Plank, 1}, {}}, ItemType::None, 14}; + static constexpr Recipe weave{{ItemAmount{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12}; + static constexpr Recipe floor{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 6}; + static constexpr Recipe wall{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 9}; + static constexpr Recipe door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12}; + static constexpr Recipe cabinet{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 10}; + static constexpr Recipe mining_rack{{ItemAmount{ItemType::Wood, 1}, ItemAmount{ItemType::Stone, 1}}, ItemType::None, 10}; - static constexpr Recipe loom{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; - static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8}; - static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14}; + static constexpr Recipe loom{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12}; + static constexpr Recipe install_door{{ItemAmount{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8}; + static constexpr Recipe craft_door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14}; static constexpr Recipe craft_cabinet{cabinet.ingredients, ItemType::MedicineCabinet, 14}; static constexpr Recipe craft_rack{mining_rack.ingredients, ItemType::MiningRack, 14}; static constexpr Recipe craft_loom{loom.ingredients, ItemType::Loom, 16}; - static constexpr Recipe install_cabinet{{ItemStack{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8}; - static constexpr Recipe install_rack{{ItemStack{ItemType::MiningRack, 1}, {}}, ItemType::None, 8}; - static constexpr Recipe install_loom{{ItemStack{ItemType::Loom, 1}, {}}, ItemType::None, 8}; + static constexpr Recipe install_cabinet{{ItemAmount{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8}; + static constexpr Recipe install_rack{{ItemAmount{ItemType::MiningRack, 1}, {}}, ItemType::None, 8}; + static constexpr Recipe install_loom{{ItemAmount{ItemType::Loom, 1}, {}}, ItemType::None, 8}; switch (id) { case RecipeId::SawPlank: return saw; case RecipeId::CutStoneBlock: return cut; @@ -276,6 +276,7 @@ void Inventory::remove(ItemType type, std::uint32_t count) noexcept { const auto index = static_cast(type); assert(index != 0 && index <= counts_.size() && count <= counts_[index - 1]); counts_[index - 1] -= count; + if (counts_[index - 1] == 0) stack_ids_[index - 1] = 0; } ItemType Inventory::first_item() const noexcept { @@ -497,8 +498,20 @@ void World::stock_storage(std::uint64_t id, ItemType type, std::uint32_t count) } if (count == 0) return; auto stack = stack_position(*storage, type); - if (stack != storage->items.end() && stack->type == type) stack->count += count; - else storage->items.insert(stack, ItemStack{type, count}); + auto& balance = item_balances_[static_cast(type) - 1]; + const auto grant = Void::Numeric::checked_add(balance.grant, std::uint64_t{count}); + if (!grant) throw std::overflow_error("stock grant balance exhausted"); + if (stack != storage->items.end() && stack->type == type) { + const auto amount = Void::Numeric::checked_add(stack->count, count); + if (!amount) throw std::overflow_error("stock quantity exhausted"); + stack->count = *amount; + } else { + const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1}); + if (next_stack_id_ == 0 || !next) throw std::overflow_error("stack identities exhausted"); + storage->items.insert(stack, ItemStack{type, count, 0, next_stack_id_}); + next_stack_id_ = *next; + } + balance.grant = *grant; } void World::enable_hunger() noexcept { @@ -565,12 +578,12 @@ bool World::can_place_room(const RoomPlan& plan) const noexcept { }); } -std::array World::construction_materials(RecipeId recipe, BedBase base) const { +std::array World::construction_materials(RecipeId recipe, BedBase base) const { if (recipe == RecipeId::BuildBed && staged_beds_) { - return {ItemStack{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1}, - ItemStack{ItemType::Cloth, 2}}; + return {ItemAmount{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1}, + ItemAmount{ItemType::Cloth, 2}}; } - return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array{}; + return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array{}; } RecipeId World::room_construction_recipe(RecipeId part) const noexcept { @@ -584,8 +597,8 @@ RecipeId World::room_construction_recipe(RecipeId part) const noexcept { return part; } -std::array World::carpentry_materials(RecipeId recipe) const { - return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array{}; +std::array World::carpentry_materials(RecipeId recipe) const { + return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array{}; } std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations, @@ -746,6 +759,14 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest // Demand is evaluated against the post-removal inventory, without // losing stock or issuing any order until the entire batch fits. if (!reserve_production(total)) return CommandStatus::Busy; + auto balances = item_balances_; + for (const auto& stack : storage->items) { + auto& sink = balances[static_cast(stack.type) - 1].demolition; + const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{stack.count}); + if (!amount) return CommandStatus::Busy; + sink = *amount; + } + item_balances_ = balances; storages_.erase(storage); for (std::size_t i = 0; i < replacements.size(); ++i) { for (std::size_t j = 0; j < replacements[i]; ++j) { @@ -1305,6 +1326,7 @@ void World::assign_resource_tasks(ResourceFocus focus) { } if (node.needs_tending()) { + if (!admit_custody(agent, TransferKind::Tending, 0, node.id, 0, {})) break; ++resource_nodes_[node_index].reserved_workers; --untended_sites; agent.resource_node_id = node.id; @@ -1341,8 +1363,9 @@ void World::assign_resource_tasks(ResourceFocus focus) { continue; } - ++resource_nodes_[node_index].reserved_workers; Storage& storage = storages_[storage_index]; + if (!admit_custody(agent, TransferKind::Harvest, 0, node.id, storage.id, {})) break; + ++resource_nodes_[node_index].reserved_workers; ++storage.reserved_slots; if (!has_space(storage)) { if (storage.kind == StorageKind::Pantry) --open_pantry_count; @@ -1369,7 +1392,7 @@ void World::assign_production_tasks(bool weaving) { })) return; for (std::size_t index = 0; index < production_orders_.size(); ++index) { ProductionOrder& order = production_orders_[index]; - if (order.state != JobState::Available || (order.recipe == RecipeId::WeaveCloth) != weaving) continue; + if (order.suspended || order.state != JobState::Available || (order.recipe == RecipeId::WeaveCloth) != weaving) continue; const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(), [&order](const ProductionOrder& other) { @@ -1387,7 +1410,7 @@ void World::assign_production_tasks(bool weaving) { std::vector storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown); std::vector materials; bool supplied = true; - for (const ItemStack& ingredient : recipe.ingredients) { + for (const ItemAmount& ingredient : recipe.ingredients) { std::uint32_t remaining = ingredient.count; for (std::size_t storage_index = 0; storage_index < storages_.size() && remaining > 0; ++storage_index) { @@ -1438,10 +1461,13 @@ void World::assign_production_tasks(bool weaving) { if (agent.state != AgentState::Idle || !eligible) continue; auto path = assignment_path(agent.position, destination); if (!path.reachable) continue; + std::vector haul_route; if (carpentry) { - agent.haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions; + haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions; } - + const auto output_storage = recipe.output == ItemType::None ? 0 : materials.front().storage_id; + if (!admit_custody(agent, TransferKind::Production, order.id, 0, output_storage, materials)) break; + if (carpentry) agent.haul_route = std::move(haul_route); for (const auto& material : materials) { stack_position(storage_by_id(material.storage_id), material.type)->reserved += material.count; } @@ -1459,19 +1485,6 @@ void World::assign_production_tasks(bool weaving) { } } -namespace { - -void take_reserved_material(Storage& storage, const MaterialReservation& material) { - auto stack = stack_position(storage, material.type); - assert(stack != storage.items.end() && stack->type == material.type); - assert(stack->reserved >= material.count && stack->count >= stack->reserved); - stack->reserved -= material.count; - stack->count -= material.count; - if (stack->count == 0) storage.items.erase(stack); -} - -} // namespace - void World::assign_meals() { for (Agent& agent : agents_) { if (agent.hunger < max_hunger) ++agent.hunger; @@ -1497,6 +1510,8 @@ void World::assign_meals() { auto path = assignment_path(agent.position, storage.position); if (!path.reachable) continue; + const std::vector meal{MaterialReservation{storage.id, ItemType::Berries, 1}}; + if (!admit_custody(agent, TransferKind::Meal, 0, 0, 0, meal)) break; auto stack = stack_position(storage, ItemType::Berries); ++stack->reserved; agent.storage_id = storage.id; @@ -1512,9 +1527,10 @@ void World::assign_meals() { void World::finish_meal_step(Agent& agent) { if (agent.state == AgentState::GoingToEat) { if (agent.route_cursor != agent.route.size()) return; - const std::array meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}}; - if (!withdraw_reserved_materials(storage_by_id(agent.storage_id), agent.inventory, meal)) { - throw std::logic_error("invalid reserved meal pickup"); + const std::vector meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}}; + if (!pickup_custody(agent, storage_by_id(agent.storage_id), meal, false)) { + if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved meal pickup"); + return; } agent.storage_id = 0; agent.route.clear(); @@ -1523,8 +1539,19 @@ void World::finish_meal_step(Agent& agent) { agent.state = AgentState::Eating; return; } - if (--agent.work_remaining != 0) return; + if (agent.work_remaining > 0) --agent.work_remaining; + if (agent.work_remaining != 0) return; + auto& sink = item_balances_[static_cast(ItemType::Berries) - 1].meal; + const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{1}); + const auto meals = Void::Numeric::checked_add(meals_eaten_, std::uint64_t{1}); + auto receipt = prepare_custody(agent, CustodyOperation::Eat, + amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow); + if (!receipt) return; + commit_custody(agent, receipt); + if (!amount || !meals) return; + sink = *amount; agent.inventory.remove(ItemType::Berries); + finish_custody(agent); agent.hunger = 0; agent.state = AgentState::Idle; ++meals_eaten_; @@ -1585,9 +1612,7 @@ void World::finish_rest_step(Agent& agent) { void World::advance_construction_delivery(Agent& agent) { ProductionOrder& order = production_by_id(agent.production_id); if (order.collected_stops == order.delivery_stops.size()) { - for (const auto& material : order.materials) { - agent.inventory.remove(material.type, material.count); - } + if (!deliver_custody(agent, order.input, {OwnerKind::Production, order.id})) return; order.delivery_stops.clear(); order.collected_stops = 0; agent.state = AgentState::Working; @@ -1602,8 +1627,9 @@ void World::advance_construction_delivery(Agent& agent) { auto& stop = order.delivery_stops[order.collected_stops]; const bool reserve_output = is_carpentry_recipe(order.recipe) && stop.storage_id == order.materials.front().storage_id; - if (!withdraw_reserved_materials(storage_by_id(stop.storage_id), agent.inventory, order.materials, reserve_output)) { - throw std::logic_error("invalid reserved construction pickup"); + if (!pickup_custody(agent, storage_by_id(stop.storage_id), order.materials, reserve_output)) { + if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved construction pickup"); + return; } ++order.collected_stops; agent.route = std::move(stop.route_to_next); @@ -1614,26 +1640,83 @@ void World::advance_construction_delivery(Agent& agent) { void World::finish_production(Agent& agent) { ProductionOrder& order = production_by_id(agent.production_id); const Recipe recipe = recipe_for(order); - assert(!order.materials.empty()); - if (is_carpentry_recipe(order.recipe)) { - agent.inventory.add(recipe.output); + auto balances = item_balances_; + auto input = order.input; + auto inventory = agent.inventory; + auto next = next_stack_id_; + std::vector stores; + const bool delivered = delivers_materials(order.recipe); + const bool carpentry = is_carpentry_recipe(order.recipe); + auto status = CustodyStatus::Accepted; + for (const auto& material : order.materials) { + auto& balance = balances[static_cast(material.type) - 1]; + auto& sink = recipe.output == ItemType::None ? balance.installation : balance.recipe_input; + const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{material.count}); + if (!amount) { status = CustodyStatus::Overflow; break; } + sink = *amount; + if (delivered) { + if (input.item_count(material.type) < material.count) { status = CustodyStatus::Invalid; break; } + input.remove(material.type, material.count); + } else { + auto store = std::find_if(stores.begin(), stores.end(), [&](const auto& s) { return s.id == material.storage_id; }); + if (store == stores.end()) { stores.push_back(storage_by_id(material.storage_id)); store = std::prev(stores.end()); } + const auto stack = stack_position(*store, material.type); + if (stack == store->items.end() || stack->type != material.type || stack->reserved < material.count || stack->count < material.count) { + status = CustodyStatus::Invalid; break; + } + stack->count -= material.count; + stack->reserved -= material.count; + if (stack->count == 0) store->items.erase(stack); + } + } + StackId output_id = 0; + if (status == CustodyStatus::Accepted && recipe.output != ItemType::None) { + auto& balance = balances[static_cast(recipe.output) - 1].recipe_output; + const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1}); + if (!amount) status = CustodyStatus::Overflow; + else balance = *amount; + if (carpentry) { + if (next == 0 || next == std::numeric_limits::max()) status = CustodyStatus::Exhausted; + else { output_id = next++; inventory.add(recipe.output); inventory.set_stack_id(recipe.output, output_id); } + } else { + auto& store = stores.front(); + auto stack = stack_position(store, recipe.output); + if (stack != store.items.end() && stack->type == recipe.output) { ++stack->count; output_id = stack->id; } + else if (next == 0 || next == std::numeric_limits::max()) status = CustodyStatus::Exhausted; + else { output_id = next++; store.items.insert(stack, {recipe.output, 1, 0, output_id}); } + } + } + auto receipt = std::const_pointer_cast(prepare_custody(agent, CustodyOperation::Complete, status)); + if (!receipt) return; + if (status == CustodyStatus::Accepted) { + receipt->result.terminal = !carpentry; + if (output_id) { + receipt->result.effects[0] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} : + StockOwner{OwnerKind::Storage, stores.front().id}, output_id, recipe.output, + carpentry ? inventory.item_count(recipe.output) : stores.front().item_count(recipe.output)}; + receipt->result.effect_count = 1; + } + } + commit_custody(agent, receipt); + if (status != CustodyStatus::Accepted) return; + for (auto& store : stores) storage_by_id(store.id).items.swap(store.items); + item_balances_ = balances; + next_stack_id_ = next; + order.input = input; + agent.inventory = inventory; + for (auto& claim : agent.execution->reservations) if (claim.kind != ReservationKind::Capacity) claim = {}; + if (carpentry) { agent.storage_id = order.materials.front().storage_id; agent.route = std::move(agent.haul_route); agent.haul_route.clear(); agent.route_cursor = 0; agent.production_id = 0; + agent.execution->production = 0; agent.state = AgentState::Hauling; order.materials.clear(); order.state = JobState::Completed; return; } - if (recipe.output != ItemType::None) { - for (const auto& material : order.materials) { - take_reserved_material(storage_by_id(material.storage_id), material); - } - // Crafting replaces one raw item with one finished item in the same store. - storage_by_id(order.materials.front().storage_id).add_item(recipe.output); - } order.materials.clear(); if (order.recipe == RecipeId::BuildBed && (order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) { @@ -1644,13 +1727,12 @@ void World::finish_production(Agent& agent) { order.state = JobState::Available; } else if (order.recipe == RecipeId::WeaveCloth) { order.state = JobState::Available; - } else { - order.state = JobState::Completed; - } + } else order.state = JobState::Completed; agent.production_id = 0; agent.state = AgentState::Idle; agent.route.clear(); agent.route_cursor = 0; + finish_custody(agent); } void World::grow_sites() { @@ -1707,7 +1789,7 @@ void World::step(TickProfile* profile) { Agent& agent = agents_[index]; if ((agent.state == AgentState::Travelling || agent.state == AgentState::Hauling || agent.state == AgentState::FetchingMaterials || agent.state == AgentState::GoingToEat || - agent.state == AgentState::GoingToSleep) && + agent.state == AgentState::GoingToSleep || agent.state == AgentState::Returning) && agent.route_cursor < agent.route.size()) { agent.position = agent.route[agent.route_cursor++]; if (agent.state == AgentState::Travelling && agent.route_cursor == agent.route.size()) { @@ -1762,6 +1844,7 @@ void World::step(TickProfile* profile) { } for (Agent& agent : agents_) { + if (agent.state == AgentState::Returning) { advance_return(agent); continue; } if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) { finish_meal_step(agent); continue; @@ -1783,7 +1866,13 @@ void World::step(TickProfile* profile) { 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); + const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site)); + auto receipt = prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow); + if (!receipt) continue; + commit_custody(agent, receipt); + if (!growth) continue; + node.growth_at = *growth; + finish_custody(agent); --node.reserved_workers; agent.resource_node_id = 0; agent.state = AgentState::Idle; @@ -1791,9 +1880,26 @@ void World::step(TickProfile* profile) { agent.route_cursor = 0; continue; } - if (node.quantity > 0) --node.quantity; - if (node.reserved_workers > 0) --node.reserved_workers; + auto& balance = item_balances_[static_cast(node.type) - 1].harvest; + const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1}); + const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1}); + auto receipt = std::const_pointer_cast(prepare_custody(agent, CustodyOperation::Harvest, + !next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted)); + if (!receipt) continue; + if (next && amount) { + receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, next_stack_id_, node.type, 1}; + receipt->result.effect_count = 1; + } + commit_custody(agent, receipt); + if (!next || !amount) continue; + --node.quantity; + --node.reserved_workers; + balance = *amount; agent.inventory.add(node.type); + agent.inventory.set_stack_id(node.type, next_stack_id_); + next_stack_id_ = *next; + for (auto& claim : agent.execution->reservations) if (claim.kind == ReservationKind::Harvest) claim = {}; + agent.execution->source = 0; agent.resource_node_id = 0; agent.route = std::move(agent.haul_route); agent.haul_route.clear(); @@ -1806,9 +1912,8 @@ void World::step(TickProfile* profile) { 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); + if (!deposit_custody(agent, storage, cargo, 1)) continue; + finish_custody(agent); agent.storage_id = 0; agent.state = AgentState::Idle; agent.route.clear(); diff --git a/tests/custody_tests.cpp b/tests/custody_tests.cpp new file mode 100644 index 0000000..b0f0d75 --- /dev/null +++ b/tests/custody_tests.cpp @@ -0,0 +1,187 @@ +#include "settlement/core/world.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace settlement; +using Void::Testing::Test; +void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); } +void ticks(World& world, int count) { for (int i = 0; i < count; ++i) { world.step(); world.validate_custody(); } } +std::unique_ptr cabin(std::uint32_t stock = 3) { + auto w = std::make_unique(7, 32, 32, 1, ExecutionMode::SerialReference); + auto storage = w->add_storage({3, 3}, 50); + w->stock_storage(storage, ItemType::Plank, stock); + w->stock_storage(storage, ItemType::StoneBlock, 2); + (void)w->spawn_agent({1, 3}); + w->queue_production({16, 3}, RecipeId::BuildCabin); + return w; +} +struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::Suite { + [[= Void::Testing::tag("custody")]] Test ownership_delivery_and_consumption(); + [[= Void::Testing::tag("custody")]] Test cancel_site_returns_all_types(); + [[= Void::Testing::tag("custody")]] Test split_merge_and_snapshot(); + [[= Void::Testing::tag("custody")]] Test exact_receipt_and_conflict(); + [[= Void::Testing::tag("custody")]] Test original_colony_continuous_balance(); + [[= Void::Testing::tag("custody")]] Test five_sources(); + [[= Void::Testing::tag("custody")]] Test blocked_return_retains_every_item(); + [[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume(); + [[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction(); + [[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance(); + [[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics(); +}; +Test CustodyTests::ownership_delivery_and_consumption() { + auto w = cabin(); + const auto plank = w->storages()[0].items[0].id; + ticks(*w, 2); + require(w->agents()[0].inventory.stack_id(ItemType::Plank) == plank, "whole pickup changed ID"); + for (int i = 0; i < 20 && w->agents()[0].state != AgentState::Working; ++i) ticks(*w, 1); + require(w->production_orders()[0].input.stack_id(ItemType::Plank) == plank, "site lost ID"); + require(w->production_orders()[0].input.item_count(ItemType::Plank) == 3, "site lost physical count"); + ticks(*w, 40); + require(w->production_orders()[0].state == JobState::Completed, "construction incomplete"); + require(w->item_balances()[2].installation == 3, "installation sink missing"); +} +Test CustodyTests::cancel_site_returns_all_types() { + auto w = cabin(); + ticks(*w, 16); + require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); + w->validate_custody(); + require(w->agents()[0].state == AgentState::Returning && !w->legacy_representable(), "cancel phase lost"); + ticks(*w, 40); + require(w->agents()[0].inventory.empty() && w->storages()[0].item_count(ItemType::Plank) == 3 && + w->storages()[0].item_count(ItemType::StoneBlock) == 2, "return lost cargo"); +} +Test CustodyTests::split_merge_and_snapshot() { + auto w = cabin(5); + const auto original = w->storages()[0].items[0].id; + auto snapshot = w->capture(); + ticks(*w, 2); + require(w->storages()[0].items[0].id == original && w->agents()[0].inventory.stack_id(ItemType::Plank) != original, "split identity wrong"); + require(snapshot->storages()[0].item_count(ItemType::Plank) == 5 && snapshot->custody_receipts().empty(), "snapshot mutated"); + require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); + ticks(*w, 10); + require(w->storages()[0].items[0].id == original && w->storages()[0].item_count(ItemType::Plank) == 5, "merge identity wrong"); +} +Test CustodyTests::exact_receipt_and_conflict() { + auto w = cabin(); ticks(*w, 1); + auto receipt = *w->custody_receipts().front(); + require(w->custody_request(receipt.request) == receipt.result, "exact retry differed"); + ++receipt.request.destination; + require(w->custody_request(receipt.request).status == CustodyStatus::Conflict, "changed retry accepted"); + receipt.request.key.ordinal += 100; + require(w->custody_request(receipt.request).status == CustodyStatus::Future, "future retry accepted"); + ticks(*w, 60); +} +Test CustodyTests::original_colony_continuous_balance() { + auto w = make_first_colony(1, BedConstructionMode::Staged, ExecutionMode::SerialReference); + w->validate_custody(); + ticks(*w, 1000); +} +Test CustodyTests::five_sources() { + auto w = std::make_unique(7, 32, 32, 1, ExecutionMode::SerialReference); + for (int i = 0; i < 5; ++i) { + const auto store = w->add_storage({3 + i, 3}, 10); + w->stock_storage(store, i < 3 ? ItemType::Plank : ItemType::StoneBlock, 1); + } + (void)w->spawn_agent({1, 3}); w->queue_production({16, 3}, RecipeId::BuildCabin); + ticks(*w, 1); + require(w->custody_receipts()[0]->request.line_count == 5, "admission omitted sources"); + ticks(*w, 80); + require(w->production_orders()[0].state == JobState::Completed, "five-source cabin incomplete"); +} + +Test CustodyTests::blocked_return_retains_every_item() { + auto w = cabin(); ticks(*w, 16); + require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); + auto& store = const_cast(w->storages()[0]); store.capacity = 1; + ticks(*w, 40); + require(w->agents()[0].state == AgentState::Returning && w->agents()[0].execution && + w->agents()[0].execution->blocked == CustodyStatus::NoDestination, "blocked return lost execution"); + require(w->agents()[0].inventory.item_count(ItemType::Plank) == 2 && + w->agents()[0].inventory.item_count(ItemType::StoneBlock) == 2, "partial return lost items"); + auto id = w->add_storage({4, 3}, 20); + ticks(*w, 20); + require(w->agents()[0].inventory.empty() && w->find_storage(id)->total_items() == 4, "unblocked return incomplete"); +} +Test CustodyTests::suspended_bed_and_loom_resume() { + World w(9, 20, 20, 1, ExecutionMode::SerialReference); + const auto store = w.add_storage({2, 2}, 30); + w.stock_storage(store, ItemType::Wood, 4); w.stock_storage(store, ItemType::Cloth, 2); + const auto actor = w.spawn_agent({2, 2}); (void)actor; w.start_scenario({8, 8}); + require(w.apply_command({1, 1, CommandKind::PlaceBed, {4, 2}}).status == CommandStatus::Accepted, "bed placement refused"); + const auto id = w.production_orders()[0].id; + for (int i = 0; i < 80 && w.find_production(id)->bed_stage == BedStage::Foundation; ++i) ticks(w, 1); + require(w.find_production(id)->bed_stage == BedStage::Bedding, "bed foundation absent"); + require(w.cancel_production(id) == CommandStatus::Accepted && w.find_production(id)->suspended, "partial bed not suspended"); + ticks(w, 20); require(!w.legacy_representable(), "suspended bed projected"); + require(w.resume_production(id) == CommandStatus::Accepted, "resume refused"); + ticks(w, 100); require(w.find_production(id)->state == JobState::Completed, "bed resumed wrong stage"); + require(w.item_balances()[0].installation == 1 && w.item_balances()[5].installation == 2, "bed installed twice"); + require(w.cancel_production(id) == CommandStatus::Busy, "completed bed canceled"); + w.queue_production({6, 2}, RecipeId::WeaveCloth); const auto loom = w.production_orders().back().id; + require(w.cancel_production(loom) == CommandStatus::Accepted && w.find_production(loom)->suspended, "loom not retained"); + w.stock_storage(store, ItemType::Flax, 1); + require(w.resume_production(loom) == CommandStatus::Accepted, "loom resume refused"); + ticks(w, 60); require(w.find_storage(store)->item_count(ItemType::Cloth) == 1, "loom failed after resume"); +} +Test CustodyTests::admission_exhaustion_and_receipt_eviction() { + auto w = cabin(); + auto& actor = const_cast(w->agents()[0]); actor.next_admission = std::numeric_limits::max(); + ticks(*w, 2); + require(!actor.execution && w->custody_receipts().empty() && w->storages()[0].items[0].reserved == 0, "exhausted admission mutated stock"); + World loom(1, 16, 16, 1, ExecutionMode::SerialReference); + const auto store = loom.add_storage({2, 2}, 4000); loom.stock_storage(store, ItemType::Flax, 3000); + (void)loom.spawn_agent({3, 2}); loom.queue_production({3, 2}, RecipeId::WeaveCloth); + loom.step(); auto first = *loom.custody_receipts()[0]; auto snapshot = loom.capture(); + for (int i = 0; i < 26000; ++i) loom.step(); + loom.validate_custody(); + require(loom.custody_receipts().size() == custody_receipt_limit && + loom.custody_request(first.request).status == CustodyStatus::Stale, "evicted admission not stale"); + require(snapshot->custody_receipts()[0]->request == first.request && snapshot->custody_receipts()[0]->result == first.result, + "retained snapshot receipt mutated"); + for (const auto& receipt : loom.custody_receipts()) require(loom.custody_request(receipt->request) == receipt->result, "retained replay differed"); +} +Test CustodyTests::recipes_meals_and_harvest_balance() { + World w(1, 20, 20, 1, ExecutionMode::SerialReference); + const auto store = w.add_storage({2, 2}, 100); + const auto pantry = w.add_storage({2, 3}, 20, StorageKind::Pantry); + w.stock_storage(store, ItemType::Wood, 10); w.stock_storage(store, ItemType::Stone, 3); + w.stock_storage(pantry, ItemType::Berries, 4); + (void)w.spawn_agent({2, 2}); (void)w.add_resource_node({3, 3}, ItemType::Wood, 5); + w.queue_production({4, 2}, RecipeId::SawPlank); w.queue_production({5, 2}, RecipeId::CutStoneBlock); + w.enable_hunger(); ticks(w, 300); + require(w.meals_eaten() > 0 && w.item_balances()[0].harvest == 5 && w.item_balances()[0].recipe_input == 1 && + w.item_balances()[2].recipe_output == 1 && w.item_balances()[3].recipe_output == 1, "recipe/source/sink path omitted"); +} +Test CustodyTests::snapshot_metrics() { + for (bool full : {false, true}) { + World w(1, 512, 512, 1, ExecutionMode::SerialReference); + if (full) { + auto store = w.add_storage({1, 1}, 4000); w.stock_storage(store, ItemType::Flax, 3000); + (void)w.spawn_agent({2, 1}); w.queue_production({2, 1}, RecipeId::WeaveCloth); + for (int i = 0; i < 26000; ++i) w.step(); + } + while (w.agents().size() < 500) (void)w.spawn_agent({1, 1}); + for (int i = 0; i < 1000; ++i) { + auto store = w.add_storage({i % 500, i / 500 + 5}, 1000); + for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast(j) != ItemType::Berries) + w.stock_storage(store, static_cast(j), 1); + } + while (w.production_orders().size() < 2000) w.queue_production({3, 3}, RecipeId::SawPlank); + w.validate_custody(); + std::vector samples; + for (int i = 0; i < 101; ++i) { + const auto begin = std::chrono::steady_clock::now(); auto snapshot = w.capture(); + samples.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); + } + std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes); + std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size() + << " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << '\n'; + } +} +} From b5f75d3c136ca087ee78b6649ccfa63090b28d4f Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:13:59 +0300 Subject: [PATCH 04/10] Cancel and resume durable production orders from the Works menu --- CMakeLists.txt | 8 + app/viewer_win32.cpp | 160 +++++++++- docs/agent-workflow/tasks/S04-02.md | 50 ++++ .../settlement/core/command_dispatcher.hpp | 13 +- engine/src/command_dispatcher.cpp | 6 + tests/production_commands_tests.cpp | 269 +++++++++++++++++ tests/production_controls_tests.cpp | 275 ++++++++++++++++++ 7 files changed, 779 insertions(+), 2 deletions(-) create mode 100644 docs/agent-workflow/tasks/S04-02.md create mode 100644 tests/production_commands_tests.cpp create mode 100644 tests/production_controls_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e6f933..d0da71d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -125,6 +125,7 @@ if(BUILD_TESTING) tests/executor_tests.cpp tests/identity_tests.cpp tests/production_identity_tests.cpp + tests/production_commands_tests.cpp tests/profile_tests.cpp tests/quantity_transaction_tests.cpp tests/replay_tests.cpp @@ -145,4 +146,11 @@ if(BUILD_TESTING) add_executable(settlement_viewer_tests tests/viewer_session_tests.cpp tests/test_main.cpp) target_link_libraries(settlement_viewer_tests PRIVATE settlement_client Void::Testing) add_test(NAME settlement_viewer_tests COMMAND settlement_viewer_tests) + + add_executable(settlement_production_controls_tests + tests/production_controls_tests.cpp tests/test_main.cpp app/d3d_scene_win32.cpp app/house_icons.rc) + target_link_libraries(settlement_production_controls_tests PRIVATE settlement_client settlement_lan + Void::Testing user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler) + add_test(NAME settlement_production_controls_tests COMMAND settlement_production_controls_tests) + set_tests_properties(settlement_production_controls_tests PROPERTIES RUN_SERIAL TRUE TIMEOUT 60) endif() diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index d4d0f32..402e1dc 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -72,6 +72,7 @@ constexpr int furnished_room_tool_id = 1045; constexpr int house_list_back_id = 1046; constexpr int carpenter_menu_id = 1047; constexpr int craft_door_id = 1048; +constexpr int manage_orders_id = 1049; constexpr int first_furniture_craft_id = 1143; constexpr int first_work_choice_id = 1050; constexpr int resident_list_id = 1060; @@ -140,7 +141,7 @@ LanState displayed_lan_state = LanState::Offline; std::uint64_t lan_generation = 1; const auto local_worker_count = std::clamp( std::thread::hardware_concurrency(), settlement::min_worker_count, 8); -enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room }; +enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room, ManageOrders }; PlacementMode placement_mode = PlacementMode::None; enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, Houses, Carpenter, None }; WorkPanel work_panel = WorkPanel::None; @@ -832,6 +833,15 @@ bool can_give_orders() { return world && session && (lan->is_guest() ? lan->state() == LanState::GuestConnected : session->can_submit()); } +bool can_manage_orders() { + return !showing_title && can_give_orders() && !lan->is_guest() && !session->guest() && + !session->changing_world(); +} + +bool manageable_order(const settlement::ProductionOrder& order) { + return order.suspended || order.state != settlement::JobState::Completed; +} + void update_roster_details() { const auto* resident = selected_agent(); const auto role = resident ? profession_name(resident->profession) : L""; @@ -1422,6 +1432,9 @@ bool valid_edit_cell(settlement::GridPosition cell) { case PlacementMode::Move: return move_source ? world->can_place_storage(cell) : world->object_status(cell, true) == CommandStatus::Accepted; case PlacementMode::Demolish: return world->object_status(cell, false) == CommandStatus::Accepted; + case PlacementMode::ManageOrders: + return can_manage_orders() && std::any_of(world->production_orders().begin(), world->production_orders().end(), + [cell](const auto& order) { return order.position == cell && manageable_order(order); }); case PlacementMode::Building: return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell); case PlacementMode::Room: @@ -1676,6 +1689,11 @@ void complete_command(std::uint64_t id, const settlement::SessionPayload& payloa } if (accepted) { placement_message = L"Команда выполнена."; + if (std::holds_alternative(payload)) { + placement_message = L"Заказ отменён. Установленные части сохранены; груз вернут жители."; + } else if (std::holds_alternative(payload)) { + placement_message = L"Работа по заказу возобновлена."; + } if (const auto* command = std::get_if(&payload)) { if (command->kind == settlement::CommandKind::MoveObject && move_source == command->cell) { move_source.reset(); @@ -1687,6 +1705,13 @@ void complete_command(std::uint64_t id, const settlement::SessionPayload& payloa } } } else { + if (std::holds_alternative(payload) || + std::holds_alternative(payload)) { + placement_message = status == settlement::CommandStatus::Busy + ? L"Заказ пока нельзя изменить. Дождитесь возврата материалов или повторите позже." + : L"Заказ отклонён: работа уже завершена, удалена или изменилась."; + return; + } placement_message = status == settlement::CommandStatus::Busy ? L"Объект занят. Дождитесь окончания работы или сна." : L"Команда отклонена. Проверьте клетку и доступ к ней. Чертёж сохранён."; @@ -1779,8 +1804,115 @@ void pump_session(HWND window) { invalidate_scene(window); } +const wchar_t* production_name(settlement::RecipeId recipe) { + using settlement::RecipeId; + switch (recipe) { + case RecipeId::SawPlank: return L"Распилить доску"; + case RecipeId::CutStoneBlock: return L"Вытесать каменный блок"; + case RecipeId::BuildCabin: return L"Построить домик"; + case RecipeId::BuildBed: return L"Спальное место"; + case RecipeId::WeaveCloth: return L"Ткать ткань"; + case RecipeId::BuildFloor: return L"Пол"; + case RecipeId::BuildWall: return L"Стена"; + case RecipeId::BuildDoorAlongX: + case RecipeId::BuildDoorAlongY: return L"Построить дверь"; + case RecipeId::BuildMedicineCabinet: return L"Построить аптечный шкаф"; + case RecipeId::BuildMiningRack: return L"Построить стойку шахтёра"; + case RecipeId::BuildLoom: return L"Построить ткацкий станок"; + case RecipeId::InstallDoorAlongX: + case RecipeId::InstallDoorAlongY: return L"Установить дверь"; + case RecipeId::CraftWoodenDoor: return L"Изготовить дверь"; + case RecipeId::InstallMedicineCabinet: return L"Установить аптечный шкаф"; + case RecipeId::InstallMiningRack: return L"Установить стойку шахтёра"; + case RecipeId::InstallLoom: return L"Установить ткацкий станок"; + case RecipeId::CraftMedicineCabinet: return L"Изготовить аптечный шкаф"; + case RecipeId::CraftMiningRack: return L"Изготовить стойку шахтёра"; + case RecipeId::CraftLoom: return L"Изготовить ткацкий станок"; + } + return L"Производственный заказ"; +} + +void manage_orders_at_cell(HWND window, settlement::GridPosition cell) { + if (!can_manage_orders()) return; + // Popup menus pump nested messages. Keep every displayed order alive and + // fence both replacement admission and completed world/session replacement. + const auto opening = session->runtime().latest(); + const auto generation = session->generation(); + const auto* opening_session = session.get(); + const auto network_generation = lan_generation; + const auto* connection = lan.get(); + const auto current_context = [&] { + return can_manage_orders() && session.get() == opening_session && session->generation() == generation && + session->runtime().latest()->identity == opening->identity && network_generation == lan_generation && + connection == lan.get() && placement_mode == PlacementMode::ManageOrders; + }; + constexpr std::size_t page_size = 16; + constexpr UINT previous_page = 100; + constexpr UINT next_page = 101; + std::size_t offset = 0; + POINT cursor{}; + GetCursorPos(&cursor); + for (;;) { + std::array choices{}; + std::size_t count = 0, skipped = 0; + bool more = false; + for (const auto& order : opening->world->production_orders()) { + if (order.position != cell || !manageable_order(order)) continue; + if (skipped++ < offset) continue; + if (count == page_size) { more = true; break; } + choices[count++] = ℴ + } + if (count == 0) { + placement_message = L"На этой клетке нет незавершённых или приостановленных заказов."; + return; + } + const auto menu = CreatePopupMenu(); + if (!menu) return; + for (std::size_t index = 0; index < count; ++index) { + const auto& order = *choices[index]; + const auto title = std::wstring(order.suspended ? L"Возобновить: " : L"Отменить: ") + + production_name(order.recipe) + L" №" + std::to_wstring(order.id) + L" [" + + std::to_wstring(cell.x + 1) + L", " + std::to_wstring(cell.y + 1) + L"]"; + AppendMenuW(menu, MF_STRING, index + 1, title.c_str()); + } + if (offset != 0 || more) AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); + if (offset != 0) AppendMenuW(menu, MF_STRING, previous_page, L"← Предыдущие заказы"); + if (more) AppendMenuW(menu, MF_STRING, next_page, L"Следующие заказы →"); + const auto selected = static_cast(TrackPopupMenu(menu, TPM_RETURNCMD | TPM_NONOTIFY | + TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, window, nullptr)); + DestroyMenu(menu); + if (!current_context()) { + placement_message = L"Поселение или режим изменились. Выберите заказ заново."; + return; + } + if (selected == previous_page) { offset -= page_size; continue; } + if (selected == next_page) { offset += page_size; continue; } + if (selected == 0 || selected > count) return; + const auto& chosen = *choices[selected - 1]; + const auto current = session->runtime().latest(); + const auto* order = current->world->find_production(chosen.id); + if (!order || order->position != chosen.position || order->recipe != chosen.recipe || + order->suspended != chosen.suspended || !manageable_order(*order)) { + placement_message = L"Заказ изменился. Выберите его заново."; + return; + } + const settlement::SessionPayload payload = chosen.suspended + ? settlement::SessionPayload{settlement::ResumeProductionPayload{chosen.id}} + : settlement::SessionPayload{settlement::CancelProductionPayload{chosen.id}}; + placement_message = enqueue_command(payload) ? L"Изменение заказа ожидает подтверждения…" + : L"Очередь занята. Попробуйте ещё раз."; + return; + } +} + void edit_at_cell(HWND window, settlement::GridPosition cell) { if (!can_give_orders()) return; + if (placement_mode == PlacementMode::ManageOrders) { + manage_orders_at_cell(window, cell); + update_status(); + invalidate_scene(window); + return; + } const auto held_world = world; const auto generation = session->generation(); const auto installed_session = session->runtime().latest()->identity.session; @@ -1850,6 +1982,7 @@ HMENU create_work_menu() { role_choices[static_cast(id - farmer_menu_id + 1)].title); } AppendMenuW(menu, MF_STRING, carpenter_menu_id, L"Плотник"); + if (can_manage_orders()) AppendMenuW(menu, MF_STRING, manage_orders_id, L"Управление заказами…"); AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC"); return menu; @@ -2069,6 +2202,24 @@ std::wstring resident_details() { profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%"; if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой"; else if (resident->state == settlement::AgentState::Eating) text += L" Ест"; + else if (resident->state == settlement::AgentState::Returning) { + text += L" Возвращает материалы"; + if (resident->execution) { + switch (resident->execution->blocked) { + case settlement::CustodyStatus::NoDestination: + text += L": нет доступного склада с местом"; break; + case settlement::CustodyStatus::Capacity: + text += L": на складе недостаточно места"; break; + case settlement::CustodyStatus::Busy: + text += L": ожидает освобождения склада"; break; + case settlement::CustodyStatus::Exhausted: + case settlement::CustodyStatus::Overflow: + text += L": достигнут предел учёта запасов"; break; + case settlement::CustodyStatus::Accepted: break; + default: text += L": ожидает возможности сдать груз"; break; + } + } + } else if (world->find_production(resident->production_id) != nullptr && settlement::is_carpentry_recipe(world->find_production(resident->production_id)->recipe)) { text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" : @@ -2192,6 +2343,8 @@ void draw_world(HDC dc, int width, int height) { L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; + } else if (placement_mode == PlacementMode::ManageOrders) { + hint = L"Щёлкните по площадке или станку. Выберите заказ, чтобы отменить или возобновить работу."; } else if (placement_mode == PlacementMode::Room) { if (room_draft_move) { hint = L"Щёлкните по новой площадке. R поворачивает дом, правый щелчок отменяет перенос."; @@ -2622,6 +2775,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp if (world) show_resident_roster(window); return 0; } + if (LOWORD(wparam) == manage_orders_id && HIWORD(wparam) == BN_CLICKED) { + if (can_manage_orders()) set_placement_mode(window, PlacementMode::ManageOrders); + SetFocus(window); + return 0; + } if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == build_blueprint_id) { submit_blueprint(window); SetFocus(window); diff --git a/docs/agent-workflow/tasks/S04-02.md b/docs/agent-workflow/tasks/S04-02.md new file mode 100644 index 0000000..9effdde --- /dev/null +++ b/docs/agent-workflow/tasks/S04-02.md @@ -0,0 +1,50 @@ +# Cancel and resume production work by durable order ID + +Task ID: S04-02 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Isolated s04 e5d01a4 contains 5a64a27 user-facing viewer + private S06 header 4f42488. World::cancel_production/resume_production(ProductionId)->CommandStatus, AgentState::Returning, Agent.execution and ProductionOrder.suspended are frozen declarations; peer S06 implements actual effects. Legacy LAN11 supports only PlayerCommand and local LegacyCabinPayload has existing runtime path. Existing Работы menu is a real entry and current UI correlates exact SessionPayload after receipt. + +## 2. Objective and deliverables +Connect modern cancellation and resumption to the authenticated command dispatcher and an actual localized host/offline Win32 control aimed at durable ProductionId. Make receipt/status/return reason visible and verify retry, rejection, stale selection and real returned cargo with S06. + +## 3. Scope and non-goals +Only S04 modern session variants and minimal Win32 normal orders action for present job lifecycle. Keep historical PlayerCommand, CommandKind, LAN11, ordinary demolition/move and S19 profiles unchanged. S06 owns World and all ledger/cargo transitions; S15 owns codecs. S17 owns presentation in a sibling branch. + +## 4. Files to inspect +Read command_dispatcher.hpp/.cpp, simulation_runtime.hpp and exact receipt semantics, app/viewer_win32.cpp enqueue_command/complete_command/edit_at_cell/Работы menu & agent status, app/viewer_session and existing modal epoch guards, tests/session/runtime and viewer. Inspect frozen custody.hpp/world.hpp and docs/plan/custody.md. Study exposed work order/actual stages and S04 docs. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/command_dispatcher.hpp; engine/src/command_dispatcher.cpp; app/viewer_win32.cpp narrow order-action menu/handler and returned cargo display only; tests/session_tests.cpp and NEW tests/production_commands_tests.cpp if needed; NEW tests/production_controls_tests.cpp for the real Win32 controls; CMakeLists.txt only owned test entries; docs/plan/systems/S04.md +Isolated s04 only; other workers have independent worktrees. Never revert changes, edit S06/S16/S17 or switch shared Serena. No Git/remote ops/children. + +## 6. Implementation or investigation approach +Add distinct typed CancelProductionPayload{ProductionId production} and ResumeProductionPayload; equality/payload conflict checks go through existing SessionPayload variant/ledger. Admit/validate trusted client/world/session/city/request before World methods and pass domain status through existing DispatchReceipt; successful mutations advance revision once, refused result retained. No legacy sequence side effect for these new modern payloads or untyped std::get fallthrough. Existing cabin branch remains exact. + +## 7. Interfaces and data contracts +User must be able to cancel/resume through normal game UI. Prefer a single order-management action in existing Работы menu with a map target using current user-visible names/coordinates and explicit Отменить/Возобновить choices; if multiple eligible orders share a cell, bind each displayed choice to its actual durable ProductionId. Don't use vector index as command. Host/offline only: hide/disable for legacy guest before enqueue. Pin opening snapshot, recheck world+session incarnation and presentation generation after any modal interaction and validate target still appropriate; never send an old selection into a loaded different colony. Bound menu/list size while retaining access to all choices. Use existing asynchronous queue and return receipt so UI only reports completion after commit. Returning resident with no eligible space shows why it waits; avoid reporting unearned cancel/return, preserve existing move/demolish behaviors. + +## 8. Dependencies and integration +Depends on S06 core, not yet linked initially; root provides actual local commits before final build. S17 in another branch may touch drawing; keep changes narrow and alert parent about status text fields so final packet integration preserves them. Separate S16 tests for incompatible legacy guests, no new wire variant. + +## 9. Edge cases security and performance +Resource/capacity refusal returns repeatable domain status with stable world and actual request identities. Prior receipt still valid after target removed. Wrong-world/city/session and same request differing ProductionId/variant are fenced/Conflict. Early command/UI must not synthesize arbitrary orders or try to resolve IDs from stale sessions. + +## 10. Acceptance criteria +1. Tests use actual dispatcher/runtime with live order/cargo; same request accepted/refused twice, different payload same key Conflict, wrong world/session/city rejected, accepted cancellation/return and resume retained site progress once. 2. UI test actual action/receipt, bound durable ID and cancel on stale dialog without enqueuing new-world action, legacy guest cannot submit. 3. Default legacy command numbering/cabin/old raw & LAN tests unchanged. 4. Native Windows x64 cross-build + loops, full integrated CTest when dependencies provided. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s04-cancel-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Compile independent translation units/tests as feasible before S06 implementation lands. Use actual focused session/order tests and CTest -V, isolated Windows/Wine UI smoke under /tmp, logs s04-cancel-*. git diff --check. Native hardware not assumed. + +## 12. Constraints and stop conditions +Never implement duplicate inventory mutation/ID logic or mock final acceptance. If cyclic API, incorrect capacity/epoch or unavailable real core, report exact required seam and continue independent adapter/tests. Two failed same-cause attempts escalate. No Git/remote/children. + +## 13. Authorization and decisions +User authorizes all milestones. F8/root approve explicit modern cancel/resume of retained partially built bed or existing loom, stable identities and old Busy constraints. Root integrates/publishes once end-to-end safe. + +## 14. Return format +Return S04-02 READY or PARTIAL, actual normal command/UI entry, test outcomes/real dependency status, logs and native limitations. + +The Win32 executable may include the viewer implementation in its test translation unit using its real window and menu handlers. Drive modal selection via an actual window timer, including a world replacement while a choice is open. Cover the correct durable selection, receipt, stale selection and guest action fence. Reuse existing test/build conventions and keep this target independent of the S17 frame smoke. Register it with CTest and report actual Wine results after S06/S15 link. diff --git a/engine/include/settlement/core/command_dispatcher.hpp b/engine/include/settlement/core/command_dispatcher.hpp index fd83cd6..0e734e9 100644 --- a/engine/include/settlement/core/command_dispatcher.hpp +++ b/engine/include/settlement/core/command_dispatcher.hpp @@ -44,7 +44,18 @@ struct LegacyCabinPayload { bool operator==(const LegacyCabinPayload&) const = default; }; -using SessionPayload = std::variant; +struct CancelProductionPayload { + ProductionId production = 0; + bool operator==(const CancelProductionPayload&) const = default; +}; + +struct ResumeProductionPayload { + ProductionId production = 0; + bool operator==(const ResumeProductionPayload&) const = default; +}; + +using SessionPayload = std::variant; struct CommandEnvelope { std::uint32_t version = command_envelope_version; diff --git a/engine/src/command_dispatcher.cpp b/engine/src/command_dispatcher.cpp index 73c8561..dd54cfa 100644 --- a/engine/src/command_dispatcher.cpp +++ b/engine/src/command_dispatcher.cpp @@ -74,6 +74,12 @@ CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const } if (client.player != colony_host) return CommandStatus::Unauthorized; + if (const auto* payload = std::get_if(&command.payload)) { + return world.cancel_production(payload->production); + } + if (const auto* payload = std::get_if(&command.payload)) { + return world.resume_production(payload->production); + } if (world.scenario_active()) return CommandStatus::Unavailable; const auto& payload = std::get(command.payload); try { diff --git a/tests/production_commands_tests.cpp b/tests/production_commands_tests.cpp new file mode 100644 index 0000000..6bb24eb --- /dev/null +++ b/tests/production_commands_tests.cpp @@ -0,0 +1,269 @@ +#include "settlement/core/simulation_runtime.hpp" + +#include + +#include +#include +#include +#include + +namespace { +using namespace settlement; +using Void::Testing::Test; +using namespace std::chrono_literals; +constexpr TrustedClient host{colony_host}; + +void require(bool condition, const char* message = "production command invariant failed") { + if (!condition) throw std::runtime_error(message); +} + +SessionIdentity identity() { + SessionIdentity result; + result.world.bytes.back() = 61; + result.session.bytes.back() = 62; + return result; +} + +CommandEnvelope envelope(std::uint64_t request, SessionPayload payload, SessionIdentity context = identity()) { + return {command_envelope_version, context.world, context.session, context.city, request, std::move(payload)}; +} + +DispatchReceipt send(World& world, CommandDispatcher& dispatcher, SessionPayload payload) { + return dispatcher.dispatch(world, host, envelope(dispatcher.next_request(host), std::move(payload))); +} + +void accepted(const DispatchReceipt& receipt) { + require(receipt.status == DispatchStatus::Completed && receipt.command_status == CommandStatus::Accepted, + "production command was not accepted"); +} + +template +void step_until(World& world, Predicate done) { + for (int tick = 0; tick < 600 && !done(); ++tick) world.step(); + require(done(), "actual work did not reach the required phase"); + world.validate_custody(); +} + +std::unique_ptr cabin() { + auto world = std::make_unique(43, 32, 32, 1, ExecutionMode::SerialReference); + const auto store = world->add_storage({3, 3}, 20); + world->stock_storage(store, ItemType::Plank, 3); + world->stock_storage(store, ItemType::StoneBlock, 2); + static_cast(world->spawn_agent({1, 3})); + world->queue_production({14, 3}, RecipeId::BuildCabin); + return world; +} + +RuntimeResult finish(RuntimeSubmission submission) { + require(submission.admission == RuntimeAdmission::Accepted); + require(submission.completion.wait_for(5s) == std::future_status::ready); + auto result = submission.completion.get(); + require(result.outcome == RuntimeOutcome::Completed && result.receipt.has_value()); + return result; +} + +struct [[= Void::Testing::name("ProductionCommandsTests")]] ProductionCommandsTests + : Void::Testing::Suite { + [[= Void::Testing::tag("production-command")]] Test exact_results_and_conflicts_use_durable_ids(); + [[= Void::Testing::tag("production-command")]] Test context_and_guest_denials_leave_orders_untouched(); + [[= Void::Testing::tag("production-command")]] Test cancel_at_each_phase_returns_actual_cargo_once(); + [[= Void::Testing::tag("production-command")]] Test full_storage_preserves_return_until_space_exists(); + [[= Void::Testing::tag("production-command")]] Test resume_keeps_partial_bed_and_installed_loom_identity(); + [[= Void::Testing::tag("production-command")]] Test runtime_publishes_and_retains_modern_receipts(); +}; + +Test ProductionCommandsTests::exact_results_and_conflicts_use_durable_ids() { + World world(43, 32, 32, 1, ExecutionMode::SerialReference); + world.queue_production({8, 8}, RecipeId::BuildCabin); + world.queue_production({8, 8}, RecipeId::BuildCabin); + const auto first = world.production_orders().front().id; + const auto second = world.production_orders().back().id; + CommandDispatcher dispatcher(identity()); + const auto cancel = envelope(1, CancelProductionPayload{first}); + const auto result = dispatcher.dispatch(world, host, cancel); + accepted(result); + require(result.revision == 1 && world.find_production(first) == nullptr && world.find_production(second), + "cancel selected by vector position or cell instead of exact durable id"); + require(dispatcher.dispatch(world, host, cancel) == result && dispatcher.lookup(host, cancel) == result); + for (const SessionPayload changed : {SessionPayload{CancelProductionPayload{second}}, + SessionPayload{ResumeProductionPayload{first}}, SessionPayload{CommandPayload{}}, + SessionPayload{LegacyCabinPayload{{8, 8}, {2, 2}, {3, 2}}}}) { + require(dispatcher.dispatch(world, host, envelope(1, changed)).status == DispatchStatus::Conflict, + "same request accepted a different id or payload variant"); + } + const auto refused = envelope(2, ResumeProductionPayload{first}); + const auto rejection = dispatcher.dispatch(world, host, refused); + require(rejection.status == DispatchStatus::Completed && rejection.command_status == CommandStatus::InvalidTarget && + rejection.revision == 1 && dispatcher.dispatch(world, host, refused) == rejection); + const auto zero = envelope(3, CancelProductionPayload{0}); + const auto zero_result = dispatcher.dispatch(world, host, zero); + require(zero_result.command_status == CommandStatus::InvalidTarget && dispatcher.dispatch(world, host, zero) == zero_result); + accepted(send(world, dispatcher, CancelProductionPayload{second})); + require(world.production_orders().empty() && dispatcher.revision() == 2 && + world.next_command_sequence(1) == 1 && world.next_command_sequence(2) == 1, + "modern command changed legacy accepted-command numbering"); + require(dispatcher.dispatch(world, host, cancel) == result, "removed target lost the original retained receipt"); + world.validate_custody(); +} + +Test ProductionCommandsTests::context_and_guest_denials_leave_orders_untouched() { + World world(43, 32, 32, 1, ExecutionMode::SerialReference); + world.queue_production({8, 8}, RecipeId::BuildCabin); + const auto id = world.production_orders().front().id; + CommandDispatcher dispatcher(identity()); + auto command = envelope(1, CancelProductionPayload{id}); + command.world.bytes.back() ^= 1; + require(dispatcher.dispatch(world, host, command).status == DispatchStatus::WrongWorld); + command = envelope(1, CancelProductionPayload{id}); + command.session.bytes.back() ^= 1; + require(dispatcher.dispatch(world, host, command).status == DispatchStatus::StaleSession); + command = envelope(1, CancelProductionPayload{id}); + require(dispatcher.dispatch(world, {0}, command).status == DispatchStatus::UnauthorizedClient); + require(dispatcher.dispatch(world, {3}, command).status == DispatchStatus::UnauthorizedClient); + require(dispatcher.receipt_count(host) == 0 && dispatcher.revision() == 0 && world.find_production(id)); + const auto guest_result = dispatcher.dispatch(world, {2}, command); + require(guest_result.command_status == CommandStatus::Unauthorized && + dispatcher.dispatch(world, {2}, command) == guest_result); + const auto guest_resume = envelope(2, ResumeProductionPayload{id}); + require(dispatcher.dispatch(world, {2}, guest_resume).command_status == CommandStatus::Unauthorized); + command.city = 2; + const auto denied = dispatcher.dispatch(world, host, command); + require(denied.command_status == CommandStatus::Unauthorized && denied.revision == 0 && + dispatcher.dispatch(world, host, command) == denied && world.find_production(id)); + command.city = 1; + require(dispatcher.dispatch(world, host, command).status == DispatchStatus::Conflict); + command.request = 2; + accepted(dispatcher.dispatch(world, host, command)); + command.world.bytes.back() ^= 1; + require(dispatcher.dispatch(world, host, command).status == DispatchStatus::WrongWorld, + "cached receipt bypassed world identity check"); + require(world.next_command_sequence(1) == 1 && world.next_command_sequence(2) == 1); +} + +Test ProductionCommandsTests::cancel_at_each_phase_returns_actual_cargo_once() { + for (int phase = 0; phase < 3; ++phase) { + auto world = cabin(); + const auto id = world->production_orders().front().id; + const auto storage = world->storages().front().id; + step_until(*world, [&] { + const auto& agent = world->agents().front(); + return phase == 0 ? agent.state == AgentState::FetchingMaterials && agent.inventory.empty() : + phase == 1 ? !agent.inventory.empty() : agent.state == AgentState::Working; + }); + CommandDispatcher dispatcher(identity()); + const auto sequence = world->next_command_sequence(1); + require(send(*world, dispatcher, CommandPayload{CommandKind::DemolishObject, {3, 3}}).command_status == CommandStatus::Busy); + require(send(*world, dispatcher, CommandPayload{CommandKind::MoveObject, {3, 3}, 0, {4, 3}}).command_status == CommandStatus::Busy); + const auto cancel = envelope(dispatcher.next_request(host), CancelProductionPayload{id}); + const auto result = dispatcher.dispatch(*world, host, cancel); + accepted(result); + if (phase != 0) require(world->agents().front().state == AgentState::Returning && + !world->agents().front().inventory.empty(), "cancellation erased carried or worksite input"); + require(dispatcher.dispatch(*world, host, cancel) == result); + step_until(*world, [&] { return world->agents().front().state != AgentState::Returning; }); + require(world->find_storage(storage)->item_count(ItemType::Plank) == 3 && + world->find_storage(storage)->item_count(ItemType::StoneBlock) == 2 && + world->agents().front().inventory.empty() && world->find_production(id) == nullptr, + "cancelled material was lost, duplicated or left assigned"); + for (int tick = 0; tick < 4; ++tick) world->step(); + require(dispatcher.dispatch(*world, host, cancel) == result && world->next_command_sequence(1) == sequence && + world->find_storage(storage)->item_count(ItemType::Plank) == 3 && + world->find_storage(storage)->item_count(ItemType::StoneBlock) == 2); + world->validate_custody(); + } +} + +Test ProductionCommandsTests::full_storage_preserves_return_until_space_exists() { + auto world = cabin(); + const auto id = world->production_orders().front().id; + const auto original = world->storages().front().id; + step_until(*world, [&] { return !world->agents().front().inventory.empty(); }); + world->stock_storage(original, ItemType::Wood, 20); + CommandDispatcher dispatcher(identity()); + accepted(send(*world, dispatcher, CancelProductionPayload{id})); + for (int tick = 0; tick < 10; ++tick) world->step(); + const auto& waiting = world->agents().front(); + require(waiting.state == AgentState::Returning && waiting.execution && + (waiting.execution->blocked == CustodyStatus::NoDestination || waiting.execution->blocked == CustodyStatus::Capacity) && + waiting.inventory.item_count(ItemType::Plank) == 3 && waiting.inventory.item_count(ItemType::StoneBlock) == 2, + "full storage did not preserve the cargo and meaningful blocked reason"); + const auto destination = world->add_storage({4, 3}, 5); + step_until(*world, [&] { return world->agents().front().state != AgentState::Returning; }); + require(world->find_storage(destination)->item_count(ItemType::Plank) == 3 && + world->find_storage(destination)->item_count(ItemType::StoneBlock) == 2 && + world->find_storage(original)->item_count(ItemType::Wood) == 20); +} + +Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identity() { + for (const bool bed : {true, false}) { + World world(43, 32, 32, 1, ExecutionMode::SerialReference); + world.start_scenario({2, 2}); + const auto storage = world.add_storage({3, 3}, 20); + world.stock_storage(storage, ItemType::Wood, 2); + static_cast(world.spawn_agent({1, 3})); + CommandDispatcher dispatcher(identity()); + if (bed) { + accepted(send(world, dispatcher, CommandPayload{CommandKind::PlaceBed, {9, 3}})); + } else { + world.queue_production({9, 3}, RecipeId::BuildLoom); + } + const auto id = world.production_orders().back().id; + step_until(world, [&] { + const auto* order = world.find_production(id); + return bed ? order->bed_stage == BedStage::Bedding : order->recipe == RecipeId::WeaveCloth; + }); + const auto before_cancel = world.capture(); + const auto stage = world.find_production(id)->bed_stage; + const auto sequence = world.next_command_sequence(1); + accepted(send(world, dispatcher, CancelProductionPayload{id})); + require(world.find_production(id) && world.find_production(id)->suspended && + world.find_production(id)->bed_stage == stage && !world.can_place_storage({9, 3}), + "cancel removed installed progress or its occupied site"); + for (int tick = 0; tick < 5; ++tick) world.step(); + const auto resume = envelope(dispatcher.next_request(host), ResumeProductionPayload{id}); + const auto resumed = dispatcher.dispatch(world, host, resume); + accepted(resumed); + require(world.find_production(id) && !world.find_production(id)->suspended && + world.find_production(id)->bed_stage == stage && dispatcher.dispatch(world, host, resume) == resumed && + world.next_command_sequence(1) == sequence && !before_cancel->find_production(id)->suspended); + world.stock_storage(storage, bed ? ItemType::Cloth : ItemType::Flax, 2); + step_until(world, [&] { return bed ? world.find_production(id)->state == JobState::Completed : + world.find_storage(storage)->item_count(ItemType::Cloth) > 0; }); + require(world.find_storage(storage)->item_count(ItemType::Wood) == (bed ? 1U : 0U), + "resume charged for an already installed stage twice"); + if (bed) { + const auto refused = send(world, dispatcher, CancelProductionPayload{id}); + require(refused.command_status == CommandStatus::InvalidTarget, + "completed final bed accepted cancel"); + } + } +} + +Test ProductionCommandsTests::runtime_publishes_and_retains_modern_receipts() { + auto world = cabin(); + step_until(*world, [&] { return !world->agents().front().inventory.empty(); }); + const auto id = world->production_orders().front().id; + const auto rules = default_rules_manifest(); + require(rules.has_value()); + SimulationRuntime runtime(WorldCheckpoint{std::move(world), identity().world, 1, *rules}, {.ticking = false}); + const auto opening = runtime.latest(); + const auto cancel = envelope(1, CancelProductionPayload{id}, opening->identity); + const auto first = finish(runtime.try_submit(host, cancel)); + accepted(*first.receipt); + require(first.snapshot->world->find_production(id) == nullptr && + first.snapshot->world->agents().front().state == AgentState::Returning && + opening->world->find_production(id) && opening->world->agents().front().state != AgentState::Returning, + "modern runtime effect was not published with independent old snapshot"); + const auto repeat = finish(runtime.try_submit(host, cancel)); + require(repeat.receipt == first.receipt && runtime.lookup(host, cancel) == first.receipt && + repeat.snapshot->revision == first.snapshot->revision && repeat.snapshot->next_requests[0] == 2); + const auto changed = finish(runtime.try_submit(host, envelope(1, ResumeProductionPayload{id}, opening->identity))); + require(changed.receipt->status == DispatchStatus::Conflict); + const auto refusal = envelope(2, ResumeProductionPayload{id}, opening->identity); + const auto denied = finish(runtime.try_submit(host, refusal)); + require(denied.receipt->command_status == CommandStatus::InvalidTarget && + finish(runtime.try_submit(host, refusal)).receipt == denied.receipt && + runtime.latest()->world->next_command_sequence(1) == 1 && runtime.view().state == RuntimeState::Running); + runtime.latest()->world->validate_custody(); +} +} // namespace diff --git a/tests/production_controls_tests.cpp b/tests/production_controls_tests.cpp new file mode 100644 index 0000000..0623007 --- /dev/null +++ b/tests/production_controls_tests.cpp @@ -0,0 +1,275 @@ +// Exercise the real private Win32 controls and modal handlers in their own +// executable, without adding test hooks to the shipping UI or wire protocol. +#include "../app/viewer_win32.cpp" +#include +#include +#include + +namespace production_controls { +using namespace settlement; +using Void::Testing::Test; +using namespace std::chrono_literals; + +void require(bool condition, const char* message = "production controls invariant failed") { + if (!condition) throw std::runtime_error(message); +} + +constexpr UINT_PTR drive_timer = 904; +struct MenuStep { UINT command; std::function before_select; }; +std::vector steps; +std::vector> observed_menus; +HMENU active_menu = nullptr; +std::string driver_error; +unsigned timer_attempts = 0; + +void key(std::vector& input, WORD code) { + INPUT down{}; + down.type = INPUT_KEYBOARD; + down.ki.wVk = code; + input.push_back(down); + down.ki.dwFlags = KEYEVENTF_KEYUP; + input.push_back(down); +} + +LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + if (message == WM_INITMENUPOPUP) { + active_menu = reinterpret_cast(wparam); + std::vector labels; + for (int index = 0; index < GetMenuItemCount(active_menu); ++index) { + wchar_t label[512]{}; + GetMenuStringW(active_menu, static_cast(index), label, 512, MF_BYPOSITION); + labels.emplace_back(label); + } + observed_menus.push_back(std::move(labels)); + } + if (message == WM_TIMER && wparam == drive_timer) { + if (++timer_attempts > 100) { + driver_error = "real popup did not accept the scripted input"; + KillTimer(window, drive_timer); + EndMenu(); + return 0; + } + if (!active_menu || steps.empty()) return 0; + const auto menu = std::exchange(active_menu, nullptr); + auto step = std::move(steps.front()); + steps.erase(steps.begin()); + int target = -1; + for (int index = 0; index < GetMenuItemCount(menu); ++index) { + if (GetMenuItemID(menu, index) == step.command) { target = index; break; } + } + if (target < 0) { + driver_error = "expected action absent from actual popup"; + EndMenu(); + return 0; + } + if (step.before_select) step.before_select(); + std::vector input; + key(input, VK_HOME); + for (int index = 0; index < target; ++index) { + if ((GetMenuState(menu, static_cast(index), MF_BYPOSITION) & MF_SEPARATOR) == 0) key(input, VK_DOWN); + } + key(input, VK_RETURN); + if (SendInput(static_cast(input.size()), input.data(), sizeof(INPUT)) != input.size()) { + driver_error = "SendInput failed for actual popup"; + EndMenu(); + } + return 0; + } + return window_proc(window, message, wparam, lparam); +} + +struct Window { + HWND handle = nullptr; + std::filesystem::path user_data; + std::wstring old_user_data; + explicit Window(std::unique_ptr initial) { + const auto uuid = Void::Uuid::try_v4(); + require(uuid.has_value()); + user_data = std::filesystem::temp_directory_path() / ("settlement-order-controls-" + uuid->to_string()); + require(std::filesystem::create_directory(user_data)); + wchar_t old[32768]{}; + const auto size = GetEnvironmentVariableW(L"LOCALAPPDATA", old, 32768); + old_user_data.assign(old, size < 32768 ? size : 0); + require(SetEnvironmentVariableW(L"LOCALAPPDATA", user_data.c_str())); + auto rules = default_rules_manifest(); + require(rules.has_value()); + session = std::make_unique( + WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 1); + world = session->world(); + showing_title = true; + has_session = true; + lan = std::make_unique(); + displayed_lan_state = LanState::Offline; + placement_mode = PlacementMode::None; + placement_message.clear(); + steps.clear(); + observed_menus.clear(); + active_menu = nullptr; + driver_error.clear(); + timer_attempts = 0; + INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; + require(InitCommonControlsEx(&controls)); + WNDCLASSW type{}; + type.lpfnWndProc = test_window_proc; + type.hInstance = GetModuleHandleW(nullptr); + type.lpszClassName = L"SettlementProductionControlsTest"; + type.hCursor = LoadCursorW(nullptr, IDC_ARROW); + require(RegisterClassW(&type) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS); + handle = CreateWindowExW(0, type.lpszClassName, L"Production controls test", + WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 32, 32, 1120, 752, nullptr, nullptr, type.hInstance, nullptr); + require(handle != nullptr); + show_title_screen(handle, false); + file_dialog_active = true; // Freeze ticks while exercising UI receipt delivery. + KillTimer(handle, timer_id); + session->set_ticking(false); + ShowWindow(handle, SW_SHOW); + UpdateWindow(handle); + SetForegroundWindow(handle); + } + ~Window() { + if (handle) DestroyWindow(handle); + session.reset(); + world.reset(); + file_dialog_active = false; + MSG message{}; + while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {} + SetEnvironmentVariableW(L"LOCALAPPDATA", old_user_data.empty() ? nullptr : old_user_data.c_str()); + std::error_code error; + std::filesystem::remove_all(user_data, error); + } + void menu(std::vector actions, const std::function& open) { + steps = std::move(actions); + require(SetTimer(handle, drive_timer, 50, nullptr) != 0); + open(); + KillTimer(handle, drive_timer); + require(driver_error.empty(), driver_error.c_str()); + require(steps.empty(), "not all popup pages were reachable"); + } + void pump_until(const std::function& done) { + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (!done()) { + SendMessageW(handle, WM_TIMER, timer_id, 0); + require(std::chrono::steady_clock::now() < deadline, "UI receipt/replacement did not finish"); + std::this_thread::yield(); + } + } + void activate_tool() { + menu({{manage_orders_id, {}}}, [&] { SendMessageW(work_list_button, BM_CLICK, 0, 0); }); + // The normal work menu posts WM_COMMAND after closing its popup. + MSG message{}; + while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&message); + DispatchMessageW(&message); + } + require(placement_mode == PlacementMode::ManageOrders, "Работы menu did not activate order management"); + } +}; + +std::unique_ptr orders(unsigned count = 2) { + auto result = std::make_unique(43, 32, 32, 1, ExecutionMode::SerialReference); + for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::BuildCabin); + return result; +} + +struct [[= Void::Testing::name("ProductionControlsTests")]] ProductionControlsTests + : Void::Testing::Suite { + [[= Void::Testing::tag("production-controls")]] Test real_work_menu_selects_exact_id_and_waits_for_receipt(); + [[= Void::Testing::tag("production-controls")]] Test every_order_remains_accessible_across_popup_pages(); + [[= Void::Testing::tag("production-controls")]] Test replacement_during_popup_cannot_cancel_in_new_world(); + [[= Void::Testing::tag("production-controls")]] Test legacy_guest_has_no_action_or_modern_submission(); + [[= Void::Testing::tag("production-controls")]] Test returning_resident_explains_wait_for_storage(); +}; + +Test ProductionControlsTests::real_work_menu_selects_exact_id_and_waits_for_receipt() { + Window fixture(orders()); + const auto first = world->production_orders().front().id; + const auto second = world->production_orders().back().id; + fixture.activate_tool(); + fixture.menu({{2, {}}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); + require(world->find_production(second) && world->find_production(first) && + placement_message.find(L"ожидает подтверждения") != std::wstring::npos, + "UI forged success before a committed receipt"); + require(observed_menus.back().at(1).find(L"Отменить: Построить домик №" + std::to_wstring(second)) != std::wstring::npos && + observed_menus.back().at(1).find(L"[9, 9]") != std::wstring::npos, + "actual popup lost the order name, durable id or user-facing position"); + fixture.pump_until([&] { return !world->find_production(second); }); + require(world->find_production(first) && placement_message.find(L"Заказ отменён") != std::wstring::npos && + session->runtime().latest()->next_requests[0] == 2 && world->next_command_sequence(1) == 1); +} + +Test ProductionControlsTests::every_order_remains_accessible_across_popup_pages() { + Window fixture(orders(35)); + const auto last = world->production_orders().back().id; + fixture.activate_tool(); + fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); + fixture.pump_until([&] { return !world->find_production(last); }); + require(world->production_orders().size() == 34 && world->production_orders().front().id == 1); + for (const auto& page : observed_menus) require(page.size() <= 19, "popup page exceeded its bounded display size"); +} + +Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_world() { + for (const bool complete_replacement : {false, true}) { + Window fixture(orders()); + const auto opening = session->runtime().latest(); + fixture.activate_tool(); + fixture.menu({{1, [&] { + session->new_colony(); + if (complete_replacement) { + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (session->changing_world()) { + static_cast(session->poll()); + require(std::chrono::steady_clock::now() < deadline); + std::this_thread::yield(); + } + world = session->world(); + } + }}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); + fixture.pump_until([&] { return !session->changing_world(); }); + const auto current = session->runtime().latest(); + require(current->identity != opening->identity && current->next_requests[0] == 1 && + current->world->next_command_sequence(1) == 1, + "stale popup enqueued a production command into the new session"); + require(opening->world->production_orders().size() == 2, "modal selection invalidated pinned snapshot"); + } +} + +Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() { + Window fixture(orders()); + session->enter_guest(); + lan->join("127.0.0.1", "000000", 1); + require(lan->is_guest() && session->guest()); + const auto before = session->runtime().latest(); + const auto menu = create_work_menu(); + require(menu != nullptr && GetMenuState(menu, manage_orders_id, MF_BYCOMMAND) == static_cast(-1), + "legacy guest saw the modern management action"); + DestroyMenu(menu); + SendMessageW(fixture.handle, WM_COMMAND, manage_orders_id, 0); + require(placement_mode != PlacementMode::ManageOrders && !can_manage_orders()); + placement_mode = PlacementMode::ManageOrders; + edit_at_cell(fixture.handle, {8, 8}); + require(!enqueue_command(CancelProductionPayload{1}) && !enqueue_command(ResumeProductionPayload{1}) && + session->runtime().latest() == before && guest_intents.empty(), + "legacy guest admitted a modern order payload"); +} + +Test ProductionControlsTests::returning_resident_explains_wait_for_storage() { + auto initial = orders(1); + const auto storage = initial->add_storage({3, 3}, 5); + initial->stock_storage(storage, ItemType::Plank, 3); + initial->stock_storage(storage, ItemType::StoneBlock, 2); + const auto resident = initial->spawn_agent({1, 3}); + for (int tick = 0; tick < 100 && initial->agents().front().inventory.empty(); ++tick) initial->step(); + require(!initial->agents().front().inventory.empty()); + initial->stock_storage(storage, ItemType::Wood, 5); + require(initial->cancel_production(initial->production_orders().front().id) == CommandStatus::Accepted); + for (int tick = 0; tick < 5; ++tick) initial->step(); + Window fixture(std::move(initial)); + selected_resident = resident; + const auto details = resident_details(); + require(details.find(L"Возвращает материалы") != std::wstring::npos && + (details.find(L"нет доступного склада с местом") != std::wstring::npos || + details.find(L"на складе недостаточно места") != std::wstring::npos) && + details.find(L"доски ×3") != std::wstring::npos && details.find(L"блоки ×2") != std::wstring::npos, + "real returning resident did not expose actual cargo and waiting reason"); +} +} // namespace production_controls From 83a57cbe46b73672bd41ad92a9ad0198572c6f44 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:13:59 +0300 Subject: [PATCH 05/10] Fence legacy peers from an unrepresentable custody publication --- app/lan_session.hpp | 4 +- app/lan_session_win32.cpp | 71 ++++++++++++++----- app/viewer_session.cpp | 6 +- docs/agent-workflow/tasks/S16-03.md | 48 +++++++++++++ docs/plan/systems/S16.md | 6 ++ tests/lan_tests.cpp | 106 +++++++++++++++++++++++++++- tests/viewer_session_tests.cpp | 36 +++++++++- 7 files changed, 256 insertions(+), 21 deletions(-) create mode 100644 docs/agent-workflow/tasks/S16-03.md diff --git a/app/lan_session.hpp b/app/lan_session.hpp index 96f5307..cfcc08b 100644 --- a/app/lan_session.hpp +++ b/app/lan_session.hpp @@ -53,7 +53,9 @@ public: // poll_guest pauses further sends until this one retained result is drained. [[nodiscard]] std::optional take_result() noexcept; [[nodiscard]] std::unique_ptr poll(World& world); - // Protocol 11 accepts the compiled default rules and a 32x32 active colony. + // Protocol 11 accepts the compiled default rules and a representable 32x32 + // active colony. Incompatible state drops the peer, including queued bytes, + // while the listener and authoritative owner remain available. // Calls never wait for the owner. An admitted guest operation survives peer // turnover, so poll_host must continue with the same owner until it settles. void poll_host(SimulationRuntime& runtime); diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index dab4ab7..ba5c55e 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -151,6 +151,16 @@ struct Action { AgentId resident; }; +void require_legacy_world(const World& world) { + if (!world.scenario_active() || world.width() != first_colony_map_size || + world.height() != first_colony_map_size) { + throw std::runtime_error("Protocol 11 requires a supported 32x32 colony."); + } + if (!world.legacy_representable()) { + throw UnsupportedLegacyState{}; + } +} + } // namespace struct LanSession::Impl { @@ -300,13 +310,18 @@ struct LanSession::Impl { } } - void complete_runtime_command() { + void complete_runtime_command(SimulationRuntime& runtime) { if (!pending_command || pending_command->completion.wait_for(0s) != std::future_status::ready) return; auto pending = std::move(*pending_command); pending_command.reset(); const auto result = pending.completion.get(); if (pending.peer_generation != peer_generation || !authenticated || !runtime_session || pending.session != *runtime_session) return; + // A ready receipt can predate a load or an incompatible local change. + // Settle its future, but never queue old bytes for the current peer. + const auto current = runtime.view(); + validate_runtime(current); + if (current.snapshot->identity.session != pending.session) return; if (result.outcome != RuntimeOutcome::Completed || !result.receipt || !result.snapshot || result.snapshot->identity.session != pending.session) { throw std::runtime_error("The authoritative guest command did not commit."); @@ -321,27 +336,38 @@ struct LanSession::Impl { } } - void bind_runtime(const RuntimeView& view) { + void validate_runtime(const RuntimeView& view) { if (!compatibility_rules) { auto rules = default_rules_manifest(); if (!rules) throw std::runtime_error("Could not resolve the legacy LAN rules."); compatibility_rules = std::move(*rules); } - if (view.state != RuntimeState::Running || !view.snapshot) { + if (view.state != RuntimeState::Running || !view.snapshot || !view.snapshot->world) { throw std::runtime_error("The authoritative owner is unavailable."); } const auto& snapshot = *view.snapshot; if (!snapshot.rules || *snapshot.rules != *compatibility_rules) { throw std::runtime_error("Protocol 11 requires the compiled default rules."); } - if (!snapshot.world->scenario_active() || snapshot.world->width() != first_colony_map_size || - snapshot.world->height() != first_colony_map_size) { - throw std::runtime_error("Protocol 11 requires a supported 32x32 colony."); - } + require_legacy_world(*snapshot.world); + } + + void bind_runtime(const RuntimeView& view) { + validate_runtime(view); + const auto& snapshot = *view.snapshot; if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer(); runtime_session = snapshot.identity.session; } + std::shared_ptr current_runtime_snapshot(SimulationRuntime& runtime) { + const auto view = runtime.view(); + validate_runtime(view); + if (!runtime_session || *runtime_session != view.snapshot->identity.session) { + throw std::runtime_error("The authoritative session changed. Reconnect to the host."); + } + return view.snapshot; + } + void handle_guest(std::unique_ptr& latest, Message message, std::string_view payload) { if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version."); if (message == Message::Snapshot) { @@ -373,6 +399,7 @@ struct LanSession::Impl { } void send_snapshot(const World& world, Clock::time_point now) { + require_legacy_world(world); if (peer.pending()) return; const auto host_seq = world.next_command_sequence(1); const auto guest_seq = world.next_command_sequence(guest_player); @@ -400,8 +427,9 @@ struct LanSession::Impl { awaiting_receipt = action; } - template - void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) { + template + void poll_network(Receive receive, SendHost send_host, Validate validate, bool accept_allowed = true) { + validate(); if (listener && accept_allowed) accept_guest(); if (!peer.socket) return; const auto now = Clock::now(); @@ -411,7 +439,12 @@ struct LanSession::Impl { } if (connecting) finish_connection(); if (connecting) return; - peer.receive(receive); + peer.receive([&](Message message, std::string_view payload) { + // The owner can publish while one receive drains several frames. + validate(); + receive(message, payload); + }); + validate(); if (authenticated && guest) { send_action(); if (!peer.pending() && now - last_ping >= 2s) { @@ -421,6 +454,8 @@ struct LanSession::Impl { } else if (authenticated) { send_host(now); } + // This includes old snapshots/receipts already waiting in output. + validate(); peer.flush(); if (reject_pending && !peer.pending()) drop_peer(); } @@ -536,7 +571,9 @@ std::unique_ptr LanSession::poll(World& world) { connection.poll_network([&](Message message, std::string_view payload) { if (connection.guest) connection.handle_guest(latest, message, payload); else connection.handle_host(world, message, payload); - }, [&](Clock::time_point now) { connection.send_snapshot(world, now); }); + }, [&](Clock::time_point now) { connection.send_snapshot(world, now); }, [&] { + if (connection.listener && !connection.guest) require_legacy_world(world); + }); } catch (const std::exception& error) { connection.notice = error.what(); connection.drop_peer(); @@ -549,16 +586,18 @@ void LanSession::poll_host(SimulationRuntime& runtime) { auto& connection = *impl_; if (!connection.listener || connection.guest) return; try { - connection.complete_runtime_command(); + connection.complete_runtime_command(runtime); // Completion may have published a newer next-request number. Re-read it // before admitting a reconnect or decoding any further guest intent. const auto view = runtime.view(); connection.bind_runtime(view); connection.poll_network([&](Message message, std::string_view payload) { - connection.handle_runtime_host(runtime, *view.snapshot, message, payload); + const auto snapshot = connection.current_runtime_snapshot(runtime); + connection.handle_runtime_host(runtime, *snapshot, message, payload); }, [&](Clock::time_point now) { - if (!connection.pending_command) connection.send_snapshot(*view.snapshot->world, now); - }, !connection.pending_command); + const auto snapshot = connection.current_runtime_snapshot(runtime); + if (!connection.pending_command) connection.send_snapshot(*snapshot->world, now); + }, [&] { static_cast(connection.current_runtime_snapshot(runtime)); }, !connection.pending_command); } catch (const std::exception& error) { connection.notice = error.what(); connection.drop_peer(); @@ -573,7 +612,7 @@ std::unique_ptr LanSession::poll_guest() { try { connection.poll_network([&](Message message, std::string_view payload) { connection.handle_guest(latest, message, payload); - }, [](Clock::time_point) {}); + }, [](Clock::time_point) {}, [] {}); } catch (const std::exception& error) { connection.notice = error.what(); connection.drop_peer(); diff --git a/app/viewer_session.cpp b/app/viewer_session.cpp index dd91714..85948de 100644 --- a/app/viewer_session.cpp +++ b/app/viewer_session.cpp @@ -76,7 +76,11 @@ bool ViewerSession::can_submit() const { bool ViewerSession::can_host_legacy() const { const auto current = runtime_.view(); return !guest_ && !changing_world_ && current.state == RuntimeState::Running && - current.snapshot->rules && *current.snapshot->rules == supported_rules_; + current.snapshot && current.snapshot->rules && *current.snapshot->rules == supported_rules_ && + current.snapshot->world && current.snapshot->world->scenario_active() && + current.snapshot->world->width() == first_colony_map_size && + current.snapshot->world->height() == first_colony_map_size && + current.snapshot->world->legacy_representable(); } std::optional ViewerSession::submit(SessionPayload payload) { diff --git a/docs/agent-workflow/tasks/S16-03.md b/docs/agent-workflow/tasks/S16-03.md new file mode 100644 index 0000000..9565969 --- /dev/null +++ b/docs/agent-workflow/tasks/S16-03.md @@ -0,0 +1,48 @@ +# Gate legacy guests on exact representability of authoritative cargo + +Task ID: S16-03 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Isolated s16 1b57183, local base modern selector 5a64a27 + S06 header 4f42488. World::legacy_representable() const noexcept and typed UnsupportedLegacyState declared. S06 and S15 owners implement actual new states and raw13 preflight. Existing session supports LAN11 32×32/default rules and historical old binary interop. A common send path sends pending output before a new snapshot, so handling only encode exceptions is too late. + +## 2. Objective and deliverables +Reject admission and disconnect incompatible existing LAN11 guests early when the actual authoritative snapshot cannot project into the old format, while preserving the host and all already-admitted receipts. Keep both direct/deferred UI Host refusal before creating a listener. + +## 3. Scope and non-goals +LAN11 adapter, host-readiness predicate used by Win32, and focused compatibility tests. No protocol change, modern authoritative-rules restriction, dispatcher command variant or alteration of actual inventory ownership. Normal valid old/new binary interop remains. + +## 4. Files to inspect +Read app/lan_session_win32.cpp all poll_network, handshake/receive/send_snapshot/pending output/complete_runtime_command paths incl older standalone poll(World&), app/lan_session.hpp, viewer_session.cpp::can_host_legacy and member/header/actual normal callers from S18; engine/core/world.hpp public frozen readiness + exception, S04/S06 plans and M01-F8. Read tests/lan_tests.cpp and viewer_session_tests.cpp, historic two-binary interop harness in /tmp. + +## 5. Write ownership and coordination +Write scope: app/lan_session_win32.cpp; app/lan_session.hpp only if meaningful API docs or narrow shared predicate; app/viewer_session.cpp only can_host_legacy and local support predicate; tests/lan_tests.cpp and tests/viewer_session_tests.cpp narrowly for legacy compatibility; docs/plan/systems/S16.md +No S06 World/codec/cancel implementation, dispatcher edits or S04/S17 viewer_win32 file changes. Others own these in siblings; do not revert/switch Serena or write outside worktree except your temp verification source. Root owns Git/remote. + +## 6. Implementation or investigation approach +Gate exact supported rules/active dimensions and actual World::legacy_representable result before accepting/authenticating, receiving/dispatching guest commands, sending/continuing queued legacy output. Do not send partially legacy-encoded bytes. A newly unrepresentable state disconnects old peer and safely clears outgoing/peer-specific pending/request metadata; preserve settlement of already-admitted owner work and compatibility of later reconnection. Incoming cmd must check current published view/epoch before admission; allow valid previously accepted owner work to settle after disconnect. Old poll(World&) normal host path must guard projection and keep owning standalone world unchanged on refusal. + +## 7. Interfaces and data contracts +Use typed compatibility failures/explicit reason or existing guarded notice. Healthy hosts continue stepping, saving modern checkpoint and receiving modern commands; ViewerSession::can_host_legacy must check published exact default and freeze during replacement, direct/deferred actual callers gate on that. Do not silently downgrade, fabricate a matching old state, or disconnect a guest for representable ordinary historical default/simple worlds. Preserve user-selected local colony and port/peer while refusing a newly requested Host. + +## 8. Dependencies and integration +Depends on S06-03 implementation+S15-04 current15 for actual integrated tests. Local branch currently contains header only, parent will merge coherent core for real normal entry and old binary. Design fixture with a real canceled mixed-cargo/no-storage or withheld suspended site and positive representable counterpart; coordinate with S06/S04 if needed. No mocks for final acceptance. + +## 9. Edge cases security and performance +Beware connected guest with old snapshot bytes pending, re-auth/wrong connection incarnation, UDP not involved, S16 ledger boundaries vs published current epoch. Keep game thread and UI polling nonblocking. Avoid full serialization solely to test readiness on each poll when dedicated bounded pure check exists; use immutable snapshot identity/revision when caches needed. + +## 10. Acceptance criteria +1. At least one real unrepresentable default colony (mixed canceled carrier/single unlinked plank/suspended residual as applicable) refuses listener/handshake and drops already-connected guest before a further wire command mutates it. 2. Already-admitted command still settles. 3. Host remains healthy, new modern save/reload works and local progress continues. 4. Normal old protocol fixture and old binary both directions pass, valid default simple historical colony still allowed; optional rules still denied. 5. All CTest/GUI at final integrate. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s16-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Compile independent translation units as feasible now; verify actual core when root supplies it. CTest -V/targeted wire/owner, external interop harness /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-interop.{cpp,py}; keep s16-custody-* logs. Scoped tests use localhost only and temp saves. + +## 12. Constraints and stop conditions +Never weaken wire11 bounds or gate whole modern owner/dispatcher. Do not add general authentication flow or expose an external service. If checked interface missing/incorrect, inform root and work independently pending real dependencies. No Git/remote writes/children. Two same-cause failed repairs escalate. + +## 13. Authorization and decisions +User authorizes full project. F8/root approve truthful unsupported legacy projection and disconnect preserving host; original normal interop retained. Root owns public actions. + +## 14. Return format +Return S16-03 progress/READY or PARTIAL, actual admission/queued frame/receipt behavior, tests/logs and native limits. Identify exact dependency commit needed for final integration. diff --git a/docs/plan/systems/S16.md b/docs/plan/systems/S16.md index 6393cd1..1b21266 100644 --- a/docs/plan/systems/S16.md +++ b/docs/plan/systems/S16.md @@ -51,6 +51,12 @@ Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается. +Проверка представимости фактического имущества выполняется до приёма соединения, перед каждым разобранным сообщением и перед отправкой, включая продолжение ранее поставленного снимка или квитанции. `World::legacy_representable()` проверяет игровой контракт без пробной сериализации. Если отменённый груз или приостановленная площадка не имеют точного представления в формате 13, адаптер закрывает гостя и очищает его буферы. Слушатель, современный владелец и принятая им работа сохраняются; готовая квитанция прежнего подключения не отправляется следующему гостю. При работе с фоновым владельцем каждое сообщение и отправка сверяют свежую публикацию и инкарнацию. Прежний `poll(World&)` применяет ту же проверку представимости. + +Общий `ViewerSession::can_host_legacy()` разрешает создание слушателя только для опубликованной представимой активной колонии 32×32 с точными встроенными правилами, вне гостевого режима и смены партии. Это ограничение совместимости не блокирует современные команды и контрольные точки. Историческая активная колония с простым рецептом кровати и встроенным манифестом остаётся допустимой. [Контракт S16-03](../../agent-workflow/tasks/S16-03.md) + +Для этого адаптера повторно проверены публичный `Void/Net/Socket.hpp`, Windows-ветка `src/Net/Socket.cpp` и `tests/standalone/Net/Socket.cpp` закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792`: UDP не реализован для Windows и не предоставляет игровую проверку представимости. Существующий TCP-транспорт остаётся прежним. Имущество и условие отказа принадлежат игровому адаптеру поверх операций [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8); новое универсальное сетевое средство не вводится. + Пять проверок `--tag lan-owner` под Wine покрывают квитанции, заполнение очереди, совмещённые пакеты, переподключение при задержанной публикации, откат с незавершённой командой и отказ при несовместимых правилах. Отдельный двоичный клиент прототипа подтвердил обмен в обоих направлениях с новым хостом и гостем. Проверка физической Windows и двух машин остаётся частью сетевой приёмки. [Сценарии](../../../tests/lan_tests.cpp) Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6) diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index c7a078a..162cff5 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -48,6 +48,29 @@ WorldCheckpoint colony_checkpoint() { return {make_first_colony(2), *identity, 1, std::move(*rules)}; } +std::unique_ptr mixed_delivery() { + auto world = std::make_unique(43, 32, 32, 2); + const auto store = world->add_storage({3, 3}, 5); + world->stock_storage(store, ItemType::Plank, 3); + world->stock_storage(store, ItemType::StoneBlock, 2); + static_cast(world->spawn_agent({1, 3})); + world->start_scenario({6, 6}); + world->queue_production({14, 3}, RecipeId::BuildCabin); + for (int tick = 0; tick < 100 && world->agents().front().inventory.empty(); ++tick) world->step(); + const auto& cargo = world->agents().front().inventory; + require(cargo.item_count(ItemType::Plank) == 3 && cargo.item_count(ItemType::StoneBlock) == 2); + // Keep canceled cargo blocked at its real owner through later steps. + world->stock_storage(store, ItemType::Wood, 5); + require(world->legacy_representable()); + return world; +} + +void cancel_mixed_delivery(World& world) { + require(world.cancel_production(world.production_orders().front().id) == CommandStatus::Accepted); + require(!world.legacy_representable()); + world.validate_custody(); +} + template void pump_until(Pump pump, Condition condition, const char* message) { const auto deadline = std::chrono::steady_clock::now() + 3s; @@ -115,8 +138,9 @@ struct RawGuest { RawGuest(const RawGuest&) = delete; RawGuest& operator=(const RawGuest&) = delete; - void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) { - const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value}); + void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0, + AgentId resident = 0) { + const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value, {}, resident}); lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes)); } @@ -163,6 +187,8 @@ struct LanTests : Void::Testing::Suite { [[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_retains_slot_work_across_reconnect(); [[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_reauthenticates_after_pending_rollback(); [[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults(); + [[= Void::Testing::tag("lan-owner")]] Test test_legacy_custody_refuses_handshake_and_preserves_modern_owner(); + [[= Void::Testing::tag("lan-owner")]] Test test_standalone_custody_discards_queued_snapshot_and_command(); }; Test LanTests::test_protocol_11_fixed_messages() { @@ -617,4 +643,80 @@ Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() { require(!guest.take_result()); } +Test LanTests::test_legacy_custody_refuses_handshake_and_preserves_modern_owner() { + auto initial = colony_checkpoint(); + initial.world = mixed_delivery(); + cancel_mixed_delivery(*initial.world); + const auto encoded = encode_checkpoint(*initial.world, initial.world_id, initial.city, initial.rules); + require(encoded.has_value()); + auto packages = builtin_rule_packages(); + require(packages.has_value()); + auto restored = decode_checkpoint(*encoded, *packages, 2); + require(restored.has_value() && !restored->world->legacy_representable()); + SimulationRuntime runtime(std::move(*restored), {.ticking = false}); + LanSession host, guest; + host.host(0, true); + const auto port = host.port(); + guest.join("127.0.0.1", host.join_code(), port); + for (int attempt = 0; attempt < 20; ++attempt) { + host.poll_host(runtime); + require(!guest.poll_guest()); + } + require(host.state() == LanState::Hosting && host.port() == port && !host.detail().empty()); + require(guest.state() != LanState::GuestConnected && !guest.take_result()); + const auto before = runtime.latest(); + const auto& id = before->identity; + auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, + before->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}}); + require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready); + require(local.completion.get().receipt->command_status == CommandStatus::Accepted); + require(runtime.view().state == RuntimeState::Running && runtime.latest()->world->paused()); + const auto current = runtime.latest(); + auto saved = encode_checkpoint(*current->world, id.world, id.city, *current->rules); + require(saved.has_value() && decode_checkpoint(*saved, *packages, 2).has_value()); + require(current->next_requests[1] == before->next_requests[1]); +} + +Test LanTests::test_standalone_custody_discards_queued_snapshot_and_command() { + auto world = mixed_delivery(); + // A real historical snapshot larger than one 64 KiB flush leaves output + // queued; gating only a subsequent send_snapshot call misses this case. + for (int job = 0; job < 4096; ++job) static_cast(world->add_job({20, 20}, 1)); + std::ostringstream bytes(std::ios::binary); + world->write_save(bytes); + require(bytes.view().size() > 64 * 1024); + LanSession host; + host.host(0, true); + RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16)); + guest.poll(); + pump_until([&] { static_cast(host.poll(*world)); }, + [&] { return host.state() == LanState::HostConnected; }, "Standalone guest did not authenticate."); + guest.poll(); + require(!guest.input.empty() && !guest.snapshot); + const auto partial = guest.input.size(); + const auto profession = world->agents().front().profession; + cancel_mixed_delivery(*world); + guest.command(1, CommandKind::AssignProfession, {}, static_cast(Profession::Miner), + world->agents().front().id); + guest.poll(); + pump_until([&] { static_cast(host.poll(*world)); guest.poll(); }, + [&] { return guest.closed; }, "Unsupported standalone peer stayed connected."); + require(host.state() == LanState::Hosting && !host.detail().empty()); + require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty()); + require(world->next_command_sequence(2) == 1 && world->agents().front().profession == profession); + const auto tick = world->tick(); + world->step(); + require(world->tick() == tick + 1); + world->validate_custody(); + + auto compatible = mixed_delivery(); + RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16)); + const auto pump = [&] { static_cast(host.poll(*compatible)); next.poll(); }; + pump_until(pump, [&] { return next.snapshot != nullptr; }, "Representable counterpart could not join."); + next.command(1, CommandKind::AssignProfession, {}, static_cast(Profession::Miner), + compatible->agents().front().id); + pump_until(pump, [&] { return !next.receipts.empty(); }, "Representable counterpart command did not settle."); + require(next.receipts.front().status == CommandStatus::Accepted); +} + } // namespace diff --git a/tests/viewer_session_tests.cpp b/tests/viewer_session_tests.cpp index 6526a83..6ec7507 100644 --- a/tests/viewer_session_tests.cpp +++ b/tests/viewer_session_tests.cpp @@ -116,6 +116,7 @@ struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void [[= Void::Testing::tag("viewer-session")]] Test test_profile_validation_rejects_initial_and_loaded_mismatches(); [[= Void::Testing::tag("viewer-session")]] Test test_pending_optional_load_blocks_host_and_newest_invalid_load_wins(); [[= Void::Testing::tag("viewer-session")]] Test test_historical_default_modes_and_guest_leave_keep_default_rules(); + [[= Void::Testing::tag("viewer-session")]] Test test_legacy_host_requires_representable_published_custody(); }; Test ViewerSessionTests::test_commands_wait_for_commit_and_keep_rejected_drafts_retryable() { @@ -530,7 +531,7 @@ Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_defa if (mode == 2) candidate.world = std::make_unique(17, 32, 32, 2); const auto expected = bytes(*candidate.world); ViewerSession session(std::move(candidate), 2); - require(bytes(*session.world()) == expected && session.can_host_legacy()); + require(bytes(*session.world()) == expected && session.can_host_legacy() == (mode != 2)); write(files.root / "legacy.settlement", expected); session.load(files.root / "legacy.settlement"); pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); }); @@ -544,4 +545,37 @@ Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_defa require(!session.world()->staged_beds() && *session.runtime().latest()->rules == defaults && session.can_host_legacy()); } +Test ViewerSessionTests::test_legacy_host_requires_representable_published_custody() { + auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2)); + candidate.world = std::make_unique(43, 32, 32, 2); + auto& world = *candidate.world; + const auto store = world.add_storage({3, 3}, 5); + world.stock_storage(store, ItemType::Plank, 3); + world.stock_storage(store, ItemType::StoneBlock, 2); + static_cast(world.spawn_agent({1, 3})); + world.start_scenario({6, 6}); + world.queue_production({14, 3}, RecipeId::BuildCabin); + for (int tick = 0; tick < 100 && world.agents().front().inventory.empty(); ++tick) world.step(); + require(world.agents().front().inventory.item_count(ItemType::Plank) == 3 && + world.agents().front().inventory.item_count(ItemType::StoneBlock) == 2); + world.stock_storage(store, ItemType::Wood, 5); + require(world.legacy_representable()); + require(world.cancel_production(world.production_orders().front().id) == CommandStatus::Accepted); + require(!world.legacy_representable()); + ViewerSession session(std::move(candidate), 2); + const auto published = session.runtime().latest(); + require(!session.can_host_legacy() && session.can_submit()); + require(session.world() == published->world && session.runtime().view().state == RuntimeState::Running); + TempFiles files; + session.save(files.root / "custody.settlement"); + pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Saved); }); + session.load(files.root / "custody.settlement"); + pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); }); + require(!session.can_host_legacy() && !session.world()->legacy_representable() && session.can_submit()); + session.new_colony(); + require(session.changing_world() && !session.can_host_legacy()); + pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); }); + require(session.can_host_legacy()); +} + } // namespace From 9e20f99a66116e03a18d1e52c6d174c366e7a6ac Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:19:05 +0300 Subject: [PATCH 06/10] Validate work phases and retain exact refusal and consumption receipts --- engine/src/custody.cpp | 116 +++++++++++++++++++++++++++++++++++++--- engine/src/world.cpp | 29 +++++++--- tests/custody_tests.cpp | 73 ++++++++++++++++++++++++- 3 files changed, 203 insertions(+), 15 deletions(-) diff --git a/engine/src/custody.cpp b/engine/src/custody.cpp index 8662c9b..0107e5e 100644 --- a/engine/src/custody.cpp +++ b/engine/src/custody.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include namespace settlement { @@ -257,26 +258,31 @@ bool World::deposit_custody(Agent& agent, Storage& destination, ItemType type, s receipt->request.line_count = 1; receipt->result = {CustodyStatus::Accepted, execution.id}; if (!room(execution.next_operation, 1)) return false; + const auto fail = [&](CustodyStatus status) { + receipt->result.status = status; + commit_custody(agent, receipt); + return false; + }; auto slots = planned.reserved_slots; for (auto& claim : execution.reservations) { if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == destination.id && !claim.backing) { - if (slots < claim.count) return false; + if (slots < claim.count) return fail(CustodyStatus::Invalid); slots -= claim.count; claim = {}; } } - if (planned.total_items() + slots + count > planned.capacity) return false; + if (planned.total_items() + slots + count > planned.capacity) return fail(CustodyStatus::Capacity); auto target = stock(planned, type); StackId id = 0; if (target != planned.items.end()) { const auto amount = Void::Numeric::checked_add(target->count, count); - if (!amount) return false; + if (!amount) return fail(CustodyStatus::Overflow); target->count = *amount; id = target->id; } else { id = inventory.stack_id(type); if (count < inventory.item_count(type)) { - if (!room(next, 1)) return false; + if (!room(next, 1)) return fail(CustodyStatus::Exhausted); id = next++; } planned.items.push_back({type, count, 0, id}); @@ -455,6 +461,7 @@ void World::validate_custody() const { if (actor.production_id) require(producers.emplace(actor.production_id, &actor).second); } std::set transfers; + std::unordered_map active_ordinals; std::set reservation_ids; std::set work_sites; std::set backed; @@ -463,13 +470,16 @@ void World::validate_custody() const { if (!actor.execution) { require(actor.inventory.empty() && actor.production_id == 0 && actor.resource_node_id == 0 && actor.state != AgentState::Returning && actor.state != AgentState::Hauling && - actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat); + actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat && + actor.state != AgentState::Gathering && actor.state != AgentState::FetchingMaterials && + (actor.state != AgentState::Working || actor.current_job != 0)); continue; } const auto& execution = *actor.execution; require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second && execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 && execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination); + active_ordinals.emplace(execution.id, execution.next_operation); require(execution.production == actor.production_id && execution.source == actor.resource_node_id); if (execution.kind == TransferKind::Return) { require(!actor.inventory.empty() && !actor.production_id && !actor.resource_node_id && actor.work_remaining == 0); @@ -488,12 +498,17 @@ void World::validate_custody() const { if (execution.production) require(find_production(execution.production) != nullptr); else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item())); } + std::array claim_kinds{}; + std::array resident_claims{}; for (std::size_t index = 0; index < custody_reservation_limit; ++index) { const auto& claim = execution.reservations[index]; if (claim.id == 0) { require(claim == Reservation{}); continue; } require(index < execution.reservation_count && claim.id < next_reservation_id_ && reservation_ids.insert(claim.id).second && claim.kind <= ReservationKind::Tending && claim.count); + ++claim_kinds[static_cast(claim.kind)]; if (claim.kind == ReservationKind::Item) { + if (claim.owner.kind == OwnerKind::Resident && claim.item > ItemType::None && claim.item <= ItemType::Loom) + resident_claims[static_cast(claim.item) - 1] += claim.count; auto entry = physical.find(claim.stack); require(entry != physical.end() && entry->second.owner == claim.owner && entry->second.item == claim.item); require(!claim.backing); @@ -526,8 +541,36 @@ void World::validate_custody() const { require(claim.owner == StockOwner{} && !claim.stack && claim.item == ItemType::None && claim.count == 1 && !claim.backing && !claim.origin_storage && execution.source && find_resource_node(execution.source)); workers[execution.source] += claim.count; + require((claim.kind == ReservationKind::Tending) == (execution.kind == TransferKind::Tending)); } } + require(claim_kinds[static_cast(ReservationKind::Worksite)] == (execution.production ? 1U : 0U)); + require(claim_kinds[static_cast(ReservationKind::Capacity)] == (execution.destination ? 1U : 0U)); + require(claim_kinds[static_cast(ReservationKind::Harvest)] == + (execution.kind == TransferKind::Harvest && execution.source ? 1U : 0U)); + require(claim_kinds[static_cast(ReservationKind::Tending)] == (execution.kind == TransferKind::Tending ? 1U : 0U)); + if (execution.kind == TransferKind::Meal) { + require(claim_kinds[0] == 1); + for (const auto& claim : execution.reservations) if (claim.id && claim.kind == ReservationKind::Item) { + require(claim.item == ItemType::Berries && claim.count == 1 && claim.owner == + (actor.state == AgentState::Eating ? StockOwner{OwnerKind::Resident, actor.id} : StockOwner{OwnerKind::Storage, actor.storage_id})); + } + } + if (actor.state == AgentState::Eating || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling)) { + for (std::size_t i = 0; i < item_type_count; ++i) require(resident_claims[i] == actor.inventory.item_count(static_cast(i + 1))); + } + if (execution.source) { + const auto* node = find_resource_node(execution.source); + require(node && actor.inventory.empty() && (actor.state == AgentState::Gathering || actor.state == AgentState::Travelling)); + require(execution.kind != TransferKind::Tending || node->needs_tending()); + require(execution.kind != TransferKind::Harvest || (node->quantity && execution.destination && actor.storage_id == execution.destination)); + } + if (actor.state == AgentState::Hauling && !execution.production) { + require(actor.storage_id == execution.destination && execution.destination && actor.work_remaining == 0); + std::uint64_t carried = 0; + for (std::size_t i = 1; i <= item_type_count; ++i) carried += actor.inventory.item_count(static_cast(i)); + require(carried == 1); + } } for (const auto& store : storages_) { require(slots[store.id] == store.reserved_slots); @@ -541,6 +584,45 @@ void World::validate_custody() const { const auto found_actor = producers.find(order.id); require(found_actor != producers.end()); const auto actor = found_actor->second; + require(order.materials.size() <= custody_material_limit && order.collected_stops <= order.delivery_stops.size()); + const bool delivery = delivers_materials(order.recipe); + require(delivery || order.delivery_stops.empty()); + std::array required{}, planned{}, claimed{}, cargo{}; + const auto need = [&](ItemType item, std::uint32_t count) { if (count) required[static_cast(item) - 1] += count; }; + if (order.recipe == RecipeId::SawPlank) need(ItemType::Wood, 1); + else if (order.recipe == RecipeId::CutStoneBlock) need(ItemType::Stone, 1); + else if (order.recipe == RecipeId::WeaveCloth) need(ItemType::Flax, 1); + else if (order.recipe == RecipeId::BuildBed) need(order.bed_material(), 1); + else for (const auto& item : is_carpentry_recipe(order.recipe) ? carpentry_materials(order.recipe) : + construction_materials(order.recipe, order.bed_base)) need(item.type, item.count); + StorageId previous_stop = 0; + for (const auto& stop : order.delivery_stops) { + require(stop.storage_id > previous_stop && find_storage(stop.storage_id)); previous_stop = stop.storage_id; + require(std::any_of(order.materials.begin(), order.materials.end(), [&](const auto& m) { return m.storage_id == stop.storage_id; })); + } + for (const auto& line : order.materials) { + require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count && find_storage(line.storage_id)); + planned[static_cast(line.type) - 1] += line.count; + StockOwner expected{OwnerKind::Storage, line.storage_id}; + if (delivery) { + if (actor->state == AgentState::Working) expected = {OwnerKind::Production, order.id}; + else { + const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(), [&](const auto& e) { return e.storage_id == line.storage_id; }); + require(stop != order.delivery_stops.end()); + if (static_cast(stop - order.delivery_stops.begin()) < order.collected_stops) expected = {OwnerKind::Resident, actor->id}; + } + } + std::uint64_t line_claims = 0; + for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item && + claim.item == line.type && claim.origin_storage == line.storage_id) { require(claim.owner == expected); line_claims += claim.count; } + require(line_claims == line.count); + if (expected.kind == OwnerKind::Resident) cargo[static_cast(line.type) - 1] += line.count; + } + for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item) + claimed[static_cast(claim.item) - 1] += claim.count; + require(planned == required && claimed == required); + for (std::size_t i = 0; i < item_type_count; ++i) require(cargo[i] == actor->inventory.item_count(static_cast(i + 1))); + if (actor->state == AgentState::Working) require(actor->route_cursor == actor->route.size() && order.delivery_stops.empty()); if (delivers_materials(order.recipe) && actor->state == AgentState::Working) { std::array expected{}; for (const auto& line : order.materials) { @@ -571,7 +653,11 @@ void World::validate_custody() const { require(custody_receipts_.size() <= custody_receipt_limit && (custody_receipts_.size() == custody_receipt_limit ? custody_receipt_cursor_ < custody_receipt_limit : custody_receipt_cursor_ == 0)); std::set> keys; - for (const auto& receipt : custody_receipts_) { + std::map, std::uint64_t> last_ordinals; + TransferId last_admission = 0; + std::set terminal_transfers; + for (std::size_t receipt_index = 0; receipt_index < custody_receipts_.size(); ++receipt_index) { + const auto& receipt = custody_receipts_[(receipt_index + custody_receipt_cursor_) % custody_receipts_.size()]; require(static_cast(receipt)); const auto& request = receipt->request; const auto& result = receipt->result; @@ -579,11 +665,25 @@ void World::validate_custody() const { request.kind <= TransferKind::Return && request.operation <= CustodyOperation::Tend && request.line_count <= custody_material_limit && request.production < next_production_id_ && request.destination < next_storage_id_ && keys.emplace(request.key.kind, request.key.id, request.key.ordinal).second); + auto& last_ordinal = last_ordinals[{request.key.kind, request.key.id}]; + require(last_ordinal == 0 || (last_ordinal != maximum && request.key.ordinal == last_ordinal + 1)); + last_ordinal = request.key.ordinal; + require(!terminal_transfers.contains(result.transfer)); + if (result.terminal) { require(result.status == CustodyStatus::Accepted); terminal_transfers.insert(result.transfer); } + require(request.source < (((request.operation == CustodyOperation::Admit && + (request.kind == TransferKind::Harvest || request.kind == TransferKind::Tending)) || + request.operation == CustodyOperation::Harvest || request.operation == CustodyOperation::Tend) ? next_resource_node_id_ : next_storage_id_)); if (request.key.kind == CustodyKeyKind::Admission) { - require(request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit); + require(result.transfer > last_admission && !result.terminal); + last_admission = result.transfer; + require(result.status == CustodyStatus::Accepted && request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit); const auto actor = actors.find(request.key.id); if (actor != actors.end()) require(request.key.ordinal < actor->second->next_admission); - } else require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit); + } else { + require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit && result.transfer == request.key.id); + const auto active = active_ordinals.find(request.key.id); + if (active != active_ordinals.end()) require(request.key.ordinal < active->second); + } for (std::size_t i = 0; i < custody_material_limit; ++i) { const auto& line = request.lines[i]; if (i >= request.line_count) require(line == CustodyLine{}); diff --git a/engine/src/world.cpp b/engine/src/world.cpp index 221d60b..d473855 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -1544,9 +1544,13 @@ void World::finish_meal_step(Agent& agent) { auto& sink = item_balances_[static_cast(ItemType::Berries) - 1].meal; const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{1}); const auto meals = Void::Numeric::checked_add(meals_eaten_, std::uint64_t{1}); - auto receipt = prepare_custody(agent, CustodyOperation::Eat, - amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow); + auto receipt = std::const_pointer_cast(prepare_custody(agent, CustodyOperation::Eat, + amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow)); if (!receipt) return; + receipt->result.terminal = amount && meals; + receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, agent.inventory.stack_id(ItemType::Berries), ItemType::Berries, + amount && meals ? 0U : 1U}; + receipt->result.effect_count = 1; commit_custody(agent, receipt); if (!amount || !meals) return; sink = *amount; @@ -1690,11 +1694,23 @@ void World::finish_production(Agent& agent) { if (!receipt) return; if (status == CustodyStatus::Accepted) { receipt->result.terminal = !carpentry; + for (const auto& material : order.materials) { + const auto& original_store = storage_by_id(material.storage_id); + StackId consumed_id = 0; + std::uint32_t remaining = 0; + StockOwner owner{OwnerKind::Production, order.id}; + if (delivered) { consumed_id = order.input.stack_id(material.type); remaining = input.item_count(material.type); } + else { + owner = {OwnerKind::Storage, material.storage_id}; + for (const auto& stack : original_store.items) if (stack.type == material.type) consumed_id = stack.id; + for (const auto& store : stores) if (store.id == material.storage_id) remaining = store.item_count(material.type); + } + receipt->result.effects[receipt->result.effect_count++] = {owner, consumed_id, material.type, remaining}; + } if (output_id) { - receipt->result.effects[0] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} : + receipt->result.effects[receipt->result.effect_count++] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} : StockOwner{OwnerKind::Storage, stores.front().id}, output_id, recipe.output, carpentry ? inventory.item_count(recipe.output) : stores.front().item_count(recipe.output)}; - receipt->result.effect_count = 1; } } commit_custody(agent, receipt); @@ -1867,8 +1883,9 @@ void World::step(TickProfile* profile) { ResourceNode& node = resource_node_by_id(agent.resource_node_id); if (agent.storage_id == 0) { const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site)); - auto receipt = prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow); + auto receipt = std::const_pointer_cast(prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow, node.id)); if (!receipt) continue; + receipt->result.terminal = growth.has_value(); commit_custody(agent, receipt); if (!growth) continue; node.growth_at = *growth; @@ -1884,7 +1901,7 @@ void World::step(TickProfile* profile) { const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1}); const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1}); auto receipt = std::const_pointer_cast(prepare_custody(agent, CustodyOperation::Harvest, - !next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted)); + !next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted, node.id)); if (!receipt) continue; if (next && amount) { receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, next_stack_id_, node.type, 1}; diff --git a/tests/custody_tests.cpp b/tests/custody_tests.cpp index b0f0d75..5c089a2 100644 --- a/tests/custody_tests.cpp +++ b/tests/custody_tests.cpp @@ -32,6 +32,9 @@ struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::S [[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume(); [[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction(); [[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance(); + [[= Void::Testing::tag("custody")]] Test rejects_missing_execution_and_claims(); + [[= Void::Testing::tag("custody")]] Test persistent_counter_boundaries_and_pending_completion(); + [[= Void::Testing::tag("custody")]] Test modern_roundtrip_cancel_and_exact_retry(); [[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics(); }; Test CustodyTests::ownership_delivery_and_consumption() { @@ -180,8 +183,76 @@ Test CustodyTests::snapshot_metrics() { samples.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); } std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes); + std::ostringstream modern; w.write_save(modern, WorldSaveFormat::Current15); std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size() - << " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << '\n'; + << " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << " raw15_bytes=" << modern.str().size() + << " receipt_object_bytes=" << sizeof(CustodyReceipt) << '\n'; } } + +Test CustodyTests::rejects_missing_execution_and_claims() { + auto w = cabin(); ticks(*w, 1); + const auto rejects = [&] { try { w->validate_custody(); } catch (const std::runtime_error&) { return true; } return false; }; + auto& actor = const_cast(w->agents()[0]); auto execution = actor.execution; + actor.execution.reset(); require(rejects(), "active actor without execution accepted"); actor.execution = execution; + actor.execution->reservations[0] = {}; require(rejects(), "missing material reservation accepted"); actor.execution = execution; + actor.execution->reservations[1].id = actor.execution->reservations[0].id; + require(rejects(), "duplicate claim ID accepted"); actor.execution = execution; + auto& order = const_cast(w->production_orders()[0]); ++order.materials[0].count; + require(rejects(), "different recipe quantity accepted"); --order.materials[0].count; + w->validate_custody(); +} +Test CustodyTests::modern_roundtrip_cancel_and_exact_retry() { + auto w = cabin(); ticks(*w, 16); + require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); + std::ostringstream encoded; w->write_save(encoded, WorldSaveFormat::Current15); + std::istringstream input(encoded.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference); + for (const auto& receipt : w->custody_receipts()) require(resumed->custody_request(receipt->request) == receipt->result, "restored exact receipt differed"); + std::ostringstream legacy; + bool refused = false; try { w->write_save(legacy); } catch (const UnsupportedLegacyState&) { refused = true; } + require(refused && legacy.str().empty(), "legacy refusal wrote bytes"); + for (int i = 0; i < 40; ++i) { + ticks(*w, 1); ticks(*resumed, 1); + std::ostringstream a,b; w->write_save(a, WorldSaveFormat::Current15); resumed->write_save(b, WorldSaveFormat::Current15); + require(a.str() == b.str(), "modern return continuation changed"); + } +} + +Test CustodyTests::persistent_counter_boundaries_and_pending_completion() { + const auto restored_counter = [](const World& world, std::size_t counter, std::uint64_t value) { + std::ostringstream old, modern; + world.write_save(old, WorldSaveFormat::Current14); world.write_save(modern, WorldSaveFormat::Current15); + auto bytes = modern.str(); const auto offset = old.str().size() + counter * 8; + require(offset + 8 <= bytes.size(), "custody extension missing"); + for (std::size_t i = 0; i < 8; ++i) bytes[offset + i] = static_cast((value >> (i * 8)) & 255U); + std::istringstream input(bytes); return World::read_save(input, 1, ExecutionMode::SerialReference); + }; + auto initial = cabin(); + for (std::size_t counter = 0; counter < 3; ++counter) { + bool invalid = false; try { auto ignored = restored_counter(*initial, counter, 0); } catch (const std::runtime_error&) { invalid = true; } + require(invalid, "zero durable highwater accepted"); + if (counter == 0) continue; + auto exhausted = restored_counter(*initial, counter, std::numeric_limits::max()); + ticks(*exhausted, 3); + require(!exhausted->agents()[0].execution && exhausted->custody_receipts().empty() && + exhausted->storages()[0].items[0].reserved == 0, "exhausted admission acquired claims"); + } + World saw(1, 10, 10, 1, ExecutionMode::SerialReference); + const auto store = saw.add_storage({2, 2}, 10); saw.stock_storage(store, ItemType::Wood, 1); + (void)saw.spawn_agent({3, 2}); saw.queue_production({3, 2}, RecipeId::SawPlank); + auto exhausted = restored_counter(saw, 0, std::numeric_limits::max()); + ticks(*exhausted, 12); + const auto& actor = exhausted->agents()[0]; + require(actor.state == AgentState::Working && actor.work_remaining == 0 && actor.execution->blocked == CustodyStatus::Exhausted, + "completion did not preserve pending zero timer"); + require(exhausted->storages()[0].item_count(ItemType::Wood) == 1 && exhausted->storages()[0].item_count(ItemType::Plank) == 0, + "refused completion partially consumed input"); + const auto ordinal = actor.execution->next_operation; + ticks(*exhausted, 3); + require(actor.work_remaining == 0 && actor.execution->next_operation == ordinal + 3 && !exhausted->legacy_representable(), + "pending retry underflowed timer or reused ordinal"); + std::ostringstream saved; exhausted->write_save(saved, WorldSaveFormat::Current15); + std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference); + ticks(*resumed, 1); require(resumed->agents()[0].work_remaining == 0, "restored pending completion decremented zero"); +} } From a76bf8778727a5c1b0e6d85eb140147489361e58 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:19:06 +0300 Subject: [PATCH 07/10] Bound save expansion and test authentic custody migration and journal wrap --- docs/plan/systems/S15.md | 18 +++++ engine/src/world_save.cpp | 20 +++-- tests/custody_migration_tests.cpp | 119 +++++++++++++++++++++++++++++- tests/snapshot_tests.cpp | 2 +- 4 files changed, 152 insertions(+), 7 deletions(-) diff --git a/docs/plan/systems/S15.md b/docs/plan/systems/S15.md index e755647..ccffd15 100644 --- a/docs/plan/systems/S15.md +++ b/docs/plan/systems/S15.md @@ -37,6 +37,24 @@ Windows-адаптер чтения связан с [Void/Library #9](https://gi При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md) +## Владение имуществом в версии 15 + +`encode_checkpoint` записывает схему 3 и тело 15. Декодер проверяет отдельную таблицу пар: схема 1 допускает тела 1–13, схема 2 — только 14, схема 3 — только 15. Проверка внешнего SHA-256 предшествует декодированию мира. Старый FNV-footer тел 1–8 и нормализация сна до версии 5 сохранены. + +Тело 15 сохраняет прежний набор полей тела 14 и добавляет реестр владения: три границы выданных ID, ID складских стеков и инвентарей, номер назначения каждого жителя, действующее исполнение с номерами операций и резервами, входы и приостановку заказов, восемь счётчиков баланса для каждого предмета и журнал результатов. Резервы содержат владельца, конкретный стек, количество, источник обеспечения вместимости и исходный склад. Пустые позиции массивов имеют единственное нулевое представление. Журнал записывается от самого старого результата к самому новому независимо от физической позиции кольца в памяти. + +Запрос и результат имеют собственные 16-битные длины и типизированные поля little-endian. Текущий запрос занимает не более 109 байт, результат — 318 байт; общий предел каждого остаётся 1024 байта. Непустой элемент результата может содержать нулевой остаток уже израсходованного стека. Это историческая ссылка, а не новый пустой стек. Максимум 4096 записей занимает до 1 765 376 байт вместе с длинами. Проверяются точные данные запросов, а не только их хеши. + +Лимит тела 128 МиБ отделён от лимита старого сетевого снимка 4 МиБ и от бюджета декодированной памяти. Число записей каждой исторической коллекции ограничено миллионом. Бюджет памяти учитывает расширенные C++-записи всех ограниченных пулов, вложенные массивы и журнал; арифметика верхней границы проверяется при компиляции. Чтение растит вектор по одному элементу и не резервирует память под объявленное недоверенным файлом число. Маленький обрезанный файл с числом жителей 1 000 000 заканчивается ошибкой после первой незавершённой записи. + +Перенос старого тела начинается только после полной исторической проверки. ID назначаются в порядке вида владельца, ID владельца и предмета. Материалы, уже доставленные на стройку, восстанавливаются во входе заказа без повторного списания склада; у прямых рецептов исходный материал остаётся на складе. Только после этого измеряется начальный баланс. У старого активного задания следующее назначение равно 2, следующая операция — 1; исторические квитанции не создаются. При загрузке тела 15 недостающие данные не достраиваются. + +Экспорт 13 и 14 вызывает чистую проверку представимости до первого байта. `UnsupportedLegacyState` сообщает о возвращаемом несовместимом грузе, приостановленной площадке и нулевом времени ожидающего завершения. Эти состояния полностью сохраняются в современной контрольной точке. Правила собственности и фаз проверяет общий `World::validate_custody`; кодек дополнительно проверяет геометрию, задания, ссылки, размеры и каноничность полей. + +[Исторический корпус](../../../tests/fixtures/custody_v14/README.md) содержит 13 подлинных контрольных точек схемы 2, созданных исходной сборкой `f6493e2`, и ожидаемые хеши 80 последующих тактов. Первый объединённый прогон Windows x64 под Wine подтвердил все такты на последовательном исполнителе и 2/6/12 потоках, точный экспорт 14, канонический цикл схемы 3 и продолжение после загрузки. Отдельно проверены отменённая одиночная доска и каменный блок, смешанный груз без места, частичный возврат, приостановленные кровать и станок, нулевой таймер, старые ссылки квитанций и отказ после аутентифицированного повреждения. [Проверки миграции](../../../tests/custody_migration_tests.cpp) · [Снимки с полной версией 15](../../../tests/snapshot_tests.cpp) + +Универсальные части продолжают использовать закреплённые Void Binary/Core/Crypto. Собственный формат и перенос игровых фаз относятся к S15; проверка замены библиотечным реестром остаётся связана с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Нативная Windows и сохранность после отключения питания остаются отдельными проверками. + ## Ошибки и восстановление | Ситуация | Требуемое поведение | diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index ce895e6..f2c4616 100644 --- a/engine/src/world_save.cpp +++ b/engine/src/world_save.cpp @@ -22,6 +22,16 @@ constexpr std::uint32_t save_version = 15; constexpr std::uint32_t last_legacy_footer_version = 8; constexpr std::size_t max_records = 1'000'000; constexpr std::size_t max_save_bytes = 128 * 1024 * 1024; +// The wire limit is independent of decoded C++ layout: an old byte-light agent +// now includes an execution/claim array. Cover every bounded top-level pool, +// nested vectors (maximum element expansion <4x wire), and the receipt ring. +// This is an accounting ceiling, never a reserve() request from untrusted input. +constexpr std::size_t record_pool_bytes = sizeof(Agent) + sizeof(WorkJob) + + sizeof(ResourceNode) + sizeof(Storage) + sizeof(ProductionOrder); +static_assert(record_pool_bytes <= (std::numeric_limits::max() - + 4 * max_save_bytes - custody_receipt_limit * (sizeof(CustodyReceipt) + 32)) / max_records); +constexpr std::size_t max_decode_allocation_bytes = max_records * record_pool_bytes + + 4 * max_save_bytes + custody_receipt_limit * (sizeof(CustodyReceipt) + 32); void require_save(bool condition, const char* error) { if (!condition) throw std::runtime_error(error); @@ -87,7 +97,7 @@ public: } void allocate(std::size_t count, std::size_t size) { - require_save(count <= max_save_bytes / size && + require_save(count <= max_decode_allocation_bytes / size && allocations_.consume_field(count * size).has_value(), "Save allocation budget exceeded."); } @@ -109,7 +119,7 @@ private: std::istream& stream_; std::size_t bytes_ = 0; // Legacy footers cover the signature and version, which are read first. - Void::Binary::DecodeBudget allocations_{{max_save_bytes, max_save_bytes, 64}}; + Void::Binary::DecodeBudget allocations_{{max_decode_allocation_bytes, max_decode_allocation_bytes, 64}}; bool legacy_footer_ = true; std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis; }; @@ -467,7 +477,7 @@ void result_fields(Archive& archive, Result& result) { archive.field(effect.item); archive.field(effect.count); require_save(effect.owner.kind != OwnerKind::None && effect.stack != 0 && - effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.count != 0, + effect.item > ItemType::None && effect.item <= ItemType::Loom, "Invalid custody result effect."); } for (std::size_t i = result.effect_count; i < result.effects.size(); ++i) { @@ -634,8 +644,8 @@ void WorldSaveCodec::validate(const World& world, bool modern) { 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 reserved_items(world.storages_.size()); - std::vector expected_cargo(world.production_orders_.size()); + std::vector reserved_items(modern ? 0 : world.storages_.size()); + std::vector expected_cargo(modern ? 0 : world.production_orders_.size()); std::vector bed_owners; for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { const auto& order = world.production_orders_[i]; diff --git a/tests/custody_migration_tests.cpp b/tests/custody_migration_tests.cpp index 230a3f9..c01439f 100644 --- a/tests/custody_migration_tests.cpp +++ b/tests/custody_migration_tests.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -49,7 +50,8 @@ std::size_t body_begin(std::string_view bytes) { } template void change(std::string& bytes, std::size_t offset, T value) { Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset)); - require(writer.writeLittle(value).has_value(), "mutation exceeded frame"); + if constexpr(std::is_enum_v) require(writer.writeLittle(static_cast>(value)).has_value(), "mutation exceeded frame"); + else require(writer.writeLittle(value).has_value(), "mutation exceeded frame"); } void rehash(std::string& bytes) { auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256); @@ -62,6 +64,37 @@ void reject(std::string bytes) { auto catalog = builtin_rule_packages(); require(!decode_checkpoint(bytes,*catalog,1,ExecutionMode::SerialReference), "authenticated malformed custody was accepted"); } +struct CustodyOffsets { + std::size_t extension, agent_state, agent_timer, receipts; + std::vector> entries; +}; +CustodyOffsets offsets(const World& world, const std::string& bytes) { + CustodyOffsets result{}; + const auto body=body_begin(bytes); + result.extension=body+raw(world,WorldSaveFormat::Current14).size(); + Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(),bytes.size()})); + require(reader.skip(body+109+static_cast(world.width())*world.height()+4+16).has_value(),"missing agent state"); + result.agent_state=reader.position(); + require(reader.skip(9).has_value(),"missing agent route"); + const auto route=reader.readLittle().value(); + require(reader.skip(static_cast(route)*8+8).has_value(),"missing agent timer"); + result.agent_timer=reader.position(); + std::size_t extension_size=24+world.production_orders().size()*(12*item_type_count+1)+64*item_type_count; + for(const auto& store:world.storages()) extension_size+=store.items.size()*8; + for(const auto& agent:world.agents()) extension_size+=8*item_type_count+9+ + (agent.execution?43+47*agent.execution->reservation_count:0); + result.receipts=result.extension+extension_size; + Void::Binary::Reader receipts(std::as_bytes(std::span{bytes.data(),bytes.size()}).subspan(result.receipts)); + const auto count=receipts.readLittle().value(); + for(std::uint32_t i=0;i().value();require(receipts.skip(request_size).has_value(),"bad request fixture"); + const auto response=result.receipts+receipts.position(); + const auto result_size=receipts.readLittle().value();require(receipts.skip(result_size).has_value(),"bad result fixture"); + result.entries.emplace_back(request,response); + } + return result; +} void legacy_reject(const World& world) { for (auto format : {WorldSaveFormat::Legacy13, WorldSaveFormat::Current14}) { std::ostringstream out(std::ios::binary); @@ -78,6 +111,10 @@ struct [[= Void::Testing::name("CustodyMigrationTests")]] CustodyMigrationTests [[= Void::Testing::tag("custody-migration")]] Test completed_receipts_keep_retired_stock_and_order_references(); [[= Void::Testing::tag("custody-migration")]] Test single_finished_material_and_partial_return_use_modern_format(); [[= Void::Testing::tag("custody-migration")]] Test suspended_sites_and_zero_completion_use_modern_format(); + [[= Void::Testing::tag("custody-mutation")]] Test authenticated_phase_and_receipt_mutations_are_rejected(); + [[= Void::Testing::tag("custody-mutation")]] Test retired_zero_effect_and_bounded_receipt_fields(); + [[= Void::Testing::tag("custody-migration")]] Test truncated_collection_counts_allocate_incrementally(); + [[= Void::Testing::tag("custody-mutation")]] Test full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals(); }; Test CustodyMigrationTests::authentic_historical_phases_keep_eighty_tick_projection() { for (const auto& original : custody_v14::fixtures) { @@ -211,4 +248,84 @@ Test CustodyMigrationTests::suspended_sites_and_zero_completion_use_modern_forma require(save(pending)==encoded,"pending zero timer did not roundtrip"); pending.world->step();pending.world->validate_custody(); } +Test CustodyMigrationTests::authenticated_phase_and_receipt_mutations_are_rejected() { + auto metadata=load(unhex(fixture("cabin-before-pickup").checkpoint)); + metadata.world->step(); + const auto good=save(metadata); const auto location=offsets(*metadata.world,good); + require(location.entries.size()==1,"pickup should produce one retained operation"); + const auto [request,result]=location.entries.front(); + auto wrong_transfer=good; + change(wrong_transfer,location.extension+16,std::uint64_t{3}); + change(wrong_transfer,result+3,std::uint64_t{2});reject(std::move(wrong_transfer)); + auto future=good;change(future,request+11,std::numeric_limits::max());reject(std::move(future)); + auto source=good;change(source,request+29,std::numeric_limits::max());reject(std::move(source)); + metadata.world=std::make_unique(43,20,8,1,ExecutionMode::SerialReference); + static_cast(metadata.world->spawn_agent({1,3})); + const auto idle=save(metadata); const auto idle_locations=offsets(*metadata.world,idle); + for(auto state:{AgentState::Working,AgentState::Gathering,AgentState::FetchingMaterials}) { + auto bad=idle;change(bad,idle_locations.agent_state,state);reject(std::move(bad)); + } + auto timer=idle;change(timer,idle_locations.agent_timer,std::uint32_t{1});reject(std::move(timer)); +} +Test CustodyMigrationTests::retired_zero_effect_and_bounded_receipt_fields() { + auto metadata=load(unhex(fixture("meal-eating").checkpoint)); + for(int tick=0;tick<8;++tick)metadata.world->step(); + const auto good=save(metadata); const auto location=offsets(*metadata.world,good); + require(!location.entries.empty(),"meal did not produce historical result"); + const auto [request,result]=location.entries.back(); + auto loaded=load(good); + const auto receipt=metadata.world->custody_receipts().back(); + require(receipt->result.effect_count==1&&receipt->result.effects[0].count==0,"terminal consumption lost retired zero-count effect"); + require(loaded.world->custody_request(receipt->request)==receipt->result,"zero-count historical effect changed after restore"); + auto oversized=good;change(oversized,request,std::uint16_t{1025});reject(std::move(oversized)); + auto too_many=good;change(too_many,location.receipts,std::uint32_t{4097});reject(std::move(too_many)); + auto bad_item=good;change(bad_item,result+2+12+17,ItemType::None);reject(std::move(bad_item)); + auto bad_owner=good;change(bad_owner,result+2+12,OwnerKind::None);reject(std::move(bad_owner)); + auto count=good;change(count,result+2+10,std::uint8_t{12});reject(std::move(count)); +} +Test CustodyMigrationTests::truncated_collection_counts_allocate_incrementally() { + auto original=unhex(fixture("cabin-before-pickup").checkpoint); + const auto begin=body_begin(original); + std::string body=original.substr(begin,original.size()-begin-32); + constexpr std::size_t agents_count=109+20*8; + body.resize(agents_count+4); + for(auto count:{1'000'000U,1'000'001U}) { + change(body,agents_count,count); + std::istringstream input(body,std::ios::binary); + bool failed=false; + try{static_cast(World::read_save(input,1,ExecutionMode::SerialReference));} + catch(const std::runtime_error&){failed=true;} + require(failed,"truncated huge agent declaration was accepted"); + } + // Many byte-light historical agents remain valid despite larger modern + // in-memory Agent records; the wire ceiling does not become a sizeof cap. + World world(43,3,3,1,ExecutionMode::SerialReference); + for(int i=0;i<2000;++i)static_cast(world.spawn_agent({1,1})); + const auto bytes=raw(world,WorldSaveFormat::Current14); + std::istringstream input(bytes,std::ios::binary); + auto loaded=World::read_save(input,1,ExecutionMode::SerialReference); + require(loaded->agents().size()==2000&&raw(*loaded,WorldSaveFormat::Current14)==bytes,"byte-light history failed migration"); +} +Test CustodyMigrationTests::full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals() { + auto metadata=load(unhex(fixture("meal-eating").checkpoint)); + metadata.world=std::make_unique(43,20,8,1,ExecutionMode::SerialReference); + const auto storage=metadata.world->add_storage({3,3},2050); + metadata.world->stock_storage(storage,ItemType::Wood,2050); + static_cast(metadata.world->spawn_agent({3,3})); + for(int i=0;i<2050;++i)metadata.world->queue_production({3,3},RecipeId::SawPlank); + for(int tick=0;tick<30000&&metadata.world->custody_receipts().size()<4096;++tick)metadata.world->step(); + require(metadata.world->custody_receipts().size()==4096,"real production did not fill global receipt ring"); + const auto remembered=metadata.world->custody_receipts().front(); + const auto full=save(metadata);auto loaded=load(full); + require(save(loaded)==full&&loaded.world->custody_receipts().size()==4096,"full receipt ring was truncated or reordered"); + require(full.size()<2*1024*1024,"typed receipt ring exceeded its proven wire budget"); + require(loaded.world->custody_request(remembered->request)==remembered->result,"full ring lost exact replay"); + auto conflicting=remembered->request;conflicting.destination=0; + require(loaded.world->custody_request(conflicting).status==CustodyStatus::Conflict,"exact request conflict was not detected"); + for(int tick=0;tick<30;++tick)loaded.world->step(); + require(loaded.world->custody_request(remembered->request).status==CustodyStatus::Stale,"evicted admission was eligible for replay"); + const auto wrapped=save(loaded);auto copy=load(wrapped); + require(save(copy)==wrapped&©.world->custody_request(remembered->request).status==CustodyStatus::Stale,"wrapped ring changed order or stale fence on restore"); +} + } // namespace diff --git a/tests/snapshot_tests.cpp b/tests/snapshot_tests.cpp index 84db0e8..a2fba43 100644 --- a/tests/snapshot_tests.cpp +++ b/tests/snapshot_tests.cpp @@ -28,7 +28,7 @@ static_assert(!std::is_copy_constructible_v); std::string bytes(const World& world) { std::ostringstream stream(std::ios::binary); - world.write_save(stream); + world.write_save(stream, WorldSaveFormat::Current15); return stream.str(); } From 6cc59b4ef564d084cd25e02dc1ee7d8edfd1088a Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:19:32 +0300 Subject: [PATCH 08/10] Verify peer cutoff while real owner commands and snapshots are pending --- docs/plan/systems/S16.md | 2 + tests/lan_tests.cpp | 91 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/docs/plan/systems/S16.md b/docs/plan/systems/S16.md index 1b21266..b327fe9 100644 --- a/docs/plan/systems/S16.md +++ b/docs/plan/systems/S16.md @@ -57,6 +57,8 @@ Для этого адаптера повторно проверены публичный `Void/Net/Socket.hpp`, Windows-ветка `src/Net/Socket.cpp` и `tests/standalone/Net/Socket.cpp` закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792`: UDP не реализован для Windows и не предоставляет игровую проверку представимости. Существующий TCP-транспорт остаётся прежним. Имущество и условие отказа принадлежат игровому адаптеру поверх операций [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8); новое универсальное сетевое средство не вводится. +Проверка S16-03 на интеграционной базе `5c309b2`: Windows x64 Release GCC 16.2 под Wine 11, 13/13 LAN и 15/15 клиента. Четыре новых LAN-сценария проверяют настоящий отменённый смешанный груз при полном складе, отказ входа, сохранение современного мира, завершение ранее допущенного приказа и отсечение следующего приказа в той же инкарнации, а также удаление недосланного снимка размером больше 64 КиБ на обоих путях хоста. Отдельно проходят 3/3 `wire` и 9/9 `lan-owner`. Старый скомпилированный клиент и новый адаптер обменялись приказами в обеих ролях. Оба старых корпуса формата 13 (738 386 и 393 857 байтов) совпали полностью на 1/2/6/12 исполнителях. Полный CTest этой базы выявил два отказа `production-command` и четыре отказа `production-controls` в параллельном срезе S04; их исправление и повторная общая проверка относятся к интеграции. Нативная Windows, MSVC и две физические машины этим прогоном не проверялись. + Пять проверок `--tag lan-owner` под Wine покрывают квитанции, заполнение очереди, совмещённые пакеты, переподключение при задержанной публикации, откат с незавершённой командой и отказ при несовместимых правилах. Отдельный двоичный клиент прототипа подтвердил обмен в обоих направлениях с новым хостом и гостем. Проверка физической Windows и двух машин остаётся частью сетевой приёмки. [Сценарии](../../../tests/lan_tests.cpp) Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6) diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index 162cff5..a471e73 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -189,6 +189,8 @@ struct LanTests : Void::Testing::Suite { [[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults(); [[= Void::Testing::tag("lan-owner")]] Test test_legacy_custody_refuses_handshake_and_preserves_modern_owner(); [[= Void::Testing::tag("lan-owner")]] Test test_standalone_custody_discards_queued_snapshot_and_command(); + [[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work(); + [[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_discards_queued_snapshot_before_admission(); }; Test LanTests::test_protocol_11_fixed_messages() { @@ -719,4 +721,93 @@ Test LanTests::test_standalone_custody_discards_queued_snapshot_and_command() { require(next.receipts.front().status == CommandStatus::Accepted); } +Test LanTests::test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work() { + CaptureGate gate; + RuntimeOptions options{.ticking = false}; + options.observer = [&](RuntimePhase phase) { gate.capture(phase); }; + auto initial = colony_checkpoint(); + initial.world = mixed_delivery(); + const auto production = initial.world->production_orders().front().id; + const auto resident = initial.world->agents().front().id; + SimulationRuntime runtime(std::move(initial), options); + auto release = Void::Scope::on_exit([&] { gate.release(); }); + LanSession host; + host.host(0, true); + RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16)); + const auto pump = [&] { host.poll_host(runtime); guest.poll(); }; + pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Custody guest did not join."); + const auto before = runtime.latest(); + const auto id = before->identity; + const CommandPayload accepted{CommandKind::AssignProfession, {}, + static_cast(Profession::Miner), {}, resident}; + gate.arm(); + guest.command(1, accepted.kind, {}, accepted.value, resident); + pump_until(pump, [&] { return gate.waiting(); }, "Guest work did not reach blocked capture."); + auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, + before->next_requests[0], CancelProductionPayload{production}}); + require(canceled.admission == RuntimeAdmission::Accepted); + // This later wire intent is already in TCP when cancellation publishes. + guest.command(2, CommandKind::AssignProfession, {}, static_cast(Profession::Builder), resident); + guest.poll(); + gate.release(); + require(canceled.completion.wait_for(3s) == std::future_status::ready); + require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted); + require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable()); + pump_until(pump, [&] { return guest.closed; }, "Incompatible runtime guest stayed connected."); + require(host.state() == LanState::Hosting && runtime.view().state == RuntimeState::Running); + require(guest.receipts.empty()); + const auto current = runtime.latest(); + require(current->next_requests[1] == 2 && current->world->next_command_sequence(2) == 2); + require(current->world->agents().front().profession == Profession::Miner); + const auto retained = runtime.lookup({2}, {command_envelope_version, id.world, id.session, id.city, + before->next_requests[1], accepted}); + require(retained && retained->status == DispatchStatus::Completed && retained->command_status == CommandStatus::Accepted); + require(encode_checkpoint(*current->world, id.world, id.city, *current->rules).has_value()); + + // A later compatible incarnation can reconnect; neither the retained work + // nor its old socket's reply leaks into the new connection. + auto ticket = runtime.begin_load(); + require(ticket.has_value()); + auto replacement = colony_checkpoint(); + auto installed = runtime.try_install(*ticket, replacement); + require(installed.admission == RuntimeAdmission::Accepted && installed.completion.wait_for(3s) == std::future_status::ready); + require(installed.completion.get().outcome == RuntimeOutcome::Completed); + RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16)); + pump_until([&] { host.poll_host(runtime); next.poll(); }, + [&] { return next.snapshot != nullptr; }, "Guest could not reconnect after custody cutoff."); + require(next.receipts.empty() && next.snapshot->next_command_sequence(2) == 1); +} + +Test LanTests::test_runtime_custody_discards_queued_snapshot_before_admission() { + auto initial = colony_checkpoint(); + initial.world = mixed_delivery(); + const auto production = initial.world->production_orders().front().id; + const auto resident = initial.world->agents().front().id; + for (int job = 0; job < 4096; ++job) static_cast(initial.world->add_job({20, 20}, 1)); + SimulationRuntime runtime(std::move(initial), {.ticking = false}); + LanSession host; + host.host(0, true); + RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16)); + guest.poll(); + pump_until([&] { host.poll_host(runtime); }, [&] { return host.state() == LanState::HostConnected; }, + "Queued-snapshot guest did not authenticate."); + guest.poll(); + require(!guest.input.empty() && !guest.snapshot); + const auto partial = guest.input.size(); + const auto before = runtime.latest(); + const auto id = before->identity; + auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, + before->next_requests[0], CancelProductionPayload{production}}); + require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready); + require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted); + guest.command(1, CommandKind::AssignProfession, {}, static_cast(Profession::Miner), resident); + guest.poll(); + pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; }, + "Guest receiving queued snapshot was not dropped."); + require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable()); + require(runtime.view().state == RuntimeState::Running && host.state() == LanState::Hosting); + require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty()); + require(runtime.latest()->next_requests[1] == 1 && runtime.latest()->world->next_command_sequence(2) == 1); +} + } // namespace From 13b4665ed2c6f5b351633ad8aa07f4ff2a19bbd1 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:23:51 +0300 Subject: [PATCH 09/10] Verify order selection through real window controls and modal replacement --- app/viewer_win32.cpp | 2 +- docs/plan/systems/S04.md | 14 ++++++ tests/production_commands_tests.cpp | 12 +++-- tests/production_controls_tests.cpp | 75 +++++++++++++++++++++++++---- 4 files changed, 89 insertions(+), 14 deletions(-) diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index 402e1dc..d665133 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -1878,7 +1878,7 @@ void manage_orders_at_cell(HWND window, settlement::GridPosition cell) { if (offset != 0 || more) AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); if (offset != 0) AppendMenuW(menu, MF_STRING, previous_page, L"← Предыдущие заказы"); if (more) AppendMenuW(menu, MF_STRING, next_page, L"Следующие заказы →"); - const auto selected = static_cast(TrackPopupMenu(menu, TPM_RETURNCMD | TPM_NONOTIFY | + const auto selected = static_cast(TrackPopupMenu(menu, TPM_RETURNCMD | TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, window, nullptr)); DestroyMenu(menu); if (!current_context()) { diff --git a/docs/plan/systems/S04.md b/docs/plan/systems/S04.md index 992036c..131d0ec 100644 --- a/docs/plan/systems/S04.md +++ b/docs/plan/systems/S04.md @@ -20,6 +20,20 @@ Проверки: [production_identity_tests.cpp](../../../tests/production_identity_tests.cpp), [checkpoint_tests.cpp](../../../tests/checkpoint_tests.cpp), [replay_tests.cpp](../../../tests/replay_tests.cpp). Срез проверен Windows x64 GCC 16.2 через Wine: 9 проверок `--tag production-id`, полный verbose CTest — 115 core и 4 LAN. Replay сравнивает тело 14 на каждом такте в serial/2/6/12, включая сохранение в пути и дырку в ID. Существующие двоичные эталоны формата 13 совпали во всех четырёх режимах: 738386 байт (`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`) и 393857 байт (`05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`). Сохранён настоящий checkpoint схемы 1, полученный старым encoder до изменения. Нативный запуск Windows и MSVC не выполнялись. Общие поручения, самостоятельные ID резервов, передача владения и отмена груза остаются последующими срезами S04/S06. +## Реализованный срез S04-02: отмена и возобновление + +Современная сессия принимает отдельные `CancelProductionPayload{ProductionId}` и `ResumeProductionPayload{ProductionId}`. Диспетчер проверяет доверенного игрока, мир, инкарнацию, город и номер запроса, затем передаёт действие в `World::cancel_production` / `resume_production`. Их физические эффекты принадлежат [S06](S06.md): адаптер команд не перемещает имущество самостоятельно. Современные действия доступны хозяину; гостю возвращается сохраняемый `Unauthorized`. Они не расширяют `CommandKind`, LAN 11 и прежнюю нумерацию `PlayerCommand`. + +Принятый результат и отказ сохраняются в существующем журнале с исходными тактом и ревизией. Точный повтор возвращает прежнюю квитанцию даже после удаления заказа. Другой ID или замена отмены на возобновление под тем же номером возвращает `Conflict`; новый успешный эффект увеличивает ревизию ровно один раз. Используется существующий контракт [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6) для журнала и [#8](https://git.faumaray.com/Void/Library/issues/8) для физического перехода. У закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792` нет готового игрового жизненного цикла заказа; условия замены журнала и передачи имущества сохраняются в этих задачах. + +В обычном окне игры команда находится в **Работы → Управление заказами…**. После выбора клетки меню показывает явные «Отменить» / «Возобновить», название работы, постоянный ID и координаты. Несколько заказов одной клетки остаются отдельными действиями; страницы содержат до 16 заказов с переходами вперёд и назад. Отмена предлагается для незавершённых активных работ, возобновление — для приостановленных. Завершённые итоговые объекты сохраняют прежний отказ `Busy` от ядра. Перед отправкой повторно проверяются актуальный заказ, полная идентичность сессии, поколение представления, начавшаяся смена мира, сетевое соединение и выбранный режим. Открытый снимок удерживается до закрытия меню. Диалог из прежней колонии не может отправить действие в новую; гость LAN 11 не видит инструмент и не может вызвать его синтетической командой окна. + +До квитанции интерфейс показывает ожидание подтверждения. Подтверждённая отмена сообщает о сохранении установленных частей и последующем возврате груза; возобновление сообщает о продолжении работы. У возвращающего материалы жителя видны действительный состав сумки и причина ожидания: отсутствие доступного склада, недостаток места, занятый склад либо предел учёта. Прежние `DemolishObject` / `MoveObject` сохраняют отказы при занятом источнике, складе и объекте. + +Проверки с реальным ядром: [production_commands_tests.cpp](../../../tests/production_commands_tests.cpp) — повтор принятых/отклонённых результатов, конфликты вариантов и ID, границы контекста и прав, отмена до получения/в пути/на площадке, ожидание полного склада и возврат всех материалов, продолжение частичной кровати и установленного станка, публикация runtime. [production_controls_tests.cpp](../../../tests/production_controls_tests.cpp) создаёт настоящее Win32-окно с Direct3D, выбирает клетку обычными сообщениями мыши, проходит меню клавиатурным вводом через `WM_TIMER`, проверяет квитанции обоих действий, выбор точного ID и доступ ко всем 35 заказам на одной клетке, смену мира во время меню, подключённого гостя LAN 11 и причину ожидания возвращающегося жителя. Каждый запуск окна использует отдельный временный каталог пользовательских данных. + +На объединённом ядре S06 и кодеке S15 выполнена сборка Windows x64 GCC 16.2; полный `ctest -V` под Wine 11 прошёл 4 исполняемых набора: 160 core, 4 LAN, 14 viewer-session и 6 Win32 controls. В предыдущем полном прогоне один существовавший тест восстановления после сбоя (`viewer_session_tests.cpp:363`) однократно не получил ожидаемый допуск синхронизации; отдельный повтор и итоговый полный прогон прошли. Нативные Windows и MSVC не проверялись. + ## Данные и владение | Новый объект | Ответственность | diff --git a/tests/production_commands_tests.cpp b/tests/production_commands_tests.cpp index 6bb24eb..a758aef 100644 --- a/tests/production_commands_tests.cpp +++ b/tests/production_commands_tests.cpp @@ -74,8 +74,8 @@ struct [[= Void::Testing::name("ProductionCommandsTests")]] ProductionCommandsTe Test ProductionCommandsTests::exact_results_and_conflicts_use_durable_ids() { World world(43, 32, 32, 1, ExecutionMode::SerialReference); - world.queue_production({8, 8}, RecipeId::BuildCabin); - world.queue_production({8, 8}, RecipeId::BuildCabin); + world.queue_production({8, 8}, RecipeId::SawPlank); + world.queue_production({8, 8}, RecipeId::SawPlank); const auto first = world.production_orders().front().id; const auto second = world.production_orders().back().id; CommandDispatcher dispatcher(identity()); @@ -219,6 +219,10 @@ Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identi require(world.find_production(id) && world.find_production(id)->suspended && world.find_production(id)->bed_stage == stage && !world.can_place_storage({9, 3}), "cancel removed installed progress or its occupied site"); + const auto suspended_cancel = envelope(dispatcher.next_request(host), CancelProductionPayload{id}); + const auto busy = dispatcher.dispatch(world, host, suspended_cancel); + require(busy.status == DispatchStatus::Completed && busy.command_status == CommandStatus::Busy && + dispatcher.dispatch(world, host, suspended_cancel) == busy); for (int tick = 0; tick < 5; ++tick) world.step(); const auto resume = envelope(dispatcher.next_request(host), ResumeProductionPayload{id}); const auto resumed = dispatcher.dispatch(world, host, resume); @@ -226,6 +230,8 @@ Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identi require(world.find_production(id) && !world.find_production(id)->suspended && world.find_production(id)->bed_stage == stage && dispatcher.dispatch(world, host, resume) == resumed && world.next_command_sequence(1) == sequence && !before_cancel->find_production(id)->suspended); + require(dispatcher.dispatch(world, host, suspended_cancel) == busy && !world.find_production(id)->suspended, + "old refused cancellation changed after the same durable order was resumed"); world.stock_storage(storage, bed ? ItemType::Cloth : ItemType::Flax, 2); step_until(world, [&] { return bed ? world.find_production(id)->state == JobState::Completed : world.find_storage(storage)->item_count(ItemType::Cloth) > 0; }); @@ -233,7 +239,7 @@ Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identi "resume charged for an already installed stage twice"); if (bed) { const auto refused = send(world, dispatcher, CancelProductionPayload{id}); - require(refused.command_status == CommandStatus::InvalidTarget, + require(refused.command_status == CommandStatus::Busy, "completed final bed accepted cancel"); } } diff --git a/tests/production_controls_tests.cpp b/tests/production_controls_tests.cpp index 0623007..6c07eeb 100644 --- a/tests/production_controls_tests.cpp +++ b/tests/production_controls_tests.cpp @@ -44,7 +44,8 @@ LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPAR } if (message == WM_TIMER && wparam == drive_timer) { if (++timer_attempts > 100) { - driver_error = "real popup did not accept the scripted input"; + driver_error = "real popup did not accept input: menus=" + std::to_string(observed_menus.size()) + + " remaining=" + std::to_string(steps.size()) + " active=" + std::to_string(active_menu != nullptr); KillTimer(window, drive_timer); EndMenu(); return 0; @@ -62,7 +63,13 @@ LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPAR EndMenu(); return 0; } - if (step.before_select) step.before_select(); + try { + if (step.before_select) step.before_select(); + } catch (const std::exception& error) { + driver_error = error.what(); + EndMenu(); + return 0; + } std::vector input; key(input, VK_HOME); for (int index = 0; index < target; ++index) { @@ -94,13 +101,14 @@ struct Window { auto rules = default_rules_manifest(); require(rules.has_value()); session = std::make_unique( - WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 1); + WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 2); world = session->world(); showing_title = true; has_session = true; lan = std::make_unique(); displayed_lan_state = LanState::Offline; placement_mode = PlacementMode::None; + camera = {}; placement_message.clear(); steps.clear(); observed_menus.clear(); @@ -163,17 +171,33 @@ struct Window { } require(placement_mode == PlacementMode::ManageOrders, "Работы menu did not activate order management"); } + void click_cell(GridPosition cell) { + RECT client{}; + GetClientRect(handle, &client); + const auto scale = camera.scale(); + const auto offset = camera.offset(); + POINT point{static_cast((client.right / 2.0 + (cell.x - cell.y) * tile_width / 2.0) * scale + offset.x), + static_cast((map_origin_y + (cell.x + cell.y) * tile_height / 2.0) * scale + offset.y)}; + require(map_cell(client, point) == cell, "normal map hit test did not select the target cell"); + auto screen = point; + ClientToScreen(handle, &screen); + SetCursorPos(screen.x, screen.y); + const auto coordinates = MAKELPARAM(point.x, point.y); + SendMessageW(handle, WM_LBUTTONDOWN, MK_LBUTTON, coordinates); + SendMessageW(handle, WM_LBUTTONUP, 0, coordinates); + } }; std::unique_ptr orders(unsigned count = 2) { auto result = std::make_unique(43, 32, 32, 1, ExecutionMode::SerialReference); - for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::BuildCabin); + for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::SawPlank); return result; } struct [[= Void::Testing::name("ProductionControlsTests")]] ProductionControlsTests : Void::Testing::Suite { [[= Void::Testing::tag("production-controls")]] Test real_work_menu_selects_exact_id_and_waits_for_receipt(); + [[= Void::Testing::tag("production-controls")]] Test real_resume_choice_keeps_installed_loom_and_waits_for_receipt(); [[= Void::Testing::tag("production-controls")]] Test every_order_remains_accessible_across_popup_pages(); [[= Void::Testing::tag("production-controls")]] Test replacement_during_popup_cannot_cancel_in_new_world(); [[= Void::Testing::tag("production-controls")]] Test legacy_guest_has_no_action_or_modern_submission(); @@ -185,11 +209,11 @@ Test ProductionControlsTests::real_work_menu_selects_exact_id_and_waits_for_rece const auto first = world->production_orders().front().id; const auto second = world->production_orders().back().id; fixture.activate_tool(); - fixture.menu({{2, {}}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); + fixture.menu({{2, {}}}, [&] { fixture.click_cell({8, 8}); }); require(world->find_production(second) && world->find_production(first) && placement_message.find(L"ожидает подтверждения") != std::wstring::npos, "UI forged success before a committed receipt"); - require(observed_menus.back().at(1).find(L"Отменить: Построить домик №" + std::to_wstring(second)) != std::wstring::npos && + require(observed_menus.back().at(1).find(L"Отменить: Распилить доску №" + std::to_wstring(second)) != std::wstring::npos && observed_menus.back().at(1).find(L"[9, 9]") != std::wstring::npos, "actual popup lost the order name, durable id or user-facing position"); fixture.pump_until([&] { return !world->find_production(second); }); @@ -201,12 +225,28 @@ Test ProductionControlsTests::every_order_remains_accessible_across_popup_pages( Window fixture(orders(35)); const auto last = world->production_orders().back().id; fixture.activate_tool(); - fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); + fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { fixture.click_cell({8, 8}); }); fixture.pump_until([&] { return !world->find_production(last); }); require(world->production_orders().size() == 34 && world->production_orders().front().id == 1); for (const auto& page : observed_menus) require(page.size() <= 19, "popup page exceeded its bounded display size"); } +Test ProductionControlsTests::real_resume_choice_keeps_installed_loom_and_waits_for_receipt() { + auto initial = orders(0); + initial->queue_production({8, 8}, RecipeId::WeaveCloth); + const auto id = initial->production_orders().front().id; + require(initial->cancel_production(id) == CommandStatus::Accepted && initial->find_production(id)->suspended); + Window fixture(std::move(initial)); + fixture.activate_tool(); + fixture.menu({{1, {}}}, [&] { fixture.click_cell({8, 8}); }); + require(world->find_production(id)->suspended && + placement_message.find(L"ожидает подтверждения") != std::wstring::npos); + require(observed_menus.back().at(0).find(L"Возобновить: Ткать ткань №" + std::to_wstring(id)) != std::wstring::npos); + fixture.pump_until([&] { return !world->find_production(id)->suspended; }); + require(world->find_production(id)->recipe == RecipeId::WeaveCloth && + placement_message.find(L"возобновлена") != std::wstring::npos && world->next_command_sequence(1) == 1); +} + Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_world() { for (const bool complete_replacement : {false, true}) { Window fixture(orders()); @@ -223,7 +263,7 @@ Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_worl } world = session->world(); } - }}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); + }}}, [&] { fixture.click_cell({8, 8}); }); fixture.pump_until([&] { return !session->changing_world(); }); const auto current = session->runtime().latest(); require(current->identity != opening->identity && current->next_requests[0] == 1 && @@ -235,8 +275,22 @@ Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_worl Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() { Window fixture(orders()); + const auto host_id = Void::Uuid::try_v4(); + const auto rules = default_rules_manifest(); + require(host_id.has_value() && rules.has_value()); + SimulationRuntime host_runtime(WorldCheckpoint{make_first_colony(2), *host_id, 1, *rules}, {.ticking = false}); + settlement::viewer::LanSession host_peer; + host_peer.host(0, true); session->enter_guest(); - lan->join("127.0.0.1", "000000", 1); + lan->join("127.0.0.1", host_peer.join_code(), host_peer.port()); + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (lan->state() != LanState::GuestConnected) { + host_peer.poll_host(host_runtime); + if (auto incoming = lan->poll_guest()) session->receive_guest(std::move(incoming)); + require(std::chrono::steady_clock::now() < deadline, "real legacy guest did not connect"); + std::this_thread::yield(); + } + world = session->world(); require(lan->is_guest() && session->guest()); const auto before = session->runtime().latest(); const auto menu = create_work_menu(); @@ -253,7 +307,8 @@ Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() } Test ProductionControlsTests::returning_resident_explains_wait_for_storage() { - auto initial = orders(1); + auto initial = orders(0); + initial->queue_production({8, 8}, RecipeId::BuildCabin); const auto storage = initial->add_storage({3, 3}, 5); initial->stock_storage(storage, ItemType::Plank, 3); initial->stock_storage(storage, ItemType::StoneBlock, 2); From 4f4c0380514d7d386d26123f14f845cfb2d78368 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:23:51 +0300 Subject: [PATCH 10/10] Keep generic job phases and checked ID allocation consistent across loads --- docs/plan/systems/S06.md | 19 +++++++++++++++ engine/src/custody.cpp | 14 +++++++++++ engine/src/world.cpp | 10 ++++++-- tests/custody_tests.cpp | 50 +++++++++++++++++++++++++++++++++++++++- 4 files changed, 90 insertions(+), 3 deletions(-) diff --git a/docs/plan/systems/S06.md b/docs/plan/systems/S06.md index 87a44d9..717411e 100644 --- a/docs/plan/systems/S06.md +++ b/docs/plan/systems/S06.md @@ -84,3 +84,22 @@ S06 владеет фактическими количествами, содер - Разделить и снова объединить стек с активным резервом. Количество и свойства сохраняются, ссылка остаётся разрешимой. - Повторить подтверждение торговли и прибытия в регион. История содержит одну завершённую операцию. - На контрольных 10 000 стеках и 2 000 работах измерить поиск поставщика, стоимость операций и объём сохранения через [S21](S21.md). Варианты предметов и логистики связать с [реестром паритета](../parity.md). + + +## Срез S06-03: владение грузом и восстановление исполнения + +Кандидат M01 хранит единственное количество у склада, жителя либо входного запаса `ProductionId`. `StackId` встроен в эту запись; требования рецепта используют отдельный `ItemAmount`. Получение целого стека в пустой слот сохраняет ID, разделение выдаёт ID новой части, объединение сохраняет ID получателя. Вместе с количеством меняются ссылки резервов; исторический исходный склад остаётся в материалах заказа до завершения. [Типы](../../../engine/include/settlement/core/custody.hpp) · [Реальные операции мира](../../../engine/src/custody.cpp) + +Обычные начисления, добыча, все существующие рецепты, монтаж, еда и разбор склада учитывают источники и расходы. На стройке материалы действительно принадлежат входу заказа до завершения стадии. Перед изменением количества готовятся ограниченные копии затронутых владельцев, арифметика, ID и место для квитанции; после проверки выполняется не бросающий commit. Используются `Void::Numeric` закреплённого `7b0fea6`; локальные счётчики и условные операции связаны с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки исчерпания, целого/частичного переноса, последней единицы, отмены и продолжения после загрузки на Windows x64. + +Назначение использует ключ `(AgentId, next_admission)`, дальнейший шаг — отдельное пространство `(TransferId, next_operation)`. Планировщик выдаёт ключ и применяет операцию; `custody_request` восстанавливает результат уже выданного запроса и отказывает неизвестному будущему ключу. Сохраняются последние 4096 квитанций в порядке применения с точными типизированными полями, результатами и выданными ID. Снимки разделяют только неизменяемые объекты квитанций; массив указателей и остальные данные копируются. Длина материалов ограничена пятью реальными единицами крупнейшего рецепта, включая пять разных складов. Этот локальный повтор также связан с [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6). + +`cancel_production` освобождает неполученные резервы, возвращает вход площадки жителю и удерживает исполнителя в `Returning` до сдачи всех видов груза. Частичная сдача и отсутствие свободного склада не уничтожают остаток. Уже смонтированное основание кровати или существующий ткацкий станок сохраняют ID и приостанавливаются; `resume_production` продолжает оставшуюся стадию. Завершённые конечные объекты не отменяются. При отказе завершения нулевой таймер остаётся нулевым; следующая проверка получает новый номер операции. `legacy_representable` не изменяет мир и запрещает экспорт несовместимых фаз до записи первого байта. Сериализацию Current15, миграцию старых тел и контрольную точку схемы 3 реализует связанный S15. + +Проверки `custody` охватывают реальный вход стройки, баланс расхода, разделение/объединение, пять источников, смешанный частичный возврат, приостановку/возобновление, неизменность снимка и истории, точный повтор/конфликт/будущий запрос/вытеснение, неверные ссылки и фазы, нулевые и максимальные счётчики, ожидающее завершение после загрузки. Отдельная проверка `custody-metrics` строит мир 512×512 с 500 жителями, 10 000 стеками в 1000 складах и 2000 заказами на распределённых площадках; второй вариант дополнительно создаёт 4096 квитанций реальными циклами ткачества. Измеряются 101 захват снимка и 21 последовательный такт с полной проверкой и кодированием Current15. Это синтетический сценарий, а не измерение рендеринга или сети. [Исполняемые проверки](../../../tests/custody_tests.cpp) + +Нативный Windows, MSVC и отказ системного аллокатора не проверялись. Числовые отказы и отказы вставки из-за неверных аргументов проверяются без изменения сериализуемого состояния. Готовность к публикации зависит от независимой проверки интегрированного M01; локальные изменения и измерения не означают разрешение на выпуск. + +Проверка интегрированного кандидата: GCC 16.2, Windows x64 Release, Wine 11; полный `ctest --output-on-failure -V` прошёл 3/3 исполняемых набора (162 core, 9 LAN, 10 viewer). Включены 14 проверок `custody`, отдельная метрика и исторические/повреждённые контрольные точки S15. Оба обычных старых корпуса повторно совпали побайтово на 1/2/6/12 исполнителях: 738386 и 393857 байт. + +В описанном синтетическом сценарии без квитанций захват снимка занял p50/p95 0,036/0,049 мс; с 4096 квитанциями — 0,046/0,053 мс. Полная проверка: 0,784/0,922 и 1,301/1,664 мс; кодирование Current15 с проверкой: 9,357/9,583 и 11,881/12,025 мс; 21 последовательный такт: 0,010/0,032 и 0,010/4,728 мс. Кодирование выполнялось в памяти без записи на диск. Размер Current15 — 924042 и 1335950 байт; исходное число стеков второго варианта — 10002 из-за ткацкого запаса. Один неизменяемый объект квитанции занимает 584 байта на проверенном ABI; 4096 объектов — 2392064 байта без служебных данных аллокатора и массива указателей. Измерения зависят от прогрева и нагрузки Wine; p95 снимка укладывается в исходный ориентир 5 мс, кодирование всего мира выполняется отдельно. Локальные журналы: `/tmp/stoneheart-milestones.xprJ2SVp/s06-custody-build-final.log`, `s06-custody-ctest-final.log` и `s06-custody-{trajectory,identity-compat}-compare.log`. diff --git a/engine/src/custody.cpp b/engine/src/custody.cpp index 0107e5e..64513b4 100644 --- a/engine/src/custody.cpp +++ b/engine/src/custody.cpp @@ -454,6 +454,9 @@ void World::validate_custody() const { } for (const auto& actor : agents_) add_inventory(actor.inventory, {OwnerKind::Resident, actor.id}); for (const auto& order : production_orders_) add_inventory(order.input, {OwnerKind::Production, order.id}); + std::unordered_map work_jobs; + std::set assigned_jobs; + for (const auto& job : jobs_) require(work_jobs.emplace(job.id, &job).second); std::unordered_map actors; std::unordered_map producers; for (const auto& actor : agents_) { @@ -473,9 +476,19 @@ void World::validate_custody() const { actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat && actor.state != AgentState::Gathering && actor.state != AgentState::FetchingMaterials && (actor.state != AgentState::Working || actor.current_job != 0)); + require(actor.storage_id == 0 && actor.haul_route.empty()); + if (actor.state == AgentState::Working || actor.state == AgentState::Travelling) { + const auto job = work_jobs.find(actor.current_job); + require(job != work_jobs.end() && job->second->state == JobState::InProgress && + assigned_jobs.insert(actor.current_job).second && actor.work_remaining > 0 && actor.work_remaining <= job->second->work_required); + if (actor.state == AgentState::Working) require(actor.position == job->second->position && actor.route_cursor == actor.route.size()); + else require(actor.route_cursor < actor.route.size() && actor.route.back() == job->second->position); + } else require(actor.current_job == 0 && actor.work_remaining == 0 && + (actor.state == AgentState::Idle || actor.state == AgentState::GoingToSleep || actor.state == AgentState::Sleeping)); continue; } const auto& execution = *actor.execution; + require(actor.current_job == 0 && !actor.resting_on_ground); require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second && execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 && execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination); @@ -577,6 +590,7 @@ void World::validate_custody() const { for (const auto& stack : store.items) require(reserved[store.id][static_cast(stack.type) - 1] == stack.reserved); } for (const auto& node : resource_nodes_) require(workers[node.id] == node.reserved_workers); + for (const auto& job : jobs_) require((job.state == JobState::InProgress) == assigned_jobs.contains(job.id)); for (const auto& order : production_orders_) { require(order.state <= JobState::Completed); if (order.state == JobState::InProgress) { diff --git a/engine/src/world.cpp b/engine/src/world.cpp index d473855..2ae304f 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -429,12 +429,15 @@ AgentId World::spawn_agent(GridPosition position) { if (!is_walkable(position)) { throw std::invalid_argument("agent spawn cell is not walkable"); } - const AgentId id = next_agent_id_++; + const AgentId id = next_agent_id_; + const auto successor = Void::Numeric::checked_add(id, AgentId{1}); + if (id == 0 || !successor) throw std::overflow_error("resident identities exhausted"); Agent agent; agent.id = id; agent.position = position; if (hunger_enabled_) agent.hunger = initial_hunger(id); agents_.push_back(std::move(agent)); + next_agent_id_ = *successor; return id; } @@ -445,8 +448,11 @@ JobId World::add_job(GridPosition position, std::uint32_t work_required) { if (work_required == 0) { throw std::invalid_argument("work duration must be greater than zero"); } - const JobId id = next_job_id_++; + const JobId id = next_job_id_; + const auto successor = Void::Numeric::checked_add(id, JobId{1}); + if (id == 0 || !successor) throw std::overflow_error("job identities exhausted"); jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available}); + next_job_id_ = *successor; return id; } diff --git a/tests/custody_tests.cpp b/tests/custody_tests.cpp index 5c089a2..89842f1 100644 --- a/tests/custody_tests.cpp +++ b/tests/custody_tests.cpp @@ -34,6 +34,7 @@ struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::S [[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance(); [[= Void::Testing::tag("custody")]] Test rejects_missing_execution_and_claims(); [[= Void::Testing::tag("custody")]] Test persistent_counter_boundaries_and_pending_completion(); + [[= Void::Testing::tag("custody")]] Test resident_and_job_id_allocation_is_checked(); [[= Void::Testing::tag("custody")]] Test modern_roundtrip_cancel_and_exact_retry(); [[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics(); }; @@ -175,7 +176,10 @@ Test CustodyTests::snapshot_metrics() { for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast(j) != ItemType::Berries) w.stock_storage(store, static_cast(j), 1); } - while (w.production_orders().size() < 2000) w.queue_production({3, 3}, RecipeId::SawPlank); + while (w.production_orders().size() < 2000) { + const auto i = static_cast(w.production_orders().size()); + w.queue_production({i % 100 + 3, i / 100 + 10}, RecipeId::SawPlank); + } w.validate_custody(); std::vector samples; for (int i = 0; i < 101; ++i) { @@ -187,6 +191,21 @@ Test CustodyTests::snapshot_metrics() { std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size() << " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << " raw15_bytes=" << modern.str().size() << " receipt_object_bytes=" << sizeof(CustodyReceipt) << '\n'; + std::vector validation, serialization, advancement; + for (int i = 0; i < 21; ++i) { + auto begin = std::chrono::steady_clock::now(); w.validate_custody(); + validation.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); + begin = std::chrono::steady_clock::now(); std::ostringstream encoded; w.write_save(encoded, WorldSaveFormat::Current15); + serialization.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); + begin = std::chrono::steady_clock::now(); w.step(); + advancement.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); + } + w.validate_custody(); + for (auto pair : {std::pair{"validate", &validation}, std::pair{"serialize15", &serialization}, std::pair{"step", &advancement}}) { + std::sort(pair.second->begin(), pair.second->end()); + std::cout << "custody metrics initial_receipts=" << (full ? 4096 : 0) << ' ' << pair.first + << "_ms_p50=" << (*pair.second)[10] << " p95=" << (*pair.second)[19] << '\n'; + } } } @@ -255,4 +274,33 @@ Test CustodyTests::persistent_counter_boundaries_and_pending_completion() { std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference); ticks(*resumed, 1); require(resumed->agents()[0].work_remaining == 0, "restored pending completion decremented zero"); } + +Test CustodyTests::resident_and_job_id_allocation_is_checked() { + const auto bytes = [](const World& world) { std::ostringstream stream; world.write_save(stream, WorldSaveFormat::Current15); return stream.str(); }; + for (std::size_t kind = 0; kind < 2; ++kind) { + World empty(1, 10, 10, 1, ExecutionMode::SerialReference); + auto encoded = bytes(empty); + // Signature/version/seed/dimensions, five u64 counters, hunger flag. + const std::size_t offset = 28 + 5 * 8 + 1 + kind * 8; + for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = static_cast(255); + std::istringstream input(encoded); auto restored = World::read_save(input, 1, ExecutionMode::SerialReference); + const auto before = bytes(*restored); + bool exhausted = false; + try { if (kind == 0) (void)restored->spawn_agent({1,1}); else (void)restored->add_job({1,1}, 1); } + catch (const std::overflow_error&) { exhausted = true; } + require(exhausted && bytes(*restored) == before, "exhausted resident/job allocation changed state"); + for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = 0; + bool rejected = false; try { std::istringstream zero(encoded); auto ignored = World::read_save(zero,1,ExecutionMode::SerialReference); } + catch (const std::runtime_error&) { rejected = true; } + require(rejected, "zero resident/job counter accepted"); + const auto valid_before = bytes(empty); + try { if (kind == 0) (void)empty.spawn_agent({-1,-1}); else (void)empty.add_job({1,1}, 0); } + catch (const std::invalid_argument&) {} + require(bytes(empty) == valid_before, "invalid insertion consumed ID"); + } + World idle(1, 10, 10, 1, ExecutionMode::SerialReference); (void)idle.spawn_agent({1,1}); + const_cast(idle.agents()[0]).work_remaining = 1; + bool rejected = false; try { idle.validate_custody(); } catch (const std::runtime_error&) { rejected = true; } + require(rejected, "idle timer escaped phase validation"); +} }