From de38aff2ff538505d89599b382538b63960196f7 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 21:20:21 +0300 Subject: [PATCH] Resolve and fingerprint versioned game rule packages --- CMakeLists.txt | 10 +- docs/agent-workflow/tasks/S19-01.md | 48 +++ docs/plan/systems/S19.md | 6 + .../settlement/core/rules_manifest.hpp | 103 +++++ engine/src/rules_manifest.cpp | 394 ++++++++++++++++++ tests/rules_tests.cpp | 226 ++++++++++ 6 files changed, 783 insertions(+), 4 deletions(-) create mode 100644 docs/agent-workflow/tasks/S19-01.md create mode 100644 engine/include/settlement/core/rules_manifest.hpp create mode 100644 engine/src/rules_manifest.cpp create mode 100644 tests/rules_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index becaf96..8233612 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,7 +23,8 @@ function(add_void_library) set(BUILD_SHARED_LIBS OFF) set(VOID_ENABLE_TESTING OFF) set(VOID_ENABLE_BENCHMARKS OFF) - set(VOID_ENABLED_MODULES Binary Core) + set(VOID_ENABLED_MODULES Algorithms Binary Core Crypto Data Text) + set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON) if(BUILD_TESTING) list(APPEND VOID_ENABLED_MODULES Testing) endif() @@ -39,6 +40,7 @@ find_package(Threads REQUIRED) add_library(settlement_core engine/src/first_colony.cpp + engine/src/rules_manifest.cpp engine/src/worker_pool.cpp engine/src/world.cpp engine/src/world_save.cpp @@ -49,10 +51,10 @@ target_include_directories(settlement_core ${CMAKE_CURRENT_SOURCE_DIR}/engine/include ) -target_compile_features(settlement_core PUBLIC cxx_std_20) +target_compile_features(settlement_core PUBLIC cxx_std_23) target_link_libraries(settlement_core PUBLIC Threads::Threads - PRIVATE Void::Binary Void::Core + PRIVATE Void::Algorithms Void::Binary Void::Core Void::Crypto Void::Data Void::Text ) if(MSVC) @@ -104,7 +106,7 @@ else() endif() if(BUILD_TESTING) - add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/test_main.cpp) + add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/rules_tests.cpp tests/test_main.cpp) target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing) add_test(NAME settlement_core_tests COMMAND settlement_core_tests) diff --git a/docs/agent-workflow/tasks/S19-01.md b/docs/agent-workflow/tasks/S19-01.md new file mode 100644 index 0000000..be307f8 --- /dev/null +++ b/docs/agent-workflow/tasks/S19-01.md @@ -0,0 +1,48 @@ +# Resolve a frozen set of game rule packages from actual manifests + +Task ID: S19-01 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Exclusive worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 8d2870a. Main working directory belongs to another task. Exact Void pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. M01-P2/R2 and preflight F2 confirm the implementation seam. + +## 2. Objective and deliverables +Implement S19-W01 typed game rule manifest loading, validation and reproducible identity, with real JSON inputs and CTest coverage. Supply the public interface S15/S01 will freeze into worlds. + +## 3. Scope and non-goals +Only S19/M01 core support and its tests/build wiring; no Lua, UI, save codec or network yet. Plan requires diagnostics usable by a caller and frozen identity for explicit world selection. + +## 4. Files to inspect +Inspect docs/plan/systems/S19.md, M01, CMakeLists.txt, exact upstream Void/Data/StrictJson.hpp, Void/Text/Semver.hpp, Void/Algorithms/Graph.hpp, Void/Crypto/Crypto.hpp and respective tests. Source root for pin is /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/rules_manifest.hpp; engine/src/rules_manifest.cpp; tests/rules_tests.cpp; CMakeLists.txt +You are not alone. Use ONLY your specified worktree with explicit workdir/absolute paths, verify root/HEAD before edits. Other systems have separate checkouts. Do not edit the main checkout, change shared Serena project, stage, commit, push or spawn. Root integrates CMake. + +## 6. Implementation or investigation approach +Bound byte count and node/dependency/depth limits before/while using Void::Json::Strict. Manifest schema v1 includes namespaced package ID, exact strict SemVer, named dependencies and version constraints, exclusive providers, definitions with stable qualified IDs and references. For M01 definitions live in the JSON file (no external untrusted file paths/scripts). Resolve transitive deps from installed packages (one installed version per ID), detect duplicates/missing/range incompatibility/cycles/exclusive-provider clashes/unresolved definition refs. Use Void::Semver, Algorithms, Crypto and StrictJson. Sort sets, include definition content in SHA256, recompute digests; preserve semantically ordered data. Write diagnostics containing package/source and field. Provide usable base game package(s) for later startup via an explicit built-in loader or factory in owned code. Avoid implementing generic library alternatives. + +## 7. Interfaces and data contracts +NEW public RulePackage source + immutable RulesManifest (sorted frozen package ID/exact version/SHA256 and manifest fingerprint), loading/resolution via settlement/core/rules_manifest.hpp. Expose a base default and real catalog/selection input. Keep public types independent of upstream internals where practical. Define schema, duplicate/unknown semantics and source error handling in a short header comment. Send final signatures to root ASAP for S15/runtime. + +## 8. Dependencies and integration +No upstream dependency update. Validate SHA-256 pure C++ fallback on Windows; use modules Data, Text, Algorithms, Crypto and transitive deps only. Matching generic candidate issue draft for reusable resolver is root-owned; game-specific capability names and decisions use published primitives. Root handles cross-system consumers and remote tracker outcome. + +## 9. Edge cases security and performance +Reject unknown schema/invalid UTF-8/duplicate fields, malformed IDs/versions, digest spoofing, large files and excessive fan-out. Range semantics need explicit prerelease policy. SemVer == ignores build metadata, so frozen exact identities compare normalized full string and 32-byte digest. Stable diagnostic path relevant to user-provided files. No third-party game content. + +## 10. Acceptance criteria +1. Load and select from at least two meaningful original package documents with deps; reversing input/definition sets produces identical frozen identity. 2. Content, exact version or build change alters fingerprint. 3. Missing dependency, bad range, duplicate, cycle, exclusive conflict, dangling references and malformed/oversize JSON give actionable diagnostics. 4. Windows target/test suites pass and API ready to persist/compare a manifest. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/rules-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Add a discoverable Void suite with tag rules. Check actual diff and log timings. + +## 12. Constraints and stop conditions +Escalate any required new generic mechanism or library incompatibility. No network writes, no Git mutations, no competing branch/source edits. Stop after two unsuccessful repairs of one issue and send original failures. + +## 13. Authorization and decisions +User authorized full plan, milestone/system branches and pushes. The root handles those; preflight READY for S19 under these limits. + +## 14. Return format +Return S19-01 status, actual files and API, schema/canonicalization decisions, failure coverage, commands/results, unverified limits, integration notes for runtime/save. Do not spawn. diff --git a/docs/plan/systems/S19.md b/docs/plan/systems/S19.md index f323ef7..1f36517 100644 --- a/docs/plan/systems/S19.md +++ b/docs/plan/systems/S19.md @@ -4,6 +4,12 @@ Статус — план реализации. Игрок выбирает совместимый набор механик при создании мира. Собственные материалы и моды подключаются через документированный формат, а состояние этой конфигурации сохраняется вместе с колонией. Основа вводится в [M01](../milestones/M01.md), используется игровыми системами и публикуется для авторов в [M10](../milestones/M10.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md) +## Первый исполняемый срез M01 + +`load_rule_package` читает ограниченный по размеру JSON с версией схемы, определениями, ссылками и зависимостями. `resolve_rules` для выбранных модулей вычисляет транзитивный состав, проверяет конфликты и возвращает точные версии с SHA-256. Порядок обхода файлов не меняет идентичность. Для проверки запустить `settlement_core_tests.exe --tag rules`. [Публичный интерфейс](../../../engine/include/settlement/core/rules_manifest.hpp) · [Реализация](../../../engine/src/rules_manifest.cpp) · [Проверки](../../../tests/rules_tests.cpp) + +На Windows x64 под Wine прошли 9 сценариев для манифестов. Разбор JSON, версии, граф и хеш использованы из закреплённой VoidLibrary. Для замены локального разрешения наборов библиотечным сервисом повторить проверки транзитивных зависимостей, перестановок, конфликтов и идентичности. [Запрос в Void/Library](https://git.faumaray.com/Void/Library/issues/4) + ## Исходное состояние Предметы, профессии, рецепты и команды прототипа определяются C++-типами, а стартовая партия создаётся кодом. В проверенной CMake-конфигурации подключены `Void::Binary`, `Void::Core` и `Void::Testing`. Скриптовый runtime в этот перечень не входит. План вводит новые определения контента и границу расширения. [Текущая конфигурация сборки](../../../CMakeLists.txt) diff --git a/engine/include/settlement/core/rules_manifest.hpp b/engine/include/settlement/core/rules_manifest.hpp new file mode 100644 index 0000000..3625b3f --- /dev/null +++ b/engine/include/settlement/core/rules_manifest.hpp @@ -0,0 +1,103 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { + +using RulesDigest = std::array; + +struct RulesDiagnostic { + std::string package; + std::string source; + std::string field; + std::string message; + std::size_t byte_offset = 0; +}; + +struct RulesLimits { + std::size_t package_bytes = 256 * 1024; + std::size_t catalog_bytes = 4 * 1024 * 1024; + std::size_t packages = 128; + std::size_t definitions = 1024; + std::size_t dependencies = 64; + std::size_t references = 64; + std::size_t json_depth = 24; + std::size_t json_nodes = 16384; +}; + +struct RuleDefinition { + std::string id; + std::string kind; + std::string canonical_data; + std::vector references; +}; + +struct FrozenRulePackage { + std::string id; + std::string exact_version; + RulesDigest content_sha256{}; + bool operator==(const FrozenRulePackage&) const = default; +}; + +class RulesManifest; +struct RulePackageData; + +// Schema 1 requires schema/id/version/dependencies/exclusive_capabilities/definitions. +// Package IDs use lower-case dot-separated segments. Definition IDs and capabilities +// use package:local-name. Each definition has id/kind/data/references, where data is +// integer-valued strict JSON. Unknown metadata fields are errors. Set-like arrays are +// sorted; arrays inside data retain order. Sources are diagnostic labels, never paths +// to execute or open. Only one installed version of each package ID is allowed. +class RulePackage { +public: + [[nodiscard]] const FrozenRulePackage& identity() const noexcept; + [[nodiscard]] std::span definitions() const noexcept; + [[nodiscard]] std::string_view canonical_json() const noexcept; + +private: + explicit RulePackage(std::shared_ptr data); + std::shared_ptr data_; + friend std::expected load_rule_package( + std::string_view, std::string_view, const RulesLimits&); + friend std::expected resolve_rules( + std::span, std::span, const RulesLimits&); +}; + +class RulesManifest { +public: + [[nodiscard]] std::span packages() const noexcept { return packages_; } + [[nodiscard]] const RulesDigest& fingerprint() const noexcept { return fingerprint_; } + // Schema-tagged canonical UTF-8 bytes shared by persistence and handshake callers. + [[nodiscard]] std::string_view canonical_json() const noexcept { return canonical_json_; } + bool operator==(const RulesManifest&) const = default; + +private: + RulesManifest(std::vector, RulesDigest, std::string); + std::vector packages_; + RulesDigest fingerprint_{}; + std::string canonical_json_; + friend std::expected resolve_rules( + std::span, std::span, const RulesLimits&); +}; + +[[nodiscard]] std::expected load_rule_package( + std::string_view source, std::string_view json, const RulesLimits& limits = {}); + +// Resolves selected IDs and their transitive dependencies. Prerelease dependencies +// require an exact constraint equal to that full version, optionally prefixed by '='. +// Content digests are computed from the parsed content and never trusted from input. +[[nodiscard]] std::expected resolve_rules( + std::span available, std::span selected, + const RulesLimits& limits = {}); + +[[nodiscard]] std::expected default_rules_manifest(); +[[nodiscard]] std::string rules_digest_hex(const RulesDigest& digest); + +} // namespace settlement diff --git a/engine/src/rules_manifest.cpp b/engine/src/rules_manifest.cpp new file mode 100644 index 0000000..8d7933c --- /dev/null +++ b/engine/src/rules_manifest.cpp @@ -0,0 +1,394 @@ +#include "settlement/core/rules_manifest.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace settlement { + +namespace json = Void::Json::Strict; + +struct RuleDependency { + std::string id; + std::string range; +}; + +struct RulePackageData { + FrozenRulePackage identity; + std::string source; + std::string canonical_json; + std::vector dependencies; + std::vector capabilities; + std::vector definitions; +}; + +namespace { + +struct InvalidRules { + RulesDiagnostic diagnostic; +}; + +struct Context { + std::string package; + std::string source; + + [[noreturn]] void fail(std::string field, std::string message, std::size_t offset = 0) const { + throw InvalidRules{{package, source, std::move(field), std::move(message), offset}}; + } +}; + +bool local_name(std::string_view text) { + if (text.empty() || text.size() > 128 || text.front() < 'a' || text.front() > 'z') return false; + return std::all_of(text.begin(), text.end(), [](char ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-'; + }); +} + +bool package_id(std::string_view text) { + if (text.size() > 128 || text.find('.') == std::string_view::npos) return false; + for (;;) { + const auto separator = text.find('.'); + if (!local_name(text.substr(0, separator))) return false; + if (separator == std::string_view::npos) return true; + text.remove_prefix(separator + 1); + } +} + +bool qualified_id(std::string_view text) { + const auto separator = text.find(':'); + return separator != std::string_view::npos && package_id(text.substr(0, separator)) && + local_name(text.substr(separator + 1)); +} + +void input_budget(std::string_view text, const RulesLimits& limits, const Context& context) { + if (text.size() > limits.package_bytes) context.fail("$", "package byte limit exceeded"); + if (limits.json_depth == 0 || limits.json_depth > 64) context.fail("$", "JSON depth limit must be 1..64"); + // Count lexical nodes (including object keys) before the JSON parser allocates. + std::size_t nodes = 0; + bool in_string = false; + bool escaped = false; + bool scalar = false; + for (char ch : text) { + if (in_string) { + if (escaped) escaped = false; + else if (ch == '\\') escaped = true; + else if (ch == '"') in_string = false; + continue; + } + if (ch == '"') { + in_string = true; + scalar = false; + ++nodes; + } else if (ch == '{' || ch == '[') { + scalar = false; + ++nodes; + } else if (ch == '}' || ch == ']' || ch == ',' || ch == ':' || + ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t') { + scalar = false; + } else if (!scalar) { + scalar = true; + ++nodes; + } + if (nodes > limits.json_nodes) context.fail("$", "JSON node limit exceeded"); + } +} + +template +const T& as(const json::Value& value, const Context& context, std::string_view field) { + const auto* result = std::get_if(&value.value); + if (!result) context.fail(std::string(field), "unexpected JSON type"); + return *result; +} + +const json::Value::Object& object(const json::Value& value, const Context& context, + std::string_view field, std::initializer_list names) { + const auto& result = as(value, context, field); + for (const auto& [key, ignored] : result) { + static_cast(ignored); + if (std::find(names.begin(), names.end(), key) == names.end()) { + context.fail(std::string(field) + "." + key, "unknown field"); + } + } + for (auto key : names) { + if (!result.contains(key)) context.fail(std::string(field) + "." + std::string(key), "required field is missing"); + } + return result; +} + +std::string text(const json::Value& value, const Context& context, const std::string& field) { + const auto& result = as(value, context, field); + if (result.size() > 256) context.fail(field, "metadata string limit exceeded"); + return result; +} + +std::vector id_set(const json::Value& value, const Context& context, + const std::string& field, std::size_t maximum) { + const auto& entries = as(value, context, field); + if (entries.size() > maximum) context.fail(field, "entry limit exceeded"); + std::vector result; + for (const auto& entry : entries) { + auto id = text(entry, context, field); + if (!qualified_id(id)) context.fail(field, "expected a package:local-name identifier"); + result.push_back(std::move(id)); + } + std::sort(result.begin(), result.end()); + if (std::adjacent_find(result.begin(), result.end()) != result.end()) context.fail(field, "duplicate identifier"); + return result; +} + +json::Value string_array(const std::vector& values) { + json::Value::Array result; + for (const auto& value : values) result.push_back(json::Value{value}); + return json::Value{std::move(result)}; +} + +std::string serialize(const json::Value& value, const Context& context, std::size_t depth) { + auto result = json::serialize(value, depth); + if (!result) context.fail("$", result.error().message, result.error().offset); + return std::move(*result); +} + +RulesDigest digest(std::string_view bytes, const Context& context) { + auto result = Void::Crypto::sha256(bytes); + if (!result || result->size() != 32) context.fail("sha256", "SHA-256 computation failed"); + RulesDigest output{}; + std::copy(result->begin(), result->end(), output.begin()); + return output; +} + +std::shared_ptr parse_package(std::string_view source, std::string_view bytes, + const RulesLimits& limits) { + Context context{"", std::string(source)}; + input_budget(bytes, limits, context); + auto parsed = json::parse(bytes, json::ParseOptions{limits.json_depth, false}); + if (!parsed) context.fail("$", parsed.error().message, parsed.error().offset); + const auto& root = object(*parsed, context, "$", + {"schema", "id", "version", "dependencies", "exclusive_capabilities", "definitions"}); + auto result = std::make_shared(); + result->source = source; + context.package = text(root.at("id"), context, "id"); + if (!package_id(context.package)) context.fail("id", "expected a lower-case dot-separated package ID"); + result->identity.id = context.package; + if (as(root.at("schema"), context, "schema") != 1) context.fail("schema", "unsupported package schema"); + const auto version = Void::Semver::parse_strict(text(root.at("version"), context, "version")); + if (!version) context.fail("version", "invalid strict SemVer"); + result->identity.exact_version = version->to_string(); + const auto& dependencies = as(root.at("dependencies"), context, "dependencies"); + if (dependencies.size() > limits.dependencies) context.fail("dependencies", "dependency limit exceeded"); + for (std::size_t i = 0; i < dependencies.size(); ++i) { + const auto field = "dependencies[" + std::to_string(i) + "]"; + const auto& dep = object(dependencies[i], context, field, {"id", "version"}); + auto id = text(dep.at("id"), context, field + ".id"); + auto range = text(dep.at("version"), context, field + ".version"); + if (!package_id(id)) context.fail(field + ".id", "invalid dependency package ID"); + if (range.empty() || !Void::Semver::VersionRange::parse(range)) context.fail(field + ".version", "invalid version range"); + result->dependencies.push_back({std::move(id), std::move(range)}); + } + std::sort(result->dependencies.begin(), result->dependencies.end(), [](const auto& a, const auto& b) { return a.id < b.id; }); + if (std::adjacent_find(result->dependencies.begin(), result->dependencies.end(), + [](const auto& a, const auto& b) { return a.id == b.id; }) != result->dependencies.end()) { + context.fail("dependencies", "duplicate dependency package ID"); + } + result->capabilities = id_set(root.at("exclusive_capabilities"), context, "exclusive_capabilities", limits.definitions); + const auto& definitions = as(root.at("definitions"), context, "definitions"); + if (definitions.size() > limits.definitions) context.fail("definitions", "definition limit exceeded"); + std::map canonical_definitions; + for (std::size_t i = 0; i < definitions.size(); ++i) { + const auto field = "definitions[" + std::to_string(i) + "]"; + const auto& entry = object(definitions[i], context, field, {"id", "kind", "data", "references"}); + RuleDefinition definition; + definition.id = text(entry.at("id"), context, field + ".id"); + if (!qualified_id(definition.id) || !definition.id.starts_with(context.package + ":")) { + context.fail(field + ".id", "definition must belong to its package namespace"); + } + definition.kind = text(entry.at("kind"), context, field + ".kind"); + constexpr std::string_view kinds[]{"item", "profession", "recipe", "material", "event"}; + if (std::find(std::begin(kinds), std::end(kinds), definition.kind) == std::end(kinds)) context.fail(field + ".kind", "unknown definition kind"); + definition.references = id_set(entry.at("references"), context, field + ".references", limits.references); + definition.canonical_data = serialize(entry.at("data"), context, limits.json_depth); + auto canonical = entry; + canonical.at("references") = string_array(definition.references); + if (!canonical_definitions.emplace(definition.id, json::Value{std::move(canonical)}).second) { + context.fail(field + ".id", "duplicate definition ID"); + } + result->definitions.push_back(std::move(definition)); + } + std::sort(result->definitions.begin(), result->definitions.end(), [](const auto& a, const auto& b) { return a.id < b.id; }); + json::Value::Array canonical_dependencies; + for (const auto& dep : result->dependencies) canonical_dependencies.push_back(json::Value{json::Value::Object{ + {"id", json::Value{dep.id}}, {"version", json::Value{dep.range}}}}); + json::Value::Array canonical_definition_array; + for (auto& [id, value] : canonical_definitions) { + static_cast(id); + canonical_definition_array.push_back(std::move(value)); + } + auto canonical = root; + canonical.at("version") = json::Value{result->identity.exact_version}; + canonical.at("dependencies") = json::Value{std::move(canonical_dependencies)}; + canonical.at("exclusive_capabilities") = string_array(result->capabilities); + canonical.at("definitions") = json::Value{std::move(canonical_definition_array)}; + result->canonical_json = serialize(json::Value{std::move(canonical)}, context, limits.json_depth); + result->identity.content_sha256 = digest(result->canonical_json, context); + return result; +} + +} // namespace + +RulePackage::RulePackage(std::shared_ptr data) : data_(std::move(data)) {} +const FrozenRulePackage& RulePackage::identity() const noexcept { return data_->identity; } +std::span RulePackage::definitions() const noexcept { return data_->definitions; } +std::string_view RulePackage::canonical_json() const noexcept { return data_->canonical_json; } + +RulesManifest::RulesManifest(std::vector packages, RulesDigest fingerprint, std::string bytes) + : packages_(std::move(packages)), fingerprint_(fingerprint), canonical_json_(std::move(bytes)) {} + +std::expected load_rule_package(std::string_view source, std::string_view bytes, + const RulesLimits& limits) { + try { + return RulePackage{parse_package(source, bytes, limits)}; + } catch (const InvalidRules& error) { + return std::unexpected{error.diagnostic}; + } +} + +std::string rules_digest_hex(const RulesDigest& hash) { + constexpr char alphabet[] = "0123456789abcdef"; + std::string result; + result.reserve(hash.size() * 2); + for (auto byte : hash) { + const auto value = std::to_integer(byte); + result.push_back(alphabet[value >> 4]); + result.push_back(alphabet[value & 15]); + } + return result; +} + +std::expected resolve_rules(std::span available, + std::span selected, + const RulesLimits& limits) { + try { + Context context{"", "catalog"}; + if (available.size() > limits.packages || selected.size() > limits.packages) context.fail("packages", "package count limit exceeded"); + std::map catalog; + std::size_t byte_count = 0; + for (const auto& package : available) { + const auto& data = *package.data_; + context = {data.identity.id, data.source}; + // Revalidate limits at the resolver boundary, including callers using a + // package parsed with more permissive limits. + if (data.canonical_json.size() > limits.catalog_bytes - std::min(byte_count, limits.catalog_bytes)) { + context.fail("packages", "catalog byte limit exceeded"); + } + static_cast(parse_package(data.source, data.canonical_json, limits)); + byte_count += data.canonical_json.size(); + if (!catalog.emplace(data.identity.id, &data).second) context.fail("id", "duplicate installed package ID"); + } + std::set chosen; + std::vector pending(selected.begin(), selected.end()); + std::sort(pending.begin(), pending.end()); + if (pending.empty()) context.fail("selected", "select at least one package"); + if (std::adjacent_find(pending.begin(), pending.end()) != pending.end()) context.fail("selected", "duplicate selected package ID"); + for (std::size_t i = 0; i < pending.size(); ++i) { + const auto id = pending[i]; + context = {id, "selection"}; + if (!package_id(id)) context.fail("selected", "invalid selected package ID"); + if (chosen.contains(id)) continue; + const auto found = catalog.find(id); + if (found == catalog.end()) context.fail("selected", "package is not installed: " + id); + const auto& package = *found->second; + context = {id, package.source}; + chosen.insert(id); + for (const auto& dep : package.dependencies) { + const auto dependency = catalog.find(dep.id); + if (dependency == catalog.end()) context.fail("dependencies." + dep.id, "required package is not installed"); + const auto version = Void::Semver::parse_strict(dependency->second->identity.exact_version); + const auto range = Void::Semver::VersionRange::parse(dep.range); + const bool prerelease_allowed = version->pre_release.empty() || dep.range == version->to_string() || dep.range == "=" + version->to_string(); + if (!prerelease_allowed || !range->contains(*version)) context.fail("dependencies." + dep.id, "installed version does not satisfy the constraint"); + if (!chosen.contains(dep.id)) pending.push_back(dep.id); + } + } + std::vector packages; + std::map indices; + for (const auto& id : chosen) { + indices.emplace(id, packages.size()); + packages.push_back(catalog.at(id)); + } + std::vector> edges(packages.size()); + for (std::size_t i = 0; i < packages.size(); ++i) { + for (const auto& dep : packages[i]->dependencies) edges[indices.at(dep.id)].push_back(i); + } + Void::Algorithms::WorkLimits graph_limits; + graph_limits.max_vertices = limits.packages; + const auto topology = Void::Algorithms::topological_order(Void::Algorithms::AdjacencyView{edges}, graph_limits); + if (!topology) { + std::string message = topology.error().message; + for (auto index : topology.error().cycle) message += " " + packages.at(index)->identity.id; + context.fail("dependencies", message); + } + std::map providers; + std::set definition_ids; + for (const auto* package : packages) { + context = {package->identity.id, package->source}; + for (const auto& capability : package->capabilities) { + auto [provider, inserted] = providers.emplace(capability, package->identity.id); + if (!inserted) context.fail("exclusive_capabilities", "conflicting provider for " + capability + ": " + provider->second); + } + for (const auto& definition : package->definitions) definition_ids.insert(definition.id); + } + for (const auto* package : packages) { + context = {package->identity.id, package->source}; + std::set accessible{package->identity.id}; + std::vector dependencies{package->identity.id}; + for (std::size_t i = 0; i < dependencies.size(); ++i) { + for (const auto& dep : catalog.at(dependencies[i])->dependencies) { + if (accessible.insert(dep.id).second) dependencies.push_back(dep.id); + } + } + for (const auto& definition : package->definitions) { + for (const auto& reference : definition.references) { + const auto owner = reference.substr(0, reference.find(':')); + if (!accessible.contains(owner) || !definition_ids.contains(reference)) { + context.fail("definitions." + definition.id + ".references", "unresolved or undeclared reference: " + reference); + } + } + } + } + std::vector frozen; + json::Value::Array array; + for (const auto* package : packages) { + frozen.push_back(package->identity); + array.push_back(json::Value{json::Value::Object{ + {"id", json::Value{package->identity.id}}, + {"version", json::Value{package->identity.exact_version}}, + {"sha256", json::Value{rules_digest_hex(package->identity.content_sha256)}}}}); + } + auto canonical = serialize(json::Value{json::Value::Object{ + {"schema", json::Value{std::int64_t{1}}}, {"packages", json::Value{std::move(array)}}}}, context, 8); + const auto fingerprint = digest(canonical, context); + return RulesManifest{std::move(frozen), fingerprint, std::move(canonical)}; + } catch (const InvalidRules& error) { + return std::unexpected{error.diagnostic}; + } +} + +std::expected default_rules_manifest() { + constexpr std::string_view core = R"({"schema":1,"id":"settlement.core","version":"1.0.0","dependencies":[],"exclusive_capabilities":["settlement.core:materials"],"definitions":[{"id":"settlement.core:wood","kind":"item","data":{"stack_limit":64},"references":[]},{"id":"settlement.core:stone","kind":"item","data":{"stack_limit":64},"references":[]}]})"; + constexpr std::string_view colony = R"({"schema":1,"id":"settlement.colony","version":"1.0.0","dependencies":[{"id":"settlement.core","version":"1.0.0"}],"exclusive_capabilities":["settlement.colony:construction"],"definitions":[{"id":"settlement.colony:board","kind":"recipe","data":{"output_count":1,"work_ticks":8},"references":["settlement.core:wood"]}]})"; + auto first = load_rule_package("builtin/core", core); + if (!first) return std::unexpected{first.error()}; + auto second = load_rule_package("builtin/colony", colony); + if (!second) return std::unexpected{second.error()}; + const std::array packages{*first, *second}; + const std::array selected{std::string{"settlement.colony"}}; + return resolve_rules(packages, selected); +} + +} // namespace settlement diff --git a/tests/rules_tests.cpp b/tests/rules_tests.cpp new file mode 100644 index 0000000..6dc33c3 --- /dev/null +++ b/tests/rules_tests.cpp @@ -0,0 +1,226 @@ +#include "settlement/core/rules_manifest.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace settlement; +using Void::Testing::Test; + +void require(bool condition, std::string_view message) { + if (!condition) throw std::runtime_error(std::string(message)); +} + +template +T checked(std::expected result) { + if (!result) { + const auto& d = result.error(); + throw std::runtime_error(d.source + " " + d.package + " " + d.field + " " + d.message); + } + return std::move(*result); +} + +std::string package(std::string_view id, std::string_view definitions = "[]", + std::string_view dependencies = "[]", std::string_view capabilities = "[]", + std::string_view version = "1.0.0") { + return "{\"schema\":1,\"id\":\"" + std::string(id) + "\",\"version\":\"" + std::string(version) + + "\",\"dependencies\":" + std::string(dependencies) + ",\"exclusive_capabilities\":" + + std::string(capabilities) + ",\"definitions\":" + std::string(definitions) + "}"; +} + +constexpr std::string_view wood = R"({"id":"game.core:wood","kind":"item","data":{"stack_limit":64},"references":[]})"; +constexpr std::string_view stone = R"({"id":"game.core:stone","kind":"item","data":{"stack_limit":32},"references":[]})"; +constexpr std::string_view board = R"([{"id":"game.colony:board","kind":"recipe","data":{"work_ticks":8},"references":["game.core:wood","game.core:stone"]}])"; +constexpr std::string_view core_dependency = R"([{"id":"game.core","version":">=1.0.0 <2.0.0"}])"; + +RulePackage load(std::string_view json) { return checked(load_rule_package("fixture.json", json)); } + +RulesManifest resolve(std::vector packages, std::vector selected = {"game.colony"}, + const RulesLimits& limits = {}) { + return checked(resolve_rules(packages, selected, limits)); +} + +void parse_error(std::string_view json, std::string_view field, const RulesLimits& limits = {}) { + const auto result = load_rule_package("bad-package.json", json, limits); + require(!result, "invalid package was accepted"); + require(result.error().source == "bad-package.json" && result.error().field.find(field) != std::string::npos && + !result.error().message.empty(), "parser diagnostic lost source or field"); +} + +void resolution_error(const std::vector& packages, const std::vector& selected, + std::string_view field, const RulesLimits& limits = {}) { + const auto result = resolve_rules(packages, selected, limits); + require(!result, "invalid package set was accepted"); + require(result.error().field.find(field) != std::string::npos && !result.error().source.empty() && + !result.error().message.empty(), "resolver diagnostic lost source or field"); +} + +struct [[= Void::Testing::name("RulesTests")]] RulesTests : Void::Testing::Suite { + [[= Void::Testing::tag("rules")]] Test test_manifest_identity_is_independent_of_discovery_order(); + [[= Void::Testing::tag("rules")]] Test test_frozen_identity_covers_content_and_exact_versions(); + [[= Void::Testing::tag("rules")]] Test test_transitive_selection_and_unselected_packages(); + [[= Void::Testing::tag("rules")]] Test test_invalid_dependencies_and_provider_conflicts(); + [[= Void::Testing::tag("rules")]] Test test_definition_references_and_namespaces(); + [[= Void::Testing::tag("rules")]] Test test_strict_json_schema_and_input_budgets(); + [[= Void::Testing::tag("rules")]] Test test_catalog_and_model_limits(); + [[= Void::Testing::tag("rules")]] Test test_prerelease_policy(); + [[= Void::Testing::tag("rules")]] Test test_builtin_default_and_known_digest(); +}; + +Test RulesTests::test_manifest_identity_is_independent_of_discovery_order() { + const auto core_a = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]")); + const auto core_b = load(package("game.core", "[" + std::string(stone) + "," + std::string(wood) + "]")); + const auto tools = load(package("game.tools")); + const auto colony_a = load(package("game.colony", board, + R"([{"id":"game.core","version":">=1.0.0 <2.0.0"},{"id":"game.tools","version":"1.0.0"}])", + R"(["game.colony:weather","game.colony:building"])")); + std::string reversed_board(board); + const auto refs = reversed_board.find("\"game.core:wood\",\"game.core:stone\""); + reversed_board.replace(refs, std::string("\"game.core:wood\",\"game.core:stone\"").size(), + "\"game.core:stone\",\"game.core:wood\""); + const auto colony_b = load(package("game.colony", reversed_board, + R"([{"id":"game.tools","version":"1.0.0"},{"id":"game.core","version":">=1.0.0 <2.0.0"}])", + R"(["game.colony:building","game.colony:weather"])")); + const auto first = resolve({core_a, colony_a, tools}); + const auto second = resolve({tools, colony_b, core_b}); + require(first == second, "permuting package, definition, capability or reference order changed identity"); + require(first.packages().size() == 3 && first.packages()[0].id == "game.colony" && + first.packages()[1].id == "game.core", "frozen packages are not sorted by ID"); + require(core_a.canonical_json() == core_b.canonical_json(), "canonical package bytes changed with input order"); + const auto reloaded = load(core_a.canonical_json()); + require(reloaded.identity() == core_a.identity(), "canonical document did not round-trip"); +} + +Test RulesTests::test_frozen_identity_covers_content_and_exact_versions() { + const auto source = package("game.core", "[" + std::string(wood) + "]"); + const auto original = resolve({load(source)}, {"game.core"}); + const auto compare = [&](std::string changed) { + require(resolve({load(changed)}, {"game.core"}) != original, "simulation change kept the frozen fingerprint"); + }; + auto modified = source; + modified.replace(modified.find("64"), 2, "65"); + compare(modified); + compare(package("game.core", "[" + std::string(wood) + "]", "[]", "[]", "1.0.1")); + compare(package("game.core", "[" + std::string(wood) + "]", "[]", "[]", "1.0.0+build2")); + compare(package("game.core")); + modified = source; + modified.replace(modified.find("game.core:wood"), 14, "game.core:logs"); + compare(modified); + const auto a = resolve({load(package("game.core", R"([{"id":"game.core:path","kind":"event","data":[1,2],"references":[]}])"))}, {"game.core"}); + const auto b = resolve({load(package("game.core", R"([{"id":"game.core:path","kind":"event","data":[2,1],"references":[]}])"))}, {"game.core"}); + require(a != b, "ordered definition data was sorted as a set"); +} + +Test RulesTests::test_transitive_selection_and_unselected_packages() { + const auto core = load(package("game.core")); + const auto colony = load(package("game.colony", "[]", core_dependency)); + const auto ui = load(package("game.ui", "[]", R"([{"id":"game.colony","version":"1.0.0"}])")); + const auto broken_unselected = load(package("game.unselected", "[]", R"([{"id":"game.missing","version":"1.0.0"}])")); + const auto first = resolve({ui, colony, core, broken_unselected}, {"game.ui"}); + const auto second = resolve({core, ui, colony}, {"game.core", "game.ui"}); + require(first == second && first.packages().size() == 3, "transitive dependency closure changed with selection order"); + resolution_error({core}, {"game.absent"}, "selected"); + resolution_error({core}, {}, "selected"); + resolution_error({core}, {"game.core", "game.core"}, "selected"); +} + +Test RulesTests::test_invalid_dependencies_and_provider_conflicts() { + const auto core = load(package("game.core")); + resolution_error({core, core}, {"game.core"}, "id"); + resolution_error({load(package("game.colony", "[]", core_dependency))}, {"game.colony"}, "dependencies"); + const auto incompatible = load(package("game.colony", "[]", R"([{"id":"game.core","version":"^2.0.0"}])")); + resolution_error({core, incompatible}, {"game.colony"}, "dependencies.game.core"); + const auto back_edge = load(package("game.core", "[]", R"([{"id":"game.colony","version":"*"}])")); + resolution_error({back_edge, load(package("game.colony", "[]", core_dependency))}, {"game.colony"}, "dependencies"); + const auto provider_a = load(package("game.first", "[]", "[]", R"(["game.core:terrain"])")); + const auto provider_b = load(package("game.second", "[]", "[]", R"(["game.core:terrain"])")); + resolution_error({provider_a, provider_b}, {"game.first", "game.second"}, "exclusive_capabilities"); + parse_error(package("game.colony", "[]", R"([{"id":"game.core","version":"=>broken"}])"), "version"); + parse_error(package("game.colony", "[]", R"([{"id":"game.core","version":"*"},{"id":"game.core","version":"*"}])"), "dependencies"); +} + +Test RulesTests::test_definition_references_and_namespaces() { + const auto core = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]")); + const auto colony = load(package("game.colony", board, core_dependency)); + static_cast(resolve({core, colony})); + resolution_error({load(package("game.core")), colony}, {"game.colony"}, "references"); + resolution_error({core, load(package("game.colony", board))}, {"game.core", "game.colony"}, "references"); + parse_error(package("game.colony", "[" + std::string(wood) + "]"), ".id"); + parse_error(package("game.core", "[" + std::string(wood) + "," + std::string(wood) + "]"), ".id"); + parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"native","data":{},"references":[]}])"), ".kind"); + parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"item","data":{},"references":["not-qualified"]}])"), ".references"); +} + +Test RulesTests::test_strict_json_schema_and_input_budgets() { + const auto valid = package("game.core"); + parse_error("{\"schema\":1,\"schema\":1}", "$"); + parse_error(valid + " false", "$"); + parse_error("{\"id\":\"\xff\"}", "$"); + parse_error("{}", "$"); + auto modified = valid; + modified.insert(1, "\"sha256\":\"forged\","); + parse_error(modified, "sha256"); + modified = valid; + modified.replace(modified.find("\"schema\":1"), 10, "\"schema\":2"); + parse_error(modified, "schema"); + parse_error(package("Game"), "id"); + parse_error(package("game.core", "[]", "[]", "[]", "v1.0.0"), "version"); + parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"item","data":0.5,"references":[]}])"), "$"); + RulesLimits limits; + limits.package_bytes = valid.size() - 1; + parse_error(valid, "$", limits); + limits = {}; + limits.json_nodes = 4; + parse_error(valid, "$", limits); + limits = {}; + limits.json_depth = 2; + parse_error(package("game.core", "[" + std::string(wood) + "]"), "$", limits); +} + +Test RulesTests::test_catalog_and_model_limits() { + const auto core = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]")); + const auto colony = load(package("game.colony", board, core_dependency)); + RulesLimits limits; + limits.packages = 1; + resolution_error({core, colony}, {"game.colony"}, "packages", limits); + limits = {}; + limits.catalog_bytes = 2; + resolution_error({core, colony}, {"game.colony"}, "packages", limits); + limits = {}; + limits.definitions = 1; + resolution_error({core}, {"game.core"}, "definitions", limits); + parse_error(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"), "definitions", limits); + limits = {}; + limits.dependencies = 0; + parse_error(package("game.colony", board, core_dependency), "dependencies", limits); + limits = {}; + limits.references = 1; + parse_error(package("game.colony", board, core_dependency), "references", limits); +} + +Test RulesTests::test_prerelease_policy() { + const auto prerelease = load(package("game.core", "[]", "[]", "[]", "1.0.0-preview+test")); + const auto broad = load(package("game.colony", "[]", R"([{"id":"game.core","version":"*"}])")); + resolution_error({prerelease, broad}, {"game.colony"}, "dependencies"); + const auto exact = load(package("game.colony", "[]", R"([{"id":"game.core","version":"=1.0.0-preview+test"}])")); + const auto result = resolve({prerelease, exact}); + require(result.packages()[1].exact_version == "1.0.0-preview+test", "prerelease exact identity was lost"); +} + +Test RulesTests::test_builtin_default_and_known_digest() { + const auto first = checked(default_rules_manifest()); + const auto second = checked(default_rules_manifest()); + require(first == second && first.packages().size() == 2, "default rules were not reproducible"); + const auto empty = load(package("game.core")); + require(rules_digest_hex(empty.identity().content_sha256) == "f6d1f704ccbb3ec707d2e1ba7b0db27dab8494b7787eeee10f1449dabee1477a", "package SHA-256 differs from the canonical-byte known vector"); + require(empty.definitions().empty(), "empty package gained a definition"); +} + +} // namespace