Compare commits
123
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59eb683404 | ||
|
|
9a55167201 | ||
|
|
a6989f35ad | ||
|
|
f2ff1ce0e8 | ||
|
|
41748ac964 | ||
|
|
129d7f204b | ||
|
|
37a08d4d48 | ||
|
|
14987b240e | ||
|
|
2017e5685a | ||
|
|
c40d9b2ae2 | ||
|
|
17389b23d7 | ||
|
|
6fdf5a90f7 | ||
|
|
3f1817a285 | ||
|
|
15887d5613 | ||
|
|
51311ca104 | ||
|
|
69ce32c2b6 | ||
|
|
cd75eab191 | ||
|
|
f60375a9f3 | ||
|
|
519e4e72a7 | ||
|
|
5dd0e35093 | ||
|
|
77781a5f1f | ||
|
|
22420e9fe2 | ||
|
|
c812df8c0b | ||
|
|
89bbb81317 | ||
|
|
ba00651b45 | ||
|
|
7a7ff32e14 | ||
|
|
13dc673088 | ||
|
|
4bac17df83 | ||
|
|
aaa0f82527 | ||
|
|
e7046a92a1 | ||
|
|
447a1cfd2b | ||
|
|
ee1eca7571 | ||
|
|
e5464784f5 | ||
|
|
1ca481b8f9 | ||
|
|
e60dc355f0 | ||
|
|
74aadb27b2 | ||
|
|
2ba4b3ffc4 | ||
|
|
86b5fb35f1 | ||
|
|
e348a4291d | ||
|
|
d613b73e1f | ||
|
|
120db6cfa0 | ||
|
|
6d1123e172 | ||
|
|
f6402eb80f | ||
|
|
d13a232f29 | ||
|
|
070db7864e | ||
|
|
67fba6e3df | ||
|
|
a34733797b | ||
|
|
6279a60bf7 | ||
|
|
431ee602c7 | ||
|
|
596b491acf | ||
|
|
7d5fbeb349 | ||
|
|
9bc52ea5c9 | ||
|
|
8522f910b3 | ||
|
|
22111440c9 | ||
|
|
c183de1952 | ||
|
|
13b4665ed2 | ||
|
|
4f4c038051 | ||
|
|
f34dcc5053 | ||
|
|
0d71bcf5d8 | ||
|
|
e26b9c2936 | ||
|
|
a47e850bb4 | ||
|
|
6cc59b4ef5 | ||
|
|
ccd50ec40c | ||
|
|
a76bf87787 | ||
|
|
9e20f99a66 | ||
|
|
3c7cc3ce2c | ||
|
|
5c309b2a9f | ||
|
|
a1c65119a2 | ||
|
|
83a57cbe46 | ||
|
|
b5f75d3c13 | ||
|
|
1cf8bd08fc | ||
|
|
455630fb39 | ||
|
|
539cea0608 | ||
|
|
e9e7e8276e | ||
|
|
6c6f4e7857 | ||
|
|
f1b8d41bb4 | ||
|
|
ef980af125 | ||
|
|
048268a27e | ||
|
|
1b57183939 | ||
|
|
e5d01a4ecd | ||
|
|
4f42488d54 | ||
|
|
5a64a27d17 | ||
|
|
180506d414 | ||
|
|
37fb6a897d | ||
|
|
f6493e2d1c | ||
|
|
66af7c5bb9 | ||
|
|
3c997ed236 | ||
|
|
e6a01bedcc | ||
|
|
db0a8720a6 | ||
|
|
b7f18c094b | ||
|
|
535424196e | ||
|
|
a8cd7bb415 | ||
|
|
2a3ec924de | ||
|
|
9a248c31ac | ||
|
|
275956395d | ||
|
|
2a5df1a18b | ||
|
|
aa4e271ab4 | ||
|
|
eef69caa0e | ||
|
|
09545bfe85 | ||
|
|
60154bd5f0 | ||
|
|
4ba64f7e62 | ||
|
|
ce814767fb | ||
|
|
a063894637 | ||
|
|
c2d9d8d51a | ||
|
|
8260e09be7 | ||
|
|
512c9ef033 | ||
|
|
8c4c1fe235 | ||
|
|
7979fff16c | ||
|
|
a4cf99c265 | ||
|
|
ce3a7dc937 | ||
|
|
2224299589 | ||
|
|
db4ac304b8 | ||
|
|
15da3f4336 | ||
|
|
1fa37d8e87 | ||
|
|
4921dffe71 | ||
|
|
645abefac5 | ||
|
|
fd17a2f3ff | ||
|
|
3844ebb205 | ||
|
|
84a78eff8a | ||
|
|
cf0cc2f32c | ||
|
|
68f91a236a | ||
|
|
de38aff2ff | ||
|
|
8d2870a6f8 |
No files matched your search
+73
-6
@@ -23,7 +23,8 @@ function(add_void_library)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
set(VOID_ENABLE_TESTING OFF)
|
||||
set(VOID_ENABLE_BENCHMARKS OFF)
|
||||
set(VOID_ENABLED_MODULES Binary Core)
|
||||
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Math Text Time)
|
||||
set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON)
|
||||
if(BUILD_TESTING)
|
||||
list(APPEND VOID_ENABLED_MODULES Testing)
|
||||
endif()
|
||||
@@ -38,8 +39,19 @@ 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
|
||||
engine/src/command_dispatcher.cpp
|
||||
engine/src/first_colony.cpp
|
||||
engine/src/inventory_transaction.cpp
|
||||
engine/src/rules_manifest.cpp
|
||||
engine/src/save_service_win32.cpp
|
||||
engine/src/simulation_runtime.cpp
|
||||
engine/src/voxel_navigation.cpp
|
||||
engine/src/worker_pool.cpp
|
||||
engine/src/voxel_region.cpp
|
||||
engine/src/world.cpp
|
||||
engine/src/world_save.cpp
|
||||
)
|
||||
@@ -49,10 +61,10 @@ target_include_directories(settlement_core
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/engine/include
|
||||
)
|
||||
|
||||
target_compile_features(settlement_core PUBLIC cxx_std_20)
|
||||
target_compile_features(settlement_core PUBLIC cxx_std_23)
|
||||
target_link_libraries(settlement_core
|
||||
PUBLIC Threads::Threads
|
||||
PRIVATE Void::Binary Void::Core
|
||||
PUBLIC Threads::Threads Void::Async Void::Core Void::Time
|
||||
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Math Void::Text
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
@@ -81,16 +93,26 @@ target_link_libraries(settlement_lan
|
||||
)
|
||||
|
||||
enable_language(RC)
|
||||
add_library(settlement_client STATIC app/viewer_session.cpp)
|
||||
target_include_directories(settlement_client PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
|
||||
target_link_libraries(settlement_client PUBLIC settlement_core)
|
||||
add_library(settlement_voxel_scene STATIC app/voxel_scene.cpp)
|
||||
target_include_directories(settlement_voxel_scene PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
|
||||
target_link_libraries(settlement_voxel_scene PUBLIC settlement_core Void::Math)
|
||||
add_executable(settlement_viewer WIN32
|
||||
app/d3d_scene_win32.cpp
|
||||
app/viewer_win32.cpp
|
||||
app/house_icons.rc
|
||||
)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan settlement_voxel_scene user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
if(MSVC)
|
||||
target_compile_options(settlement_voxel_scene PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_client PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_lan PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
|
||||
else()
|
||||
target_compile_options(settlement_voxel_scene PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_compile_options(settlement_client PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_compile_options(settlement_lan PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_link_options(settlement_viewer PRIVATE -municode)
|
||||
target_compile_options(settlement_viewer PRIVATE
|
||||
@@ -104,11 +126,56 @@ else()
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_executable(settlement_core_tests tests/core_tests.cpp tests/test_main.cpp)
|
||||
add_executable(settlement_core_tests
|
||||
tests/checkpoint_tests.cpp
|
||||
tests/checkpoint_file_tests.cpp
|
||||
tests/custody_tests.cpp
|
||||
tests/custody_migration_tests.cpp
|
||||
tests/core_tests.cpp
|
||||
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
|
||||
tests/rules_tests.cpp
|
||||
tests/runtime_tests.cpp
|
||||
tests/save_service_tests.cpp
|
||||
tests/session_tests.cpp
|
||||
tests/snapshot_tests.cpp
|
||||
tests/voxel_navigation_tests.cpp
|
||||
tests/voxel_region_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)
|
||||
|
||||
add_executable(settlement_lan_tests tests/lan_tests.cpp tests/test_main.cpp)
|
||||
target_link_libraries(settlement_lan_tests PRIVATE settlement_lan Void::Testing)
|
||||
add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests)
|
||||
|
||||
add_executable(settlement_viewer_frame_smoke
|
||||
tests/viewer_frame_smoke.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
|
||||
target_link_libraries(settlement_viewer_frame_smoke PRIVATE settlement_client settlement_lan settlement_voxel_scene
|
||||
user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
add_test(NAME settlement_viewer_frame_smoke COMMAND settlement_viewer_frame_smoke)
|
||||
set_tests_properties(settlement_viewer_frame_smoke PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
|
||||
|
||||
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 settlement_voxel_scene
|
||||
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)
|
||||
|
||||
add_executable(settlement_voxel_scene_tests
|
||||
tests/voxel_scene_tests.cpp tests/test_main.cpp app/d3d_scene_win32.cpp)
|
||||
target_link_libraries(settlement_voxel_scene_tests PRIVATE settlement_voxel_scene Void::Testing d3d11 d3dcompiler)
|
||||
add_test(NAME settlement_voxel_scene_tests COMMAND settlement_voxel_scene_tests)
|
||||
set_tests_properties(settlement_voxel_scene_tests PROPERTIES TIMEOUT 90)
|
||||
endif()
|
||||
@@ -67,6 +67,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 -VoidLibrary
|
||||
|
||||
Void Library требует поддержки C++26. Тесты ядра и LAN используют рефлексию C++26. `Void::Testing::Suite<T>` регистрирует методы без аргументов с возвращаемым типом `Void::Testing::Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры без тестов задайте `-DBUILD_TESTING=OFF` при прямом вызове CMake.
|
||||
|
||||
Потактную проверку симуляции можно запустить командой `build\settlement_core_tests.exe --tag replay`. Она сравнивает последовательную партию с исполнением на 2, 6 и 12 рабочих потоках и с продолжением из сохранения. [Сценарий M01](docs/plan/milestones/M01.md)
|
||||
|
||||
## Структура
|
||||
|
||||
```text
|
||||
|
||||
+122
-26
@@ -11,6 +11,8 @@
|
||||
#include <cstring>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement::viewer {
|
||||
@@ -468,6 +470,8 @@ cbuffer Camera : register(b0) {
|
||||
float2 screen;
|
||||
float scale;
|
||||
float padding;
|
||||
float2 depthParameters;
|
||||
float2 depthPadding;
|
||||
};
|
||||
struct Input { float3 position : POSITION; float3 color : COLOR; };
|
||||
struct Pixel { float4 position : SV_Position; float3 color : COLOR; };
|
||||
@@ -477,7 +481,8 @@ Pixel project(Input input) {
|
||||
(p.x + p.y) * halfTile.y - p.z * 16.0);
|
||||
Pixel result;
|
||||
result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0,
|
||||
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
|
||||
1.0 - screenPoint.y * 2.0 / screen.y,
|
||||
depthParameters.x - (p.x + p.y + p.z * 1.5) * depthParameters.y, 1.0);
|
||||
result.color = input.color;
|
||||
return result;
|
||||
}
|
||||
@@ -486,6 +491,13 @@ float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
|
||||
|
||||
} // namespace
|
||||
|
||||
class PreparedGeometry {
|
||||
public:
|
||||
Mesh mesh;
|
||||
std::shared_ptr<const VoxelScene> voxel_scene;
|
||||
float depth_bias = .96f, depth_scale = .009f;
|
||||
};
|
||||
|
||||
struct D3DScene::Backend {
|
||||
ComPtr<ID3D11Device> device;
|
||||
ComPtr<ID3D11DeviceContext> context;
|
||||
@@ -501,10 +513,11 @@ struct D3DScene::Backend {
|
||||
ComPtr<ID3D11Buffer> geometry;
|
||||
UINT buffer_bytes = 0;
|
||||
int width = 0, height = 0;
|
||||
Mesh mesh;
|
||||
std::shared_ptr<const PreparedGeometry> uploaded;
|
||||
|
||||
bool resize(int w, int h) {
|
||||
if (w == width && h == height && target_view && depth_view) return true;
|
||||
uploaded.reset();
|
||||
context->OMSetRenderTargets(0, nullptr, nullptr);
|
||||
target_texture.Reset();
|
||||
target_view.Reset();
|
||||
@@ -532,22 +545,29 @@ struct D3DScene::Backend {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool upload_geometry() {
|
||||
bool upload_geometry(const Mesh& mesh) {
|
||||
if (mesh.vertices.empty()) return true;
|
||||
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
|
||||
if (bytes > std::numeric_limits<UINT>::max()) return false;
|
||||
ComPtr<ID3D11Buffer> replacement;
|
||||
auto* destination = geometry.Get();
|
||||
if (bytes > buffer_bytes) {
|
||||
D3D11_BUFFER_DESC desc{};
|
||||
desc.ByteWidth = static_cast<UINT>(bytes);
|
||||
desc.Usage = D3D11_USAGE_DYNAMIC;
|
||||
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
|
||||
if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false;
|
||||
buffer_bytes = desc.ByteWidth;
|
||||
if (FAILED(device->CreateBuffer(&desc, nullptr, &replacement))) return false;
|
||||
destination = replacement.Get();
|
||||
}
|
||||
D3D11_MAPPED_SUBRESOURCE mapped{};
|
||||
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
|
||||
if (FAILED(context->Map(destination, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
|
||||
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
|
||||
context->Unmap(geometry.Get(), 0);
|
||||
context->Unmap(destination, 0);
|
||||
if (replacement) {
|
||||
geometry = std::move(replacement);
|
||||
buffer_bytes = static_cast<UINT>(bytes);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -578,7 +598,7 @@ D3DScene::D3DScene() = default;
|
||||
D3DScene::~D3DScene() = default;
|
||||
|
||||
bool D3DScene::initialize(HWND target, bool software) {
|
||||
auto graphics = std::make_unique<Backend>();
|
||||
auto graphics = std::make_shared<Backend>();
|
||||
const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
|
||||
constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
|
||||
constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
|
||||
@@ -615,7 +635,7 @@ bool D3DScene::initialize(HWND target, bool software) {
|
||||
raster.CullMode = D3D11_CULL_NONE;
|
||||
raster.DepthClipEnable = TRUE;
|
||||
D3D11_BUFFER_DESC constants{};
|
||||
constants.ByteWidth = 32;
|
||||
constants.ByteWidth = 48;
|
||||
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
|
||||
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
|
||||
vertex->GetBufferSize(), &graphics->layout)) ||
|
||||
@@ -628,24 +648,97 @@ bool D3DScene::initialize(HWND target, bool software) {
|
||||
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
|
||||
void D3DScene::reset() noexcept { backend_.reset(); }
|
||||
|
||||
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
|
||||
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
|
||||
auto& graphics = *backend_;
|
||||
if (!graphics.resize(view.width, view.height)) return false;
|
||||
graphics.mesh.vertices.clear();
|
||||
terrain(graphics.mesh, world, view);
|
||||
resources(graphics.mesh, world);
|
||||
construction(graphics.mesh, world, view.building_view);
|
||||
std::shared_ptr<const PreparedGeometry> D3DScene::prepare(const World& world, const SceneView& view) {
|
||||
auto prepared = std::make_shared<PreparedGeometry>();
|
||||
terrain(prepared->mesh, world, view);
|
||||
resources(prepared->mesh, world);
|
||||
construction(prepared->mesh, world, view.building_view);
|
||||
for (std::size_t index = 0; index < view.room_blueprints.size(); ++index) {
|
||||
if (view.moving_room == index) continue;
|
||||
const auto& plan = view.room_blueprints[index];
|
||||
draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan));
|
||||
draw_room_plan(prepared->mesh, plan, false, world.can_place_room(plan));
|
||||
}
|
||||
if (view.room_preview) draw_room_plan(prepared->mesh, *view.room_preview, true, view.valid_cursor);
|
||||
for (const auto& part : view.blueprint) draw_blueprint(prepared->mesh, part, false);
|
||||
if (view.preview) draw_blueprint(prepared->mesh, *view.preview, true);
|
||||
residents(prepared->mesh, world, view);
|
||||
return prepared;
|
||||
}
|
||||
|
||||
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
|
||||
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
|
||||
return render(prepare(world, view), view, capture);
|
||||
}
|
||||
|
||||
std::expected<std::shared_ptr<const PreparedGeometry>, VoxelSceneError>
|
||||
D3DScene::prepare_voxels(std::shared_ptr<const VoxelScene> scene) {
|
||||
if (!scene) return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
if (scene->faces().size() > std::numeric_limits<UINT>::max() / (6 * sizeof(Vertex)))
|
||||
return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
try {
|
||||
auto prepared = std::make_shared<PreparedGeometry>();
|
||||
prepared->voxel_scene = std::move(scene);
|
||||
const auto bounds = prepared->voxel_scene->visible_bounds();
|
||||
const double depth_extent = static_cast<double>(bounds.upper.x - bounds.lower.x) +
|
||||
static_cast<double>(bounds.upper.y - bounds.lower.y) +
|
||||
static_cast<double>(bounds.upper.z - bounds.lower.z) * 1.5;
|
||||
prepared->depth_bias = .95f;
|
||||
prepared->depth_scale = static_cast<float>(.9 / depth_extent);
|
||||
auto& mesh = prepared->mesh;
|
||||
mesh.vertices.reserve(prepared->voxel_scene->faces().size() * 6);
|
||||
for (const auto& face : prepared->voxel_scene->faces()) {
|
||||
const float x = static_cast<float>(std::int64_t{face.cell.x} - bounds.lower.x);
|
||||
const float y = static_cast<float>(std::int64_t{face.cell.y} - bounds.lower.y);
|
||||
const float z = static_cast<float>(std::int64_t{face.cell.z} - bounds.lower.z);
|
||||
const auto packed = voxel_face_color(face);
|
||||
const auto color = rgb(static_cast<int>((packed >> 16u) & 255u),
|
||||
static_cast<int>((packed >> 8u) & 255u), static_cast<int>(packed & 255u));
|
||||
if (face.normal.x != 0) {
|
||||
const float a = x + (face.normal.x > 0 ? 1.f : 0.f);
|
||||
mesh.quad({a, y, z}, {a, y + 1, z}, {a, y + 1, z + 1}, {a, y, z + 1}, color);
|
||||
} else if (face.normal.y != 0) {
|
||||
const float a = y + (face.normal.y > 0 ? 1.f : 0.f);
|
||||
mesh.quad({x, a, z}, {x + 1, a, z}, {x + 1, a, z + 1}, {x, a, z + 1}, color);
|
||||
} else {
|
||||
const float a = z + (face.normal.z > 0 ? 1.f : 0.f);
|
||||
mesh.quad({x, y, a}, {x + 1, y, a}, {x + 1, y + 1, a}, {x, y + 1, a}, color);
|
||||
}
|
||||
}
|
||||
return prepared;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
} catch (const std::length_error&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const VoxelCamera& camera,
|
||||
std::vector<std::uint32_t>* capture) {
|
||||
if (!geometry || !geometry->voxel_scene || !valid_voxel_camera(camera)) return false;
|
||||
SceneView view{};
|
||||
view.width = camera.width;
|
||||
view.height = camera.height;
|
||||
view.origin_x = static_cast<float>(camera.origin_x);
|
||||
view.origin_y = static_cast<float>(camera.origin_y);
|
||||
view.scale = static_cast<float>(camera.scale);
|
||||
view.tile_half_width = static_cast<float>(camera.tile_half_width);
|
||||
view.tile_half_height = static_cast<float>(camera.tile_half_height);
|
||||
return render(std::move(geometry), view, capture);
|
||||
}
|
||||
|
||||
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
|
||||
std::vector<std::uint32_t>* capture) {
|
||||
// Present may dispatch window messages, including destruction. Keep this
|
||||
// backend alive until the current submission has returned.
|
||||
const auto held_backend = backend_;
|
||||
if (!held_backend || !geometry || view.width <= 0 || view.height <= 0) return false;
|
||||
auto& graphics = *held_backend;
|
||||
if (!graphics.resize(view.width, view.height)) return false;
|
||||
if (graphics.uploaded != geometry) {
|
||||
if (!graphics.upload_geometry(geometry->mesh)) return false;
|
||||
graphics.uploaded = geometry;
|
||||
++uploads_;
|
||||
}
|
||||
if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor);
|
||||
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
|
||||
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
|
||||
residents(graphics.mesh, world, view);
|
||||
if (!graphics.upload_geometry()) return false;
|
||||
|
||||
auto* ctx = graphics.context.Get();
|
||||
constexpr float clear[] = {.83f, .87f, .79f, 1.f};
|
||||
@@ -656,7 +749,8 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
|
||||
ctx->RSSetViewports(1, &viewport);
|
||||
ctx->RSSetState(graphics.rasterizer.Get());
|
||||
const float constants[] = {view.origin_x, view.origin_y, view.tile_half_width, view.tile_half_height,
|
||||
viewport.Width, viewport.Height, view.scale, 0};
|
||||
viewport.Width, viewport.Height, view.scale, 0,
|
||||
geometry->depth_bias, geometry->depth_scale, 0, 0};
|
||||
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
|
||||
constexpr UINT stride = sizeof(Vertex);
|
||||
constexpr UINT offset = 0;
|
||||
@@ -666,9 +760,11 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
|
||||
ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0);
|
||||
ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf());
|
||||
ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0);
|
||||
ctx->Draw(static_cast<UINT>(graphics.mesh.vertices.size()), 0);
|
||||
ctx->Draw(static_cast<UINT>(geometry->mesh.vertices.size()), 0);
|
||||
if (capture && !graphics.read_frame(*capture)) return false;
|
||||
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
|
||||
if (graphics.swap_chain && FAILED(graphics.swap_chain->Present(0, 0))) return false;
|
||||
++frames_;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer
|
||||
+17
-1
@@ -3,6 +3,7 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
#include "voxel_scene.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
@@ -40,18 +41,33 @@ struct SceneView {
|
||||
std::optional<std::size_t> moving_room;
|
||||
};
|
||||
|
||||
// Immutable CPU geometry can outlive the latest frame and any GPU backend.
|
||||
class PreparedGeometry;
|
||||
|
||||
class D3DScene {
|
||||
public:
|
||||
D3DScene();
|
||||
~D3DScene();
|
||||
D3DScene(const D3DScene&) = delete;
|
||||
D3DScene& operator=(const D3DScene&) = delete;
|
||||
bool initialize(HWND target, bool software = false);
|
||||
[[nodiscard]] bool ready() const noexcept;
|
||||
bool render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture = nullptr);
|
||||
[[nodiscard]] static std::shared_ptr<const PreparedGeometry> prepare(const World& world, const SceneView& view);
|
||||
bool render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
|
||||
std::vector<std::uint32_t>* capture = nullptr);
|
||||
[[nodiscard]] static std::expected<std::shared_ptr<const PreparedGeometry>, VoxelSceneError>
|
||||
prepare_voxels(std::shared_ptr<const VoxelScene> scene);
|
||||
bool render(std::shared_ptr<const PreparedGeometry> geometry, const VoxelCamera& view,
|
||||
std::vector<std::uint32_t>* capture = nullptr);
|
||||
[[nodiscard]] std::uint64_t uploads() const noexcept { return uploads_; }
|
||||
[[nodiscard]] std::uint64_t frames() const noexcept { return frames_; }
|
||||
void reset() noexcept;
|
||||
|
||||
private:
|
||||
std::uint64_t uploads_ = 0, frames_ = 0;
|
||||
struct Backend;
|
||||
std::unique_ptr<Backend> backend_;
|
||||
std::shared_ptr<Backend> backend_;
|
||||
};
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -3,10 +3,13 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace settlement { class SimulationRuntime; }
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
|
||||
@@ -20,9 +23,25 @@ struct LanRejection {
|
||||
GridPosition destination;
|
||||
};
|
||||
|
||||
struct LanCommandResult {
|
||||
CommandStatus status;
|
||||
CommandKind kind;
|
||||
GridPosition cell;
|
||||
std::uint8_t value;
|
||||
GridPosition destination;
|
||||
AgentId resident;
|
||||
};
|
||||
|
||||
struct LanSessionOptions {
|
||||
// Runs on the polling thread after a guest command's snapshot checks and
|
||||
// before owner admission. May block or throw for diagnostics/tests.
|
||||
std::function<void()> before_command_admission;
|
||||
};
|
||||
|
||||
class LanSession {
|
||||
public:
|
||||
LanSession();
|
||||
explicit LanSession(LanSessionOptions options);
|
||||
~LanSession();
|
||||
LanSession(const LanSession&) = delete;
|
||||
LanSession& operator=(const LanSession&) = delete;
|
||||
@@ -39,7 +58,16 @@ public:
|
||||
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
|
||||
GridPosition destination = {}, AgentId resident = 0);
|
||||
[[nodiscard]] std::optional<LanRejection> take_rejection() noexcept;
|
||||
// poll_guest pauses further sends until this one retained result is drained.
|
||||
[[nodiscard]] std::optional<LanCommandResult> take_result() noexcept;
|
||||
[[nodiscard]] std::unique_ptr<World> poll(World& world);
|
||||
// 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);
|
||||
[[nodiscard]] std::unique_ptr<World> poll_guest();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
|
||||
+229
-32
@@ -6,6 +6,7 @@
|
||||
|
||||
#include "lan_session.hpp"
|
||||
#include "lan_wire.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -150,9 +151,25 @@ 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 {
|
||||
struct PendingCommand {
|
||||
std::future<RuntimeResult> completion;
|
||||
Void::Uuid::Uuid session;
|
||||
std::uint64_t peer_generation;
|
||||
};
|
||||
|
||||
bool winsock = false;
|
||||
Socket listener;
|
||||
Channel peer;
|
||||
@@ -167,14 +184,21 @@ struct LanSession::Impl {
|
||||
std::string notice;
|
||||
std::deque<Action> actions;
|
||||
std::optional<LanRejection> rejected_command;
|
||||
std::optional<LanCommandResult> command_result;
|
||||
bool result_backpressure = false;
|
||||
std::uint64_t guest_sequence = 0;
|
||||
Clock::time_point last_ping{};
|
||||
Clock::time_point last_snapshot{};
|
||||
std::uint64_t sent_tick = 0;
|
||||
std::uint64_t sent_host_sequence = 0;
|
||||
std::uint64_t sent_guest_sequence = 0;
|
||||
std::uint64_t peer_generation = 0;
|
||||
std::optional<Void::Uuid::Uuid> runtime_session;
|
||||
std::optional<RulesManifest> compatibility_rules;
|
||||
std::optional<PendingCommand> pending_command;
|
||||
LanSessionOptions options;
|
||||
|
||||
Impl() {
|
||||
explicit Impl(LanSessionOptions settings) : options(std::move(settings)) {
|
||||
WSADATA data{};
|
||||
winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0;
|
||||
}
|
||||
@@ -185,14 +209,18 @@ struct LanSession::Impl {
|
||||
}
|
||||
|
||||
void drop_peer() noexcept {
|
||||
++peer_generation;
|
||||
peer = Channel{};
|
||||
connecting = authenticated = reject_pending = false;
|
||||
awaiting_receipt.reset();
|
||||
guest_sequence = 0;
|
||||
actions.clear();
|
||||
rejected_command.reset();
|
||||
command_result.reset();
|
||||
last_snapshot = {};
|
||||
last_ping = {};
|
||||
// pending_command belongs to the authenticated guest slot, even after
|
||||
// its socket disappears. A later peer waits for this result to settle.
|
||||
}
|
||||
|
||||
void accept_guest() {
|
||||
@@ -223,17 +251,21 @@ struct LanSession::Impl {
|
||||
connecting = false;
|
||||
}
|
||||
|
||||
void authenticate(Message message, std::string_view payload) {
|
||||
if (reject_pending) return;
|
||||
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
|
||||
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
|
||||
peer.queue(Message::Reject);
|
||||
reject_pending = true;
|
||||
return;
|
||||
}
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
}
|
||||
|
||||
void handle_host(World& world, Message message, std::string_view payload) {
|
||||
if (!authenticated) {
|
||||
if (reject_pending) return;
|
||||
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
|
||||
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
|
||||
peer.queue(Message::Reject);
|
||||
reject_pending = true;
|
||||
return;
|
||||
}
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
authenticate(message, payload);
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
@@ -244,6 +276,106 @@ struct LanSession::Impl {
|
||||
peer.queue(Message::Receipt, std::string_view(reply));
|
||||
}
|
||||
|
||||
void reply(CommandStatus status, const World& world) {
|
||||
const auto bytes = lan_wire::encode_receipt({status, world.next_command_sequence(guest_player)});
|
||||
peer.queue(Message::Receipt, std::string_view(bytes));
|
||||
}
|
||||
|
||||
void handle_runtime_host(SimulationRuntime& runtime, const std::shared_ptr<const PublishedSnapshot>& checked,
|
||||
Message message, std::string_view payload) {
|
||||
const auto& snapshot = *checked;
|
||||
if (!authenticated) {
|
||||
authenticate(message, payload);
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt;
|
||||
if (!command) throw std::runtime_error("Invalid guest command.");
|
||||
if (pending_command) throw std::runtime_error("A guest command is already pending.");
|
||||
if (command->sequence != snapshot.world->next_command_sequence(guest_player)) {
|
||||
reply(CommandStatus::WrongSequence, *snapshot.world);
|
||||
return;
|
||||
}
|
||||
const auto& identity = snapshot.identity;
|
||||
const CommandEnvelope envelope{
|
||||
command_envelope_version, identity.world, identity.session, identity.city,
|
||||
snapshot.next_requests[guest_player - 1],
|
||||
CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident}
|
||||
};
|
||||
if (options.before_command_admission) options.before_command_admission();
|
||||
auto submitted = runtime.try_submit_if_current({guest_player}, envelope, checked);
|
||||
if (submitted.admission == RuntimeAdmission::Accepted) {
|
||||
pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation);
|
||||
} else if (submitted.admission == RuntimeAdmission::Busy ||
|
||||
submitted.admission == RuntimeAdmission::StaleSnapshot) {
|
||||
// Contention/capacity does not certify the old publication either.
|
||||
// Fail closed on incompatible/faulted/replaced state; an ordinary
|
||||
// compatible revision leaves the legacy sequence available to retry.
|
||||
const auto current = current_runtime_snapshot(runtime);
|
||||
reply(CommandStatus::Busy, *current->world);
|
||||
} else {
|
||||
throw std::runtime_error("The authoritative owner cannot accept guest commands.");
|
||||
}
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
const auto& receipt = *result.receipt;
|
||||
if (receipt.status == DispatchStatus::Completed) {
|
||||
reply(receipt.command_status, *result.snapshot->world);
|
||||
} else if (receipt.status == DispatchStatus::Busy) {
|
||||
reply(CommandStatus::Busy, *result.snapshot->world);
|
||||
} else {
|
||||
throw std::runtime_error("The guest command belongs to an obsolete or conflicting request.");
|
||||
}
|
||||
}
|
||||
|
||||
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 || !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.");
|
||||
}
|
||||
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<const PublishedSnapshot> 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<World>& 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) {
|
||||
@@ -264,6 +396,8 @@ struct LanSession::Impl {
|
||||
}
|
||||
const auto status = receipt->status;
|
||||
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
|
||||
command_result = LanCommandResult{status, awaiting_receipt->kind, awaiting_receipt->cell,
|
||||
awaiting_receipt->value, awaiting_receipt->destination, awaiting_receipt->resident};
|
||||
if (status != CommandStatus::Accepted) {
|
||||
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell,
|
||||
awaiting_receipt->value, awaiting_receipt->destination};
|
||||
@@ -273,6 +407,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);
|
||||
@@ -291,6 +426,7 @@ struct LanSession::Impl {
|
||||
|
||||
void send_action() {
|
||||
if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return;
|
||||
if (result_backpressure && command_result) return;
|
||||
const Action action = actions.front();
|
||||
const auto payload = lan_wire::encode_command(
|
||||
{guest_player, guest_sequence, action.kind, action.cell, action.value, action.destination, action.resident});
|
||||
@@ -298,9 +434,43 @@ struct LanSession::Impl {
|
||||
actions.pop_front();
|
||||
awaiting_receipt = action;
|
||||
}
|
||||
|
||||
template<class Receive, class SendHost, class Validate>
|
||||
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();
|
||||
if ((!authenticated && now - peer.opened > 8s) ||
|
||||
(authenticated && now - peer.last_received > 15s)) {
|
||||
throw std::runtime_error("The peer did not respond.");
|
||||
}
|
||||
if (connecting) finish_connection();
|
||||
if (connecting) return;
|
||||
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) {
|
||||
peer.queue(Message::Ping);
|
||||
last_ping = now;
|
||||
}
|
||||
} 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();
|
||||
}
|
||||
};
|
||||
|
||||
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
|
||||
LanSession::LanSession() : LanSession(LanSessionOptions{}) {}
|
||||
LanSession::LanSession(LanSessionOptions options) : impl_(std::make_unique<Impl>(std::move(options))) {}
|
||||
LanSession::~LanSession() = default;
|
||||
|
||||
void LanSession::host(std::uint16_t port, bool loopback_only) {
|
||||
@@ -397,34 +567,61 @@ std::optional<LanRejection> LanSession::take_rejection() noexcept {
|
||||
return std::exchange(impl_->rejected_command, std::nullopt);
|
||||
}
|
||||
|
||||
std::optional<LanCommandResult> LanSession::take_result() noexcept {
|
||||
return std::exchange(impl_->command_result, std::nullopt);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> LanSession::poll(World& world) {
|
||||
auto& connection = *impl_;
|
||||
connection.result_backpressure = false;
|
||||
std::unique_ptr<World> latest;
|
||||
try {
|
||||
if (connection.listener) connection.accept_guest();
|
||||
if (!connection.peer.socket) return nullptr;
|
||||
const auto now = Clock::now();
|
||||
if ((!connection.authenticated && now - connection.peer.opened > 8s) ||
|
||||
(connection.authenticated && now - connection.peer.last_received > 15s)) {
|
||||
throw std::runtime_error("The peer did not respond.");
|
||||
}
|
||||
if (connection.connecting) connection.finish_connection();
|
||||
if (connection.connecting) return nullptr;
|
||||
connection.peer.receive([&](Message message, std::string_view payload) {
|
||||
if (connection.pending_command) throw std::runtime_error("Continue polling the authoritative owner.");
|
||||
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); }, [&] {
|
||||
if (connection.listener && !connection.guest) require_legacy_world(world);
|
||||
});
|
||||
if (connection.authenticated && connection.guest) {
|
||||
connection.send_action();
|
||||
if (!connection.peer.pending() && now - connection.last_ping >= 2s) {
|
||||
connection.peer.queue(Message::Ping);
|
||||
connection.last_ping = now;
|
||||
}
|
||||
} else if (connection.authenticated) {
|
||||
connection.send_snapshot(world, now);
|
||||
}
|
||||
connection.peer.flush();
|
||||
if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer();
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
latest.reset();
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
void LanSession::poll_host(SimulationRuntime& runtime) {
|
||||
auto& connection = *impl_;
|
||||
if (!connection.listener || connection.guest) return;
|
||||
try {
|
||||
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) {
|
||||
const auto snapshot = connection.current_runtime_snapshot(runtime);
|
||||
connection.handle_runtime_host(runtime, snapshot, message, payload);
|
||||
}, [&](Clock::time_point now) {
|
||||
const auto snapshot = connection.current_runtime_snapshot(runtime);
|
||||
if (!connection.pending_command) connection.send_snapshot(*snapshot->world, now);
|
||||
}, [&] { static_cast<void>(connection.current_runtime_snapshot(runtime)); }, !connection.pending_command);
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<World> LanSession::poll_guest() {
|
||||
auto& connection = *impl_;
|
||||
connection.result_backpressure = true;
|
||||
std::unique_ptr<World> latest;
|
||||
if (!connection.guest) return nullptr;
|
||||
try {
|
||||
connection.poll_network([&](Message message, std::string_view payload) {
|
||||
connection.handle_guest(latest, message, payload);
|
||||
}, [](Clock::time_point) {}, [] {});
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include "settlement/core/colony_profile.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -19,6 +20,7 @@ constexpr int title_coop_id = 1103;
|
||||
constexpr int title_exit_id = 1104;
|
||||
constexpr int title_saves_id = 1105;
|
||||
constexpr int title_open_id = 1106;
|
||||
constexpr int title_rules_id = 1107;
|
||||
|
||||
inline std::filesystem::path saves_directory() {
|
||||
const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0);
|
||||
@@ -51,6 +53,14 @@ public:
|
||||
0, 0, 0, 0, owner, id(title_saves_id), instance, nullptr);
|
||||
open_ = CreateWindowExW(0, L"BUTTON", L"Загрузить выбранное", WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, owner, id(title_open_id), instance, nullptr);
|
||||
rules_label_ = CreateWindowExW(0, L"STATIC", L"Правила только новой колонии:", WS_CHILD,
|
||||
0, 0, 0, 0, owner, nullptr, instance, nullptr);
|
||||
rules_ = CreateWindowExW(0, L"COMBOBOX", L"Правила новой колонии",
|
||||
WS_CHILD | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST,
|
||||
0, 0, 0, 0, owner, id(title_rules_id), instance, nullptr);
|
||||
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Поэтапная кровать: опора и 2 ткани"));
|
||||
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Простая кровать: 1 доска"));
|
||||
SendMessageW(rules_, CB_SETCURSEL, 0, 0);
|
||||
list_background_ = CreateSolidBrush(RGB(44, 63, 53));
|
||||
font_ = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
|
||||
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
|
||||
@@ -58,6 +68,8 @@ public:
|
||||
for (const auto button : buttons_) SendMessageW(button, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(saves_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(open_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(rules_label_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(rules_, WM_SETFONT, font, FALSE);
|
||||
}
|
||||
|
||||
void reload_saves() {
|
||||
@@ -90,6 +102,8 @@ public:
|
||||
for (const auto button : buttons_) ShowWindow(button, flags);
|
||||
ShowWindow(saves_, flags);
|
||||
ShowWindow(open_, flags);
|
||||
ShowWindow(rules_label_, flags);
|
||||
ShowWindow(rules_, flags);
|
||||
}
|
||||
|
||||
void update(bool can_resume, bool offline) const {
|
||||
@@ -98,6 +112,7 @@ public:
|
||||
EnableWindow(buttons_[title_browse_id - title_continue_id], offline);
|
||||
EnableWindow(open_, offline && selected_index() < saves.size());
|
||||
EnableWindow(saves_, offline);
|
||||
EnableWindow(rules_, offline);
|
||||
}
|
||||
|
||||
HBRUSH paint_list_background(HWND control, HDC dc) const {
|
||||
@@ -116,6 +131,10 @@ public:
|
||||
return saves.empty() ? std::nullopt : std::optional{saves.front().path};
|
||||
}
|
||||
|
||||
[[nodiscard]] ColonyProfile new_colony_profile() const {
|
||||
return SendMessageW(rules_, CB_GETCURSEL, 0, 0) == 1 ? ColonyProfile::PlankBeds : ColonyProfile::Default;
|
||||
}
|
||||
|
||||
void layout(int width, int height) const {
|
||||
const RECT panel = bounds(width, height);
|
||||
for (std::size_t i = 0; i < buttons_.size(); ++i) {
|
||||
@@ -123,6 +142,8 @@ public:
|
||||
}
|
||||
position(saves_, panel.left + 318, panel.top + 146, panel.right - panel.left - 346, 118);
|
||||
position(open_, panel.left + 318, panel.top + 274, panel.right - panel.left - 346, 33);
|
||||
position(rules_label_, panel.left + 28, panel.top + 358, panel.right - panel.left - 56, 23);
|
||||
position(rules_, panel.left + 28, panel.top + 383, panel.right - panel.left - 56, 100);
|
||||
}
|
||||
|
||||
void draw(HDC dc, int width, int height, const std::wstring& notice) const {
|
||||
@@ -160,7 +181,7 @@ public:
|
||||
DrawTextW(dc, saves.empty() ? L"Сохранения · список пуст" : L"Сохранения", -1,
|
||||
&saves_label, DT_SINGLELINE | DT_VCENTER);
|
||||
if (!notice.empty()) {
|
||||
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.bottom - 11};
|
||||
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.top + 355};
|
||||
DrawTextW(dc, notice.c_str(), -1, &information, DT_WORDBREAK | DT_NOPREFIX);
|
||||
}
|
||||
SetTextColor(dc, ink);
|
||||
@@ -209,7 +230,7 @@ private:
|
||||
|
||||
static RECT bounds(int width, int height) {
|
||||
constexpr int panel_width = 704;
|
||||
constexpr int panel_height = 365;
|
||||
constexpr int panel_height = 430;
|
||||
const int left = (width - panel_width) / 2;
|
||||
const int top = (height - panel_height) / 2;
|
||||
return {left, top, left + panel_width, top + panel_height};
|
||||
@@ -233,6 +254,8 @@ private:
|
||||
std::array<HWND, 5> buttons_{};
|
||||
HWND saves_ = nullptr;
|
||||
HWND open_ = nullptr;
|
||||
HWND rules_label_ = nullptr;
|
||||
HWND rules_ = nullptr;
|
||||
HBRUSH list_background_ = nullptr;
|
||||
HFONT font_ = nullptr;
|
||||
std::vector<SaveFile> saves;
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
#include "viewer_session.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement::viewer {
|
||||
namespace {
|
||||
|
||||
template<class T>
|
||||
bool ready(std::future<T>& completion) {
|
||||
return completion.valid() && completion.wait_for(std::chrono::seconds{0}) == std::future_status::ready;
|
||||
}
|
||||
|
||||
RulesManifest supported_rules() {
|
||||
auto manifest = default_rules_manifest();
|
||||
if (!manifest) throw std::runtime_error(manifest.error().message);
|
||||
return std::move(*manifest);
|
||||
}
|
||||
|
||||
void validate_supported(const WorldCheckpoint& candidate) {
|
||||
const auto valid = validate_colony_checkpoint(candidate);
|
||||
if (!valid) throw std::runtime_error(valid.error().message);
|
||||
if (!candidate.world || candidate.world->width() != first_colony_map_size ||
|
||||
candidate.world->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
|
||||
}
|
||||
}
|
||||
|
||||
WorldCheckpoint validated_initial(WorldCheckpoint candidate) {
|
||||
validate_supported(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
WorldCheckpoint initial_colony(std::size_t workers, ColonyProfile profile = ColonyProfile::Default) {
|
||||
auto candidate = make_colony_checkpoint(profile, workers);
|
||||
if (!candidate) throw std::runtime_error(candidate.error().message);
|
||||
return std::move(*candidate);
|
||||
}
|
||||
|
||||
RuntimeOptions suspended(RuntimeOptions options) {
|
||||
options.ticking = false;
|
||||
return options;
|
||||
}
|
||||
|
||||
std::string exception_message() {
|
||||
try { throw; }
|
||||
catch (const std::exception& error) { return error.what(); }
|
||||
catch (...) { return "The operation failed."; }
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ViewerSession::ViewerSession(std::size_t workers, ViewerSessionOptions options)
|
||||
: ViewerSession(initial_colony(workers), workers, std::move(options)) {}
|
||||
|
||||
ViewerSession::ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options)
|
||||
: workers_(workers), command_capacity_(options.command_capacity),
|
||||
supported_rules_(supported_rules()),
|
||||
runtime_(validated_initial(std::move(initial)), suspended(std::move(options.runtime))),
|
||||
files_(std::move(options.files)) {
|
||||
if (command_capacity_ == 0) throw std::invalid_argument("The command queue must have capacity.");
|
||||
}
|
||||
|
||||
ViewerSession::~ViewerSession() = default;
|
||||
|
||||
std::shared_ptr<const World> ViewerSession::world() const {
|
||||
return guest_ || (changing_world_ && guest_view_) ? guest_view_ : runtime_.latest()->world;
|
||||
}
|
||||
|
||||
bool ViewerSession::can_submit() const {
|
||||
return !guest_ && !changing_world_ && runtime_.view().state == RuntimeState::Running;
|
||||
}
|
||||
|
||||
bool ViewerSession::can_host_legacy() const {
|
||||
const auto current = runtime_.view();
|
||||
return !guest_ && !changing_world_ && current.state == RuntimeState::Running &&
|
||||
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<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
|
||||
if (!can_submit()) return std::nullopt;
|
||||
for (const auto& intent : intents_) {
|
||||
if (intent.payload == payload) return intent.id;
|
||||
}
|
||||
if (intents_.size() == command_capacity_ || next_intent_ == std::numeric_limits<std::uint64_t>::max()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto id = next_intent_;
|
||||
intents_.push_back({id, std::move(payload)});
|
||||
++next_intent_;
|
||||
return id;
|
||||
}
|
||||
|
||||
bool ViewerSession::pending(std::uint64_t id) const noexcept {
|
||||
for (const auto& intent : intents_) if (intent.id == id) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
LoadTicket ViewerSession::begin_change() {
|
||||
if (generation_ == std::numeric_limits<std::uint64_t>::max()) {
|
||||
throw std::overflow_error("The client operation counter is exhausted.");
|
||||
}
|
||||
auto ticket = runtime_.begin_load();
|
||||
if (!ticket) throw std::runtime_error("The simulation cannot accept a world change.");
|
||||
++generation_;
|
||||
intents_.clear();
|
||||
command_completion_ = {};
|
||||
preparing_.reset();
|
||||
installing_.reset();
|
||||
install_completion_ = {};
|
||||
events_.clear();
|
||||
changing_world_ = true;
|
||||
return *ticket;
|
||||
}
|
||||
|
||||
void ViewerSession::validate_candidate(const WorldCheckpoint& candidate) const {
|
||||
validate_supported(candidate);
|
||||
}
|
||||
|
||||
void ViewerSession::replace(WorldCheckpoint candidate) {
|
||||
validate_candidate(candidate);
|
||||
const auto ticket = begin_change();
|
||||
installing_.emplace(Installing{ticket, std::move(candidate)});
|
||||
}
|
||||
|
||||
void ViewerSession::new_colony(ColonyProfile profile) {
|
||||
replace(initial_colony(workers_, profile));
|
||||
}
|
||||
|
||||
void ViewerSession::load(const std::filesystem::path& path) {
|
||||
if (guest_) throw std::runtime_error("Only the host can load a world.");
|
||||
const auto ticket = begin_change();
|
||||
try {
|
||||
auto operation = files_.try_load(path, workers_);
|
||||
if (operation.admission != CheckpointLoadAdmission::Accepted) {
|
||||
throw std::runtime_error("The file reader is busy or unavailable. Try again.");
|
||||
}
|
||||
preparing_.emplace(Preparing{ticket, std::move(operation.completion)});
|
||||
} catch (...) {
|
||||
changing_world_ = false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::save(const std::filesystem::path& path) {
|
||||
if (guest_ || changing_world_) throw std::runtime_error("The current world cannot be saved yet.");
|
||||
poll_saves();
|
||||
const auto snapshot = runtime_.snapshot_for_save();
|
||||
if (!snapshot) throw std::runtime_error("Load a valid world before saving after a simulation failure.");
|
||||
// Reserve result tracking before accepting a write so allocation cannot lose
|
||||
// the newest request's completion or its originating session.
|
||||
saving_.reserve(saving_.size() + 1);
|
||||
auto operation = files_.try_save(path, *snapshot);
|
||||
if (operation.admission != SaveAdmission::Accepted) {
|
||||
throw std::runtime_error("The save queue is busy or unavailable. Try again.");
|
||||
}
|
||||
latest_save_ = operation.request_id;
|
||||
saving_.push_back({generation_, operation.request_id, (*snapshot)->identity.session,
|
||||
std::move(operation.completion)});
|
||||
}
|
||||
|
||||
void ViewerSession::enter_guest() {
|
||||
static_cast<void>(begin_change());
|
||||
guest_ = true;
|
||||
changing_world_ = false;
|
||||
guest_world_.reset();
|
||||
guest_view_.reset();
|
||||
}
|
||||
|
||||
void ViewerSession::receive_guest(std::unique_ptr<World> world) {
|
||||
if (!guest_ || !world) return;
|
||||
auto view = world->capture();
|
||||
guest_world_ = std::move(world);
|
||||
guest_view_ = std::move(view);
|
||||
}
|
||||
|
||||
void ViewerSession::leave_guest() {
|
||||
if (!guest_) return;
|
||||
if (guest_world_) {
|
||||
auto id = Void::Uuid::try_v4();
|
||||
if (!id) throw std::runtime_error("Could not create a world identity.");
|
||||
if (guest_world_->width() != first_colony_map_size || guest_world_->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
|
||||
}
|
||||
// All fallible preparation precedes moving the last received world.
|
||||
auto rules = supported_rules_;
|
||||
const auto ticket = begin_change();
|
||||
installing_.emplace(Installing{ticket, {std::move(guest_world_), *id, 1, std::move(rules)}});
|
||||
} else {
|
||||
static_cast<void>(begin_change());
|
||||
changing_world_ = false;
|
||||
}
|
||||
guest_ = false;
|
||||
if (!changing_world_) guest_view_.reset();
|
||||
}
|
||||
|
||||
void ViewerSession::fail_change(std::string message) {
|
||||
preparing_.reset();
|
||||
installing_.reset();
|
||||
install_completion_ = {};
|
||||
changing_world_ = false;
|
||||
if (!guest_) guest_view_.reset();
|
||||
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable, std::move(message)});
|
||||
}
|
||||
|
||||
void ViewerSession::poll_changes() {
|
||||
if (preparing_ && ready(preparing_->completion)) {
|
||||
const auto ticket = preparing_->ticket;
|
||||
auto prepared = preparing_->completion.get();
|
||||
preparing_.reset();
|
||||
if (runtime_.latest()->identity.session != ticket.expected_session) {
|
||||
fail_change("The load belongs to an earlier session.");
|
||||
return;
|
||||
}
|
||||
if (!prepared) {
|
||||
fail_change(prepared.error().message);
|
||||
return;
|
||||
}
|
||||
validate_candidate(*prepared);
|
||||
installing_.emplace(Installing{ticket, std::move(*prepared)});
|
||||
}
|
||||
if (installing_) {
|
||||
auto result = runtime_.try_install(installing_->ticket, installing_->candidate);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
install_completion_ = std::move(result.completion);
|
||||
installing_.reset();
|
||||
} else if (result.admission != RuntimeAdmission::Busy) {
|
||||
fail_change("The simulation could not install this world.");
|
||||
}
|
||||
}
|
||||
if (ready(install_completion_)) {
|
||||
const auto result = install_completion_.get();
|
||||
changing_world_ = false;
|
||||
if (result.outcome == RuntimeOutcome::Completed && result.snapshot &&
|
||||
result.snapshot->identity.session == runtime_.latest()->identity.session) {
|
||||
guest_view_.reset();
|
||||
fault_reported_ = false;
|
||||
events_.push_back({ViewerEventKind::Replaced, 0, {}, CommandStatus::Unavailable, {}});
|
||||
} else {
|
||||
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable,
|
||||
"The world change failed or was superseded. The current view is retained."});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_commands() {
|
||||
if (ready(command_completion_)) {
|
||||
auto result = command_completion_.get();
|
||||
if (!intents_.empty()) {
|
||||
auto intent = std::move(intents_.front());
|
||||
intents_.pop_front();
|
||||
const auto status = result.outcome == RuntimeOutcome::Completed && result.receipt &&
|
||||
result.receipt->status == DispatchStatus::Completed
|
||||
? result.receipt->command_status : CommandStatus::Unavailable;
|
||||
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), status, {}});
|
||||
}
|
||||
}
|
||||
if (command_completion_.valid() || intents_.empty() || !can_submit()) return;
|
||||
const auto current = runtime_.latest();
|
||||
const CommandEnvelope command{command_envelope_version, current->identity.world, current->identity.session,
|
||||
current->identity.city, current->next_requests[colony_host - 1], intents_.front().payload};
|
||||
auto result = runtime_.try_submit({colony_host}, command);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
command_completion_ = std::move(result.completion);
|
||||
} else if (result.admission != RuntimeAdmission::Busy) {
|
||||
auto intent = std::move(intents_.front());
|
||||
intents_.pop_front();
|
||||
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), CommandStatus::Unavailable, {}});
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_saves() {
|
||||
for (auto item = saving_.begin(); item != saving_.end();) {
|
||||
if (!ready(item->completion)) {
|
||||
++item;
|
||||
continue;
|
||||
}
|
||||
const auto result = item->completion.get();
|
||||
if (item->generation == generation_ && item->request == latest_save_ &&
|
||||
item->session == runtime_.latest()->identity.session && !guest_) {
|
||||
events_.push_back({result.succeeded() ? ViewerEventKind::Saved : ViewerEventKind::Error,
|
||||
0, {}, CommandStatus::Unavailable,
|
||||
result.succeeded() ? "" : result.visible_on_disk
|
||||
? "The new save is visible, but its final disk status could not be confirmed."
|
||||
: "The save failed. The previous slot remains available."});
|
||||
}
|
||||
item = saving_.erase(item);
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_ticking() {
|
||||
if (ready(ticking_completion_)) {
|
||||
const auto result = ticking_completion_.get();
|
||||
// The owner applies its ticking flag even while its world is faulted.
|
||||
if (result.outcome == RuntimeOutcome::Completed || result.outcome == RuntimeOutcome::Faulted) {
|
||||
applied_ticking_ = requested_ticking_;
|
||||
}
|
||||
}
|
||||
const bool desired = desired_ticking_ && !guest_ && !changing_world_;
|
||||
if (ticking_completion_.valid() || desired == applied_ticking_) return;
|
||||
auto result = runtime_.set_ticking(desired);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
requested_ticking_ = desired;
|
||||
ticking_completion_ = std::move(result.completion);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ViewerEvent> ViewerSession::poll() {
|
||||
try {
|
||||
poll_changes();
|
||||
poll_commands();
|
||||
poll_saves();
|
||||
poll_ticking();
|
||||
} catch (...) {
|
||||
fail_change(exception_message());
|
||||
}
|
||||
if (!guest_ && runtime_.view().state == RuntimeState::Faulted && !fault_reported_) {
|
||||
fault_reported_ = true;
|
||||
intents_.clear();
|
||||
command_completion_ = {};
|
||||
events_.push_back({ViewerEventKind::Fault, 0, {}, CommandStatus::Unavailable,
|
||||
"The simulation stopped at its last completed state. Load a save to continue."});
|
||||
}
|
||||
return std::exchange(events_, {});
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/checkpoint_files.hpp"
|
||||
#include "settlement/core/colony_profile.hpp"
|
||||
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
enum class ViewerEventKind { Replaced, Command, Saved, Error, Fault };
|
||||
|
||||
struct ViewerEvent {
|
||||
ViewerEventKind kind;
|
||||
std::uint64_t command = 0;
|
||||
std::optional<SessionPayload> payload;
|
||||
CommandStatus status = CommandStatus::Unavailable;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct ViewerSessionOptions {
|
||||
RuntimeOptions runtime;
|
||||
CheckpointFilesOptions files;
|
||||
std::size_t command_capacity = 64;
|
||||
};
|
||||
|
||||
// Called only by the UI thread. Polling owns completion delivery; rendering holds
|
||||
// an immutable view independently of owner progress and nested window messages.
|
||||
class ViewerSession {
|
||||
public:
|
||||
explicit ViewerSession(std::size_t workers, ViewerSessionOptions options = {});
|
||||
ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options = {});
|
||||
~ViewerSession();
|
||||
|
||||
[[nodiscard]] SimulationRuntime& runtime() noexcept { return runtime_; }
|
||||
[[nodiscard]] std::shared_ptr<const World> world() const;
|
||||
[[nodiscard]] bool guest() const noexcept { return guest_; }
|
||||
[[nodiscard]] bool changing_world() const noexcept { return changing_world_; }
|
||||
[[nodiscard]] bool can_submit() const;
|
||||
[[nodiscard]] bool can_host_legacy() const;
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept { return generation_; }
|
||||
[[nodiscard]] std::optional<std::uint64_t> submit(SessionPayload payload);
|
||||
[[nodiscard]] bool pending(std::uint64_t id) const noexcept;
|
||||
void set_ticking(bool enabled) noexcept { desired_ticking_ = enabled; }
|
||||
[[nodiscard]] std::vector<ViewerEvent> poll();
|
||||
|
||||
void new_colony(ColonyProfile profile = ColonyProfile::Default);
|
||||
void load(const std::filesystem::path& path);
|
||||
void save(const std::filesystem::path& path);
|
||||
void enter_guest();
|
||||
void receive_guest(std::unique_ptr<World> world);
|
||||
void leave_guest();
|
||||
|
||||
private:
|
||||
struct Intent {
|
||||
std::uint64_t id;
|
||||
SessionPayload payload;
|
||||
};
|
||||
struct Preparing {
|
||||
LoadTicket ticket;
|
||||
std::future<CheckpointLoadResult> completion;
|
||||
};
|
||||
struct Installing {
|
||||
LoadTicket ticket;
|
||||
WorldCheckpoint candidate;
|
||||
};
|
||||
struct Saving {
|
||||
std::uint64_t generation;
|
||||
std::uint64_t request;
|
||||
Void::Uuid::Uuid session;
|
||||
std::future<SaveResult> completion;
|
||||
};
|
||||
[[nodiscard]] LoadTicket begin_change();
|
||||
void replace(WorldCheckpoint candidate);
|
||||
void validate_candidate(const WorldCheckpoint& candidate) const;
|
||||
void fail_change(std::string message);
|
||||
void poll_changes();
|
||||
void poll_commands();
|
||||
void poll_saves();
|
||||
void poll_ticking();
|
||||
|
||||
std::size_t workers_;
|
||||
std::size_t command_capacity_;
|
||||
RulesManifest supported_rules_;
|
||||
SimulationRuntime runtime_;
|
||||
CheckpointFiles files_;
|
||||
std::shared_ptr<const World> guest_view_;
|
||||
std::unique_ptr<World> guest_world_;
|
||||
std::deque<Intent> intents_;
|
||||
std::future<RuntimeResult> command_completion_;
|
||||
std::optional<Preparing> preparing_;
|
||||
std::optional<Installing> installing_;
|
||||
std::future<RuntimeResult> install_completion_;
|
||||
std::vector<Saving> saving_;
|
||||
std::vector<ViewerEvent> events_;
|
||||
std::future<RuntimeResult> ticking_completion_;
|
||||
bool requested_ticking_ = false;
|
||||
bool applied_ticking_ = false;
|
||||
bool desired_ticking_ = false;
|
||||
bool guest_ = false;
|
||||
bool changing_world_ = false;
|
||||
bool fault_reported_ = false;
|
||||
std::uint64_t generation_ = 1;
|
||||
std::uint64_t next_intent_ = 1;
|
||||
std::uint64_t latest_save_ = 0;
|
||||
};
|
||||
|
||||
} // namespace settlement::viewer
|
||||
+794
-279
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,337 @@
|
||||
#include "voxel_scene.hpp"
|
||||
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace settlement::viewer {
|
||||
namespace {
|
||||
|
||||
constexpr std::array<VoxelPosition, 6> normals{{
|
||||
{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}}};
|
||||
constexpr double elevation_pixels = 16;
|
||||
|
||||
bool finite(VoxelPoint point) noexcept {
|
||||
return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z);
|
||||
}
|
||||
bool empty(VoxelBounds bounds) noexcept {
|
||||
return bounds.upper.z <= bounds.lower.z;
|
||||
}
|
||||
bool solid(const VoxelSample& sample) noexcept {
|
||||
return sample.availability == VoxelAvailability::Unavailable ||
|
||||
(sample.availability == VoxelAvailability::Loaded && voxel_blocks_passage(sample.material));
|
||||
}
|
||||
bool record(std::vector<ChunkStamp>& reads, ChunkStamp stamp, std::size_t limit) {
|
||||
const auto at = std::lower_bound(reads.begin(), reads.end(), stamp.coordinate,
|
||||
[](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; });
|
||||
if (at != reads.end() && at->coordinate == stamp.coordinate) return true;
|
||||
if (reads.size() >= limit) return false;
|
||||
reads.insert(at, stamp);
|
||||
return true;
|
||||
}
|
||||
std::optional<VoxelPosition> neighbor(VoxelPosition cell, VoxelPosition normal) noexcept {
|
||||
const auto x = Void::Numeric::checked_add(cell.x, normal.x);
|
||||
const auto y = Void::Numeric::checked_add(cell.y, normal.y);
|
||||
const auto z = Void::Numeric::checked_add(cell.z, normal.z);
|
||||
if (!x || !y || !z) return std::nullopt;
|
||||
return VoxelPosition{*x, *y, *z};
|
||||
}
|
||||
bool within_budget(std::size_t faces, std::size_t reads, std::size_t limit) noexcept {
|
||||
// Include the eventual six expanded position/color vertices per quad, so
|
||||
// this budget covers a retained CPU scene plus its prepared D3D geometry.
|
||||
constexpr std::size_t face_bytes = sizeof(VoxelFace) + 6 * 6 * sizeof(float);
|
||||
const auto mesh_bytes = Void::Numeric::checked_mul(faces, face_bytes);
|
||||
// Account for geometric vector capacity growth in the read directory.
|
||||
const auto stamp_bytes = Void::Numeric::checked_mul(reads, 2 * sizeof(ChunkStamp));
|
||||
if (!mesh_bytes || !stamp_bytes) return false;
|
||||
const auto total = Void::Numeric::checked_add(*mesh_bytes, *stamp_bytes);
|
||||
return total && *total <= limit;
|
||||
}
|
||||
std::array<std::int64_t, 3> lower_array(VoxelBounds bounds) noexcept {
|
||||
return {bounds.lower.x, bounds.lower.y, bounds.lower.z};
|
||||
}
|
||||
std::array<std::int64_t, 3> extent_array(VoxelBounds bounds) noexcept {
|
||||
return {bounds.upper.x - bounds.lower.x, bounds.upper.y - bounds.lower.y,
|
||||
bounds.upper.z - bounds.lower.z};
|
||||
}
|
||||
VoxelPosition normal_for(std::size_t axis, int sign) noexcept {
|
||||
if (axis == 0) return {sign, 0, 0};
|
||||
if (axis == 1) return {0, sign, 0};
|
||||
return {0, 0, sign};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VoxelScene::VoxelScene(VoxelRegion region, Void::Uuid::Uuid session,
|
||||
VoxelSceneOptions options, VoxelBounds visible)
|
||||
: region_(std::move(region)), session_(session), options_(options), visible_(visible) {}
|
||||
|
||||
bool VoxelScene::current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept {
|
||||
return session == session_ && region.descriptor() == region_.descriptor() &&
|
||||
std::all_of(reads_.begin(), reads_.end(), [&](auto stamp) { return region.matches(stamp); });
|
||||
}
|
||||
|
||||
std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError> prepare_voxel_scene(
|
||||
const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options) {
|
||||
const auto& bounds = options.bounds;
|
||||
const auto& region_bounds = region.descriptor().bounds;
|
||||
const auto& limits = options.limits;
|
||||
if (bounds.lower.x < region_bounds.lower.x || bounds.lower.y < region_bounds.lower.y ||
|
||||
bounds.lower.z < region_bounds.lower.z || bounds.upper.x > region_bounds.upper.x ||
|
||||
bounds.upper.y > region_bounds.upper.y || bounds.upper.z > region_bounds.upper.z ||
|
||||
bounds.lower.x >= bounds.upper.x || bounds.lower.y >= bounds.upper.y ||
|
||||
bounds.lower.z >= bounds.upper.z || limits.max_axis <= 0) {
|
||||
return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
}
|
||||
const auto extents = extent_array(bounds);
|
||||
for (auto extent : extents) {
|
||||
// The shader uses float local vertices. Keep all cell corners exact,
|
||||
// including the upper endpoint, even if a caller raises its budget.
|
||||
if (extent > limits.max_axis || extent > 65536) return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
}
|
||||
auto visible = bounds;
|
||||
visible.upper.z = std::max(bounds.lower.z,
|
||||
std::min(bounds.upper.z, std::int64_t{options.slice} + 1));
|
||||
auto cells = Void::Numeric::checked_mul(static_cast<std::size_t>(extents[0]),
|
||||
static_cast<std::size_t>(extents[1]));
|
||||
if (cells) cells = Void::Numeric::checked_mul(*cells,
|
||||
static_cast<std::size_t>(visible.upper.z - visible.lower.z));
|
||||
if (!cells || *cells > limits.max_cells) return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
|
||||
try {
|
||||
auto scene = std::shared_ptr<VoxelScene>(new VoxelScene(region, session, options, visible));
|
||||
std::size_t face_count = 0;
|
||||
const auto record_read = [&](ChunkStamp stamp) {
|
||||
const auto at = std::lower_bound(scene->reads_.begin(), scene->reads_.end(), stamp.coordinate,
|
||||
[](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; });
|
||||
if (at != scene->reads_.end() && at->coordinate == stamp.coordinate) return true;
|
||||
if (scene->reads_.size() >= limits.max_read_chunks ||
|
||||
!within_budget(face_count, scene->reads_.size() + 1, limits.max_bytes)) return false;
|
||||
scene->reads_.insert(at, stamp);
|
||||
return true;
|
||||
};
|
||||
// First pass counts and records dependencies before allocating faces.
|
||||
// Second pass reads the same held immutable pages and fills exact capacity.
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
for (auto z = visible.lower.z; z < visible.upper.z; ++z) {
|
||||
for (auto y = visible.lower.y; y < visible.upper.y; ++y) {
|
||||
for (auto x = visible.lower.x; x < visible.upper.x; ++x) {
|
||||
const VoxelPosition cell{static_cast<std::int32_t>(x),
|
||||
static_cast<std::int32_t>(y), static_cast<std::int32_t>(z)};
|
||||
const auto sample = region.sample(cell);
|
||||
if (pass == 0 && !record_read(sample.stamp))
|
||||
return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
if (!solid(sample)) continue;
|
||||
for (auto normal : normals) {
|
||||
const auto next = neighbor(cell, normal);
|
||||
if (next && visible.contains(*next)) {
|
||||
const auto beside = region.sample(*next);
|
||||
if (pass == 0 && !record_read(beside.stamp))
|
||||
return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
if (solid(beside)) continue;
|
||||
}
|
||||
if (pass == 0) {
|
||||
if (face_count >= limits.max_faces) return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
++face_count;
|
||||
if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes))
|
||||
return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
} else {
|
||||
scene->faces_.push_back({cell, normal, sample.material,
|
||||
sample.availability == VoxelAvailability::Unavailable});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pass == 0) {
|
||||
if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes))
|
||||
return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
scene->faces_.reserve(face_count);
|
||||
}
|
||||
}
|
||||
return scene;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
} catch (const std::length_error&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
bool valid_voxel_camera(const VoxelCamera& camera) noexcept {
|
||||
// D3D11 maximum 2D resource dimension, with finite practical shader inputs.
|
||||
// Tiny/huge scales cannot identify a cell in a pixel and are refused.
|
||||
return camera.width > 0 && camera.width <= 16384 && camera.height > 0 && camera.height <= 16384 &&
|
||||
std::isfinite(camera.origin_x) && std::abs(camera.origin_x) <= 1e7 &&
|
||||
std::isfinite(camera.origin_y) && std::abs(camera.origin_y) <= 1e7 &&
|
||||
std::isfinite(camera.scale) && camera.scale >= 0.01 && camera.scale <= 256 &&
|
||||
std::isfinite(camera.tile_half_width) && camera.tile_half_width >= 1 && camera.tile_half_width <= 256 &&
|
||||
std::isfinite(camera.tile_half_height) && camera.tile_half_height >= 1 && camera.tile_half_height <= 256;
|
||||
}
|
||||
|
||||
std::optional<ScreenPoint> project_voxel_point(const VoxelScene& scene,
|
||||
const VoxelCamera& camera, VoxelPoint point) noexcept {
|
||||
if (!valid_voxel_camera(camera) || !finite(point)) return std::nullopt;
|
||||
const auto lower = scene.options().bounds.lower;
|
||||
point = point - VoxelPoint{static_cast<double>(lower.x), static_cast<double>(lower.y), static_cast<double>(lower.z)};
|
||||
const ScreenPoint result{camera.origin_x + camera.scale * (point.x - point.y) * camera.tile_half_width,
|
||||
camera.origin_y + camera.scale * ((point.x + point.y) * camera.tile_half_height - point.z * elevation_pixels)};
|
||||
if (!std::isfinite(result.x) || !std::isfinite(result.y)) return std::nullopt;
|
||||
return result;
|
||||
}
|
||||
|
||||
std::uint32_t voxel_face_color(const VoxelFace& face) noexcept {
|
||||
std::array<std::uint32_t, 3> color{128, 132, 140};
|
||||
if (!face.unavailable) {
|
||||
switch (face.material) {
|
||||
case MaterialId::Soil: color = {166, 119, 70}; break;
|
||||
case MaterialId::Stone: color = {130, 143, 157}; break;
|
||||
case MaterialId::DoorClosed: color = {184, 99, 46}; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
const std::uint32_t percent = face.normal.z > 0 ? 100u : face.normal.x != 0 ? 82u :
|
||||
face.normal.y != 0 ? 66u : 50u;
|
||||
for (auto& channel : color) channel = channel * percent / 100u;
|
||||
return (color[0] << 16u) | (color[1] << 8u) | color[2];
|
||||
}
|
||||
|
||||
bool VoxelPick::current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept {
|
||||
return session == current_session && region == world.descriptor().id &&
|
||||
std::all_of(reads.begin(), reads.end(), [&](auto stamp) { return world.matches(stamp); });
|
||||
}
|
||||
|
||||
std::expected<VoxelPick, VoxelSceneError> trace_voxels(
|
||||
const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits) {
|
||||
if (!finite(ray.origin) || !finite(ray.direction) || !std::isfinite(ray.max_distance) ||
|
||||
ray.max_distance < 0) return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
const double magnitude = std::max({std::abs(ray.direction.x), std::abs(ray.direction.y), std::abs(ray.direction.z)});
|
||||
if (magnitude == 0) return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
// Power-of-two scaling preserves represented component ratios. Dividing by
|
||||
// a Euclidean norm first would turn a 1:3 exact corner tie into two steps.
|
||||
int exponent = 0;
|
||||
std::frexp(magnitude, &exponent);
|
||||
const std::array<long double, 3> direction{std::scalbn(static_cast<long double>(ray.direction.x), -exponent),
|
||||
std::scalbn(static_cast<long double>(ray.direction.y), -exponent),
|
||||
std::scalbn(static_cast<long double>(ray.direction.z), -exponent)};
|
||||
const auto length = std::hypot(direction[0], direction[1], direction[2]);
|
||||
VoxelPick result;
|
||||
result.region = scene.region().descriptor().id;
|
||||
result.session = scene.session();
|
||||
const auto bounds = scene.visible_bounds();
|
||||
if (empty(bounds)) return result;
|
||||
const auto lower = lower_array(bounds);
|
||||
const auto extent = extent_array(bounds);
|
||||
const std::array<long double, 3> origin{static_cast<long double>(ray.origin.x) - lower[0],
|
||||
static_cast<long double>(ray.origin.y) - lower[1], static_cast<long double>(ray.origin.z) - lower[2]};
|
||||
std::array<int, 3> step{};
|
||||
std::array<long double, 3> entry{};
|
||||
long double start = 0, finish = ray.max_distance / length;
|
||||
for (std::size_t axis = 0; axis < 3; ++axis) {
|
||||
if (!std::isfinite(origin[axis])) return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
step[axis] = direction[axis] > 0 ? 1 : direction[axis] < 0 ? -1 : 0;
|
||||
if (step[axis] == 0) {
|
||||
if (origin[axis] < 0 || origin[axis] >= extent[axis]) return result;
|
||||
entry[axis] = -std::numeric_limits<long double>::infinity();
|
||||
continue;
|
||||
}
|
||||
const auto a = -origin[axis] / direction[axis];
|
||||
const auto b = (extent[axis] - origin[axis]) / direction[axis];
|
||||
entry[axis] = std::min(a, b);
|
||||
start = std::max(start, entry[axis]);
|
||||
finish = std::min(finish, std::max(a, b));
|
||||
}
|
||||
if (start > finish || !std::isfinite(start)) return result;
|
||||
std::array<std::int64_t, 3> cell{};
|
||||
VoxelPosition normal{};
|
||||
bool has_normal = false;
|
||||
for (std::size_t axis = 0; axis < 3; ++axis) {
|
||||
auto point = std::fma(direction[axis], start, origin[axis]);
|
||||
if (entry[axis] == start) point = step[axis] > 0 ? 0 : static_cast<long double>(extent[axis]);
|
||||
if (!std::isfinite(point) || point < 0 || point > extent[axis])
|
||||
return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
const auto floor = std::floor(point);
|
||||
cell[axis] = static_cast<std::int64_t>(floor) - (step[axis] < 0 && point == floor ? 1 : 0);
|
||||
if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result;
|
||||
if (!has_normal && step[axis] != 0 && point == floor) {
|
||||
normal = normal_for(axis, -step[axis]);
|
||||
has_normal = true;
|
||||
}
|
||||
}
|
||||
try {
|
||||
auto distance = start;
|
||||
for (std::size_t walked = 0; ; ++walked) {
|
||||
if (walked >= limits.max_steps) return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
const VoxelPosition absolute{static_cast<std::int32_t>(lower[0] + cell[0]),
|
||||
static_cast<std::int32_t>(lower[1] + cell[1]), static_cast<std::int32_t>(lower[2] + cell[2])};
|
||||
const auto sample = scene.region().sample(absolute);
|
||||
if (!record(result.reads, sample.stamp, limits.max_read_chunks))
|
||||
return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
if (solid(sample)) {
|
||||
result.status = sample.availability == VoxelAvailability::Unavailable ? VoxelPickStatus::Unavailable :
|
||||
has_normal ? VoxelPickStatus::Hit : VoxelPickStatus::Inside;
|
||||
result.cell = absolute;
|
||||
result.normal = normal;
|
||||
if (has_normal) result.adjacent = neighbor(absolute, normal);
|
||||
result.material = sample.material;
|
||||
result.distance = static_cast<double>(distance * length);
|
||||
return result;
|
||||
}
|
||||
std::array<long double, 3> crossing{};
|
||||
for (std::size_t axis = 0; axis < 3; ++axis) {
|
||||
crossing[axis] = step[axis] == 0 ? std::numeric_limits<long double>::infinity() :
|
||||
(static_cast<long double>(cell[axis] + (step[axis] > 0 ? 1 : 0)) - origin[axis]) / direction[axis];
|
||||
}
|
||||
const auto next = *std::min_element(crossing.begin(), crossing.end());
|
||||
if (next > finish || !std::isfinite(next)) return result;
|
||||
// A distance too large to represent successive voxel planes is not
|
||||
// safe for a selection. Refuse rather than returning an arbitrary cell.
|
||||
if (next <= distance) return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
has_normal = false;
|
||||
for (std::size_t axis = 0; axis < 3; ++axis) {
|
||||
if (crossing[axis] != next) continue;
|
||||
cell[axis] += step[axis];
|
||||
if (!has_normal) {
|
||||
normal = normal_for(axis, -step[axis]);
|
||||
has_normal = true;
|
||||
}
|
||||
if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result;
|
||||
}
|
||||
distance = next;
|
||||
}
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
} catch (const std::length_error&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<VoxelRay, VoxelSceneError> voxel_screen_ray(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point) {
|
||||
if (!valid_voxel_camera(camera) || !std::isfinite(point.x) || !std::isfinite(point.y) ||
|
||||
point.x < 0 || point.y < 0 || point.x >= camera.width || point.y >= camera.height)
|
||||
return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
const auto bounds = scene.visible_bounds();
|
||||
const double z = static_cast<double>(bounds.upper.z - bounds.lower.z);
|
||||
const double u = (point.x - camera.origin_x) / (camera.scale * camera.tile_half_width);
|
||||
const double v = (point.y - camera.origin_y) / (camera.scale * camera.tile_half_height);
|
||||
const double elevated = v + z * elevation_pixels / camera.tile_half_height;
|
||||
VoxelRay ray{{(u + elevated) * 0.5 + static_cast<double>(bounds.lower.x),
|
||||
(elevated - u) * 0.5 + static_cast<double>(bounds.lower.y), static_cast<double>(bounds.upper.z)},
|
||||
{-1, -1, -2 * camera.tile_half_height / elevation_pixels}, 0};
|
||||
ray.max_distance = z * std::hypot(ray.direction.x, ray.direction.y, ray.direction.z) / -ray.direction.z;
|
||||
return ray;
|
||||
}
|
||||
|
||||
std::expected<VoxelPick, VoxelSceneError> pick_voxel_screen(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits) {
|
||||
const auto ray = voxel_screen_ray(scene, camera, point);
|
||||
if (!ray) return std::unexpected(ray.error());
|
||||
return trace_voxels(scene, *ray, limits);
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
|
||||
#include "map_camera.hpp"
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
#include <Void/Math/Vec.hpp>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
using VoxelPoint = Void::Math::Vec3<double>;
|
||||
|
||||
struct VoxelCamera {
|
||||
int width = 0, height = 0;
|
||||
// Screen position of the lower corner of the prepared display bounds.
|
||||
double origin_x = 0, origin_y = 0;
|
||||
double scale = 1;
|
||||
double tile_half_width = 12, tile_half_height = 7;
|
||||
};
|
||||
struct VoxelSceneLimits {
|
||||
std::size_t max_cells = 2 * 1024 * 1024;
|
||||
std::size_t max_faces = 262144;
|
||||
std::size_t max_read_chunks = 1024;
|
||||
// Faces, read directory capacity and expanded CPU vertices. Shared source
|
||||
// pages, allocator overhead, retained older scenes and GPU memory are separate.
|
||||
std::size_t max_bytes = 64 * 1024 * 1024;
|
||||
std::int64_t max_axis = 4096;
|
||||
};
|
||||
struct VoxelSceneOptions {
|
||||
// An explicit display volume bounds work even in an enormous sparse region.
|
||||
VoxelBounds bounds;
|
||||
std::int32_t slice = 0; // Highest displayed cell, inclusive.
|
||||
VoxelSceneLimits limits;
|
||||
};
|
||||
enum class VoxelSceneError {
|
||||
InvalidInput, LimitExceeded, AllocationFailed
|
||||
};
|
||||
struct VoxelFace {
|
||||
VoxelPosition cell;
|
||||
VoxelPosition normal;
|
||||
MaterialId material = MaterialId::Air;
|
||||
bool unavailable = false;
|
||||
bool operator==(const VoxelFace&) const = default;
|
||||
};
|
||||
|
||||
class VoxelScene {
|
||||
public:
|
||||
[[nodiscard]] const VoxelRegion& region() const noexcept { return region_; }
|
||||
[[nodiscard]] const Void::Uuid::Uuid& session() const noexcept { return session_; }
|
||||
[[nodiscard]] const VoxelSceneOptions& options() const noexcept { return options_; }
|
||||
[[nodiscard]] const VoxelBounds& visible_bounds() const noexcept { return visible_; }
|
||||
[[nodiscard]] std::span<const VoxelFace> faces() const noexcept { return faces_; }
|
||||
[[nodiscard]] std::span<const ChunkStamp> reads() const noexcept { return reads_; }
|
||||
[[nodiscard]] bool current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept;
|
||||
private:
|
||||
friend std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
|
||||
prepare_voxel_scene(const VoxelRegion&, const Void::Uuid::Uuid&, VoxelSceneOptions);
|
||||
VoxelScene(VoxelRegion region, Void::Uuid::Uuid session, VoxelSceneOptions options, VoxelBounds visible);
|
||||
VoxelRegion region_;
|
||||
Void::Uuid::Uuid session_;
|
||||
VoxelSceneOptions options_;
|
||||
VoxelBounds visible_;
|
||||
std::vector<VoxelFace> faces_;
|
||||
std::vector<ChunkStamp> reads_;
|
||||
};
|
||||
|
||||
// Missing cells are opaque gray terrain boundaries. Picks stop there with
|
||||
// Unavailable so loaded geometry cannot be selected through unknown space.
|
||||
[[nodiscard]] std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
|
||||
prepare_voxel_scene(const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options);
|
||||
[[nodiscard]] bool valid_voxel_camera(const VoxelCamera& camera) noexcept;
|
||||
[[nodiscard]] std::optional<ScreenPoint> project_voxel_point(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, VoxelPoint point) noexcept;
|
||||
[[nodiscard]] std::uint32_t voxel_face_color(const VoxelFace& face) noexcept;
|
||||
|
||||
struct VoxelRay {
|
||||
VoxelPoint origin;
|
||||
VoxelPoint direction;
|
||||
double max_distance = 0;
|
||||
};
|
||||
struct VoxelPickLimits {
|
||||
std::size_t max_steps = 16384;
|
||||
std::size_t max_read_chunks = 1024;
|
||||
};
|
||||
enum class VoxelPickStatus { Miss, Hit, Inside, Unavailable };
|
||||
struct VoxelPick {
|
||||
RegionId region = 0;
|
||||
Void::Uuid::Uuid session;
|
||||
VoxelPickStatus status = VoxelPickStatus::Miss;
|
||||
VoxelPosition cell;
|
||||
VoxelPosition normal; // Zero for an initial occupied cell with no crossed face.
|
||||
std::optional<VoxelPosition> adjacent; // May be outside the region. Validate before placement.
|
||||
MaterialId material = MaterialId::Air;
|
||||
double distance = 0;
|
||||
std::vector<ChunkStamp> reads;
|
||||
[[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept;
|
||||
};
|
||||
|
||||
// Cells are [x,x+1). At an exact plane the direction selects the forward cell.
|
||||
// A zero component stays in the half-open cell owning that coordinate.
|
||||
// Simultaneous plane crossings advance all tied axes, selecting normal X/Y/Z
|
||||
// in that priority order. Cells touched only along an edge are skipped.
|
||||
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> trace_voxels(
|
||||
const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits = {});
|
||||
[[nodiscard]] std::expected<VoxelRay, VoxelSceneError> voxel_screen_ray(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point);
|
||||
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> pick_voxel_screen(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits = {});
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
Текущий план разработки расположен в [PLAN.md](../../PLAN.md). Ниже сохранена история предыдущего этапа интеграции.
|
||||
|
||||
В M02 проверены каталог изменяемых воксельных страниц и поиск пути на нескольких высотах. В объединённом коммите `14987b2` под Wine прошли 210 проверок ядра, 17 LAN, 15 клиентского сеанса, шесть проверок управления заказами в окне и испытание кадра D3D11. Житель высотой две клетки учитывает ступени, проёмы и границу области поиска. Работа в игре над верхней площадкой, выдача добычи, сохранение и показ слоя находятся в реализации. [Ход M02](../plan/milestones/M02.md#проверенный-каталог-и-навигация) · [Проверка кода](tasks/M02-V1.md)
|
||||
|
||||
Программная приёмка M01 завершена на `4bac17d` для Windows x64 под Wine. Проверены потактное воспроизведение, перенос и возврат имущества, исторические сохранения, управление заказами, оба профиля правил, совместимость с прежним клиентом в обеих ролях и кадры во время ожидания. Пять исполняемых наборов прошли полностью. Для M02 доступны подтверждённые границы мира, сеанса, команд, сохранений и отображения. [Результаты M01](../plan/milestones/M01.md#приёмка-реализации-m01) · [Экономика и кодек](tasks/M01-V14.md) · [Сеть и клиент](tasks/M01-V15.md)
|
||||
|
||||
As of 2026-12-02, the baseline is `74b89ae` on `chore/integrate-void-library`. The tracked checkout was clean at discovery. The project targets Windows x64, MSYS2 UCRT64 and Direct3D 11.
|
||||
|
||||
The user approved pinning Void to `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, adopting Binary and Core for saves and LAN, and migrating the reflection suites to Void Testing. The Windows build uses CMake 4+ and GCC 16. Use a configurable agent with Astra 6.2 XHigh for planning and independent review and Sol 6.2 XHigh for implementation, as approved by the user.
|
||||
@@ -59,3 +63,43 @@ ctest --test-dir "$SETTLEMENT_VERIFY/candidate" -V --output-on-failure
|
||||
Из корня игры собрана свежая Windows x64 Release в отдельном каталоге с закреплённым исходным деревом Void, CMake 4.5.0, GCC 16.2.0 и Ninja. Команды `cmake --build <build-dir> --parallel 8` и `ctest --test-dir <build-dir> -V --output-on-failure` под Wine 11 дали 28/28 случаев ядра и 4/4 LAN. Результат относится к кросс-сборке. Аппаратные измерения Windows и изготовление материалов относятся к следующим этапам.
|
||||
|
||||
[Итоговая проверка M00-V](tasks/M00-V.md) приняла этот срез и передачу M01. Проверены 80 идентификаторов, 43 документа и 1 041 локальная ссылка до добавления данной записи, хеши иконок, подключение ресурсов и журналы исходной сборки. Обход остальных исторических изменений, приёмка игровых сценариев и права на будущие файлы остаются открытыми.
|
||||
|
||||
## M01. Последовательный эталон и журнал
|
||||
|
||||
Пользователь подтвердил полный план, локальные коммиты и отправку веток этапов и систем в origin. M00 принят и опубликован в `milestone/m00-inventory` на `904bdf8`. Ветка `milestone/m01-authoritative-simulation` создана от него. Первая поставка S01 включает [режим мира](tasks/M01-C.md) и [пять сценариев воспроизведения](tasks/M01-T.md).
|
||||
|
||||
Под Wine 11 новая Windows x64 Release прошла 33/33 теста ядра и 4/4 LAN. Селектор `settlement_core_tests.exe --tag replay` выполнил пять новых случаев. Журнал из десяти команд дал 750 тактов с одинаковыми сохранениями в эталоне и на 2/6/12 потоках, включая продолжение с материалом в руках. Отдельная программа, собранная сначала с заголовками и ядром до M01, затем с новым ядром, сравнила квитанции и сохранения после каждой из 365 попыток шага. При 361 такте и пяти съеденных порциях все четыре режима совпали с прототипом по всем 738 386 байтам. [Итог M01-V1](tasks/M01-V1.md) — **READY** для эталона и тестов.
|
||||
|
||||
Контрольные команды из корня игры, в окружении кросс-сборки из записи выше:
|
||||
|
||||
```sh
|
||||
cmake --build /tmp/stoneheart-milestones.xprJ2SVp/windows --parallel 8
|
||||
ctest --test-dir /tmp/stoneheart-milestones.xprJ2SVp/windows -V --output-on-failure
|
||||
wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag replay
|
||||
```
|
||||
|
||||
Далее в M01 входят исполнитель Void с проверкой отказов, манифесты правил, авторитетный диспетчер команд, фоновый такт, снимки и транзакционная загрузка/запись. Приёмка этих систем ведётся отдельными коммитами.
|
||||
|
||||
### Ветки разработки и запросы на слияние
|
||||
|
||||
Для этапов используются ветки `milestone/*`, для систем — `system/*`. По поручению пользователя ветка [integration/roadmap](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/src/branch/integration/roadmap) содержит `chore/integrate-void-library`, `chore/plans` и принятые изменения каждой ветки этапа и системы. После проверки совместной сборки ответственный обновляет накопительную ветку. Она служит для получения всей работы одним checkout.
|
||||
|
||||
У каждой опубликованной рабочей ветки есть свой запрос в `main`. Описание ссылается на более ранние запросы этой серии. При параллельной работе подписи ссылок указывают, какие изменения послужили базой и какие развивались независимо. Новые коммиты ветки попадают в уже открытый запрос. Первыми открыты [VoidLibrary #3](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/3), [план #4](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/4), [M00 #5](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/5), [M01 #6](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/6), [модули правил S19 #7](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/7), [исполнитель S01 #8](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/8), [диспетчер S16 #9](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) и [сохранения S15 #10](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/10).
|
||||
|
||||
В `2224299` вместе собраны снимки мира, диспетчер команд, служба записи и кодек контрольных точек. Windows x64 Release под Wine прошла 82 из 82 случаев ядра и 4 из 4 LAN. Отдельная ветка S15 на `db4ac30` прошла 59 из 59 и 4 из 4 соответственно. По трём прогонам на поле 80×80 с шестью потоками медианы p50/p95 захвата снимка составили 2/4 мкс для 50 жителей и 23/68 мкс для 500. После 32 тактов прогрева каждый прогон измерял 240 захватов. При подключении службы записи к окну лимит одного файла должен вмещать `max_checkpoint_bytes`. Частота тактов, отзывчивость окна во время записи и работа на физической Windows проверяются отдельно. [Проверка команд и записи](tasks/M01-V4.md) · [Проверка снимка и контрольной точки](tasks/M01-V5.md) · [Совместная сборка](tasks/M01-V6.md) · [План постоянных ссылок](tasks/M01-P3.md)
|
||||
|
||||
В `cf0cc2f` объединены проверенные коммиты S19 `de38aff` и S01 `68f91a2`. После объединения под Wine 11 прошли 51 из 51 теста ядра и 4 из 4 тестов LAN, включая формат сохранений 13 и протокол 11. Независимый проверяющий сверил обе родительские версии, наследование параметров компиляции и встроенную реализацию SHA-256. [План владельца симуляции](tasks/M01-P2.md) · [Проверка библиотеки](tasks/M01-R2.md) · [Разбор отказов](tasks/M01-F2.md) · [Принятые контракты](tasks/M01-F3.md) · [Проверка S01 и S19](tasks/M01-V2.md) · [Проверка интеграции](tasks/M01-V3.md)
|
||||
|
||||
Срез S06 сохранил ссылки на склады и источники при удалении более раннего элемента. Два контрольных набора из 738 386 и 393 857 байтов совпали со старой сборкой в последовательном режиме и на 2/6/12 потоках. Второй набор включает разбор склада во время многоэтапной доставки. Изменения опубликованы отдельно в [S06 #11](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11). В `4ba64f7` также вошла фоновая подготовка старых и новых сохранений. В объединённой Windows x64-сборке под Wine прошли 106 тестов ядра и 4 LAN. Публичный аналог ограниченного чтения в Windows отслеживается в [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). [Проверка двух компонентов](tasks/M01-V8.md) · [Интеграционная проверка](tasks/M01-V9.md)
|
||||
|
||||
Хост протокола 11 теперь передаёт приказы авторитетной симуляции, а гость получает подтверждение и снимок завершённого состояния. После смены сеанса старому гостю требуется новое подключение. Старая и новая сборки обменялись приказами в обеих ролях. В `aa4e271` под Wine прошли 106 из 106 тестов ядра и 9 из 9 LAN. Отдельно проверены переподключение при незавершённом приказе и разные правила нумерации отклонённых приказов у старого клиента и нового владельца. [Ветка S16](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) · [Проверка интеграции](tasks/M01-V10.md)
|
||||
|
||||
В `a8cd7bb` объединены заказы с постоянными ID и два варианта правил строительства кровати. Формат контрольной точки 2 сохраняет ID заказов и следующий свободный ID. Прежние контрольные точки и обычные сохранения версии 13 продолжают загружаться. Оба варианта правил прошли строительство реальных кроватей, сохранение во время доставки и сравнение продолжений на 1/2/6/12 исполнителях. В объединённой сборке под Wine прошли 122 теста ядра и 9 LAN. Аппаратная Windows ещё не проверена. [Заказы S04](../plan/systems/S04.md) · [Правила S19](../plan/systems/S19.md) · [Интеграционная проверка](tasks/M01-V11.md)
|
||||
|
||||
Клиент Windows в `db0a872` обрабатывает действия игрока по квитанциям владельца и рисует из неизменяемого снимка. Три отдельных процесса под Wine проверили создание партии, паузу в меню и окне выбора файла, запись, современное и прежнее сохранения и отказ при повреждении файла. Отдельно проверены подтверждение разбора при смене партии, сохранение гостевой колонии после неудачного переподключения и возобновление тактов после восстановления. В общей сборке прошли 122 теста ядра, 9 LAN и 10 клиента. [Клиент S18](../plan/systems/S18.md) · [Проверка с обеими родительскими ветками](tasks/M01-V10.md)
|
||||
|
||||
В `37fb6a8` объединены проверяемая передача всего груза одной остановки и выбор правил на титульном экране. Игрок может создать поселение с поэтапной сборкой кровати либо с рецептом из одной доски. При открытии сохранения восстанавливается его собственный набор правил. Испытание настоящего окна проверило оба выбора мышью и клавиатурой, файл и продолжение из нового процесса. В общей сборке под Wine прошли 136 тестов ядра, 9 LAN и 14 клиента. [Загрузка и инвентарь S06](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11) · [Клиент S18](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/13) · [Совместная проверка](tasks/M01-V12.md)
|
||||
|
||||
В `048268a` две настоящие рабочие задачи завершаются в противоположном порядке. Во всех 24 воспроизведениях победитель спорной заявки и байты состояния совпали с последовательной партией. При загрузке более старого мира запоздалый результат не изменил новую партию. Windows x64 под Wine прошла 141 тест ядра, 9 LAN и 14 клиента. [Проверки S21](../plan/systems/S21.md) · [Интеграционная проверка](tasks/M01-V13.md) · [Управляемый порядок завершения в VoidLibrary](https://git.faumaray.com/Void/Library/issues/15)
|
||||
|
||||
В `455630f` камера отвечает на колесо мыши и перетаскивание, пока симуляция или запись файла задержана. Проверка настоящего окна сравнила пиксели и байты контрольной точки, воспроизвела замену мира между опросом и рисованием и проверила сохранение прежнего кадра. Под Wine прошли 141 тест ядра, 9 LAN, 14 клиента и отдельное испытание кадра с видимой цепочкой D3D11 и WARP. Проверка в нескольких процессах также подтвердила выбор и загрузку обоих рецептов кровати. Частота кадров на физическом Windows-ПК ещё не измерена. [Рендерер S17](../plan/systems/S17.md) · [Совместная проверка](tasks/M01-V13.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
# Run the same world kernels in an explicit serial reference mode
|
||||
|
||||
Task ID: M01-C
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation, M00 checkpoint 904bdf8. Legacy task notes/.serena are user work. M00-P/F and M01-R established the prototype's three worker sites and checked the pinned Void APIs.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement the first M01 execution seam: an explicit true serial reference and the existing threaded game mode for World construction and load.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Work only on simulation execution selection, including path selection/route/advancement. Keep normal CLI, viewer, LAN, wire bytes, command behavior and parallel executor compatible.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect engine/include/settlement/core/world.hpp, engine/src/{world,world_save}.cpp, worker_pool.hpp/cpp, tests/core_tests.cpp, docs/plan/milestones/M01.md and docs/plan/void-library.md. choose_jobs, find_path and advance_agents already exist in World.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp
|
||||
You are not alone in this checkout. Other authors own tests and CMake; root owns docs and Git. Do not revert others' work.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Add the explicit mode to World construction and read_save. Validate count/mode before stepping. For serial work call the same domain kernels on the caller thread: compute all candidate choices against one starting state before committing winners, run the same find_path and apply requests in the same order, advance agents for the whole range once and sum actual completions. Preserve existing chunking and order in threaded mode. Use direct domain calls and avoid building any generic executor or new state codec.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW settlement::ExecutionMode::{Parallel, SerialReference}. World(seed,w,h, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel); World::read_save(stream, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel). Parallel accepts 2..64 as today. SerialReference requires logical count 1, creates zero OS workers and reports worker_count()==1. Reject invalid combinations/unknown enum with std::invalid_argument. Configuration is local and never serialized. Other source-compatible choices inside these paths are discretionary.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Tests owner will use frozen interface immediately. Preserve save v13 fixture, old versions, LAN 11, performance of ordinary pool dispatch and its current lifetimes. Pinned Void covers binary/test primitives; game-specific direct invocation adds no generic library facility. ThreadExecutor migration has its own later failure/performance contract.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Account for no agents/jobs, paused world, one resident, fewer agents than workers, competing jobs, retries for unreachable routes, reload and cache state. Keep parallel error behavior; do not broaden lifetime hazards. No detached tasks or implicit threads in serial.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Serial mode reaches all 3 sites without a worker pool. 2. Invalid ordinary counts still fail, valid serial passes constructor and load. 3. Exact v13 save bytes and outcomes match 2/6/12 for useful scenarios. 4. Default behavior and old consumers compile.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
From game root source /tmp/stoneheart-verify.KoZwE4o8/env.sh; then cmake --build "$SETTLEMENT_VERIFY/candidate" --parallel 8 --target settlement_core. Use git diff --check and inspect actual diff. Tell root/tests when implementation compiles; tests use another build directory and root runs integrated suites.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not alter other files, registry, network, branch or legacy pool, stage/commit or spawn. Escalate a required interface change and report errors before changing approach twice.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved starting the roadmap on per-milestone branches and parallel subagents. Root selected first M01 replay increment after independent preflight.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-C status, changed paths/symbols, mode and ordering decisions, commands/results, untested paths and integration notes.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Preflight the rules, executor and authoritative runtime packages
|
||||
|
||||
Task ID: M01-F2
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Game root /home/faumaray/Projects/stoneheart_at_home on milestone/m01-authoritative-simulation, M00 at 904bdf8, M01 serial tranche under separate final review. User authorized the entire roadmap with remote pushes by milestone/system.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Check next M01 system contracts before implementation. Prioritize a verdict for independent S19 rules and S01 Void pool migration, then S16 authority, S15 persistence and S01 viewer runtime.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Review technical design/failure boundaries and independent branch ownership. Later M02+ behavior is outside this preflight; the existing prototype remains runnable while these staged features integrate.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect plans M01, S01/S15/S16/S19, world.hpp/cpp, world_save.cpp, app/viewer_win32.cpp, app/lan_session_win32.cpp, engine/include/settlement/core/worker_pool.hpp, CMakeLists.txt. For Void check docs/plan/void-library.md and exact pin headers selected below.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Root owns checkout and branches. Separate system worktrees will isolate CMake/test changes; no new child agents.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S19 proposed bounded UTF-8 strict JSON manifest with namespaced IDs, schema+SemVer versions, definitions/references, dependencies, exclusive capabilities and recomputed per-package SHA256. A selected installed set is transitively resolved, duplicates/missing/range incompatibility/cycles/exclusive conflicts/unknown definitions rejected. Canonical encoding sorted by stable IDs plus exact SemVer incl build and digest frozen with a world/save/network. Reuse Void::Json::Strict, Semver, Algorithms graph and Crypto or report target blockers. Test actual input, deterministic permutation, malformed bounds, meaningful differences. S01 worker migration uses exact-pinned ThreadExecutor and FuturePool with overload retention, startup failure cleanup, draining accepted futures before captured locals unwind, reference and pressure tests plus measured useful work.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S16 proposal: single host dispatcher, trusted transport identity separate from payload, world/session/city/request identity, exact repeat receipt for same payload, conflicting replay/stale epoch has no effect; validation and mutation on owner thread. S01 timer runs fixed interval and publishes shared immutable completed state, live local/guest commands and read-only viewer no longer step/mutate an authoritative World from WM_TIMER. S15 validated candidate swap increments epoch even on rollback, bounded asynchronous immutable snapshot writing, atomic same-volume publication leaves previous data after failure. Rule selection persists + validated before live replacement. Existing sav13/LAN11 continue only by explicit compatibility surfaces.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
M01-P2 maps game code, M01-R2 verifies APIs: SemVer == ignores build so frozen identity uses exact version; Graph input ordering must be canonical. FileSystem atomic_write is unsupported on Windows: an upstream gap issue precedes local fallback. Root integrates M01 branches; public pushes separately authorized.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Consider also capturing mutable UI references/exceptions, pool draining and useful equality after queue pressure, concurrent load/save identity and stale worker results, bounded journal/receipt identity/windows old files. Identify native-only checks explicitly.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Prioritized READY or blockers for S19, S01 pool, and architecture for S01 runtime/S15/S16. 2. Concrete failure/ownership/test requirements and needed refinements. 3. Distinguish M01 goals from M09 public coop/1.0 packaging.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
From game root git diff 904bdf8 --stat; rg -n 'WM_TIMER|read_save|write_save|try_submit|worker_pool_|apply_command' engine app; consult actual upstream pinned StrictJson/Semver/Graph/Crypto/FuturePool public APIs and local source as needed. No writes or builds.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send S19 and pool verdicts early; flag material decisions and applicability. No file edits, external actions, or child agents.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
The user authorized implementing the full plan with subagents, commits and pushes. Root retains integration and system approval.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F2 priority verdicts per package, actionable severity/location/contract fix, tests required, deferred compatibility/work. Do not review your own implementation.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Confirm the exact authority, failure and publication boundaries
|
||||
|
||||
Task ID: M01-F3
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation 8d2870a. M01-F2 identified four gaps. S01 pool and S19 running in separate worktrees. Upstream issues 3/4/5/6 are registered in Void/Library.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Verify the root's concrete decisions below close F2's open failure/identity/order points for starting S16 dispatcher, S15 writer and dependent runtime. Design review only.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Cover S16/s15 independent modules and next runtime ownership, preserved legacy behavior. No release or M09 network exposure.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/agent-workflow/tasks/M01-F2.md, docs/plan/milestones/M01.md, S01/S15/S16, World::apply_command, worker submissions, app/viewer_win32.cpp legacy save/poll/queue cabin and LAN11.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Root owns decisions; no child or shared mutation.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S16 per active epoch: trusted transport passes known client slot separately from payload. World/session are nonnil Void UUIDs, city ID checked. Each authenticated client has monotonically contiguous request numbers starting at 1. Retain every completed result (including rejections) for the active epoch; reserve the record before mutating; check status/city/kind/entire payload equality. On capacity there is backpressure on NEW requests before effects, older cached receipts remain replayable, no eviction/reexecution. Requests behind missing/out-of-order and wrong epoch have distinct transient/nonmutating errors. Envelope ID maps to existing World next sequence only after validation, preserving legacy rejected-reusable sequence behavior. Clients choose new numbers for revised intents. Per-session ledger cap is configurable and explicit. Fresh session discards old history after successful replacement; old envelopes fenced.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S15 independent FIFO bounded single-writer service accepts materialization from a held immutable snapshot, serializes in background, bounded admission returns busy, Windows same-directory exclusive temp + write/flush/close + atomic publication; distinguish before/after visibility. Queue is serialized at admission across slots, so older same-slot save cannot finish after a newer one. Each completion identifies request/tick/epoch; latest UI state checks request ID. Shutdown drains accepted work. Input prepare/validate outside owner; replace only when matching expected old epoch and most recent load request. Corrupt/superseded load changes nothing.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S01 runtime single simulation owner processes bounded requests also during pause and publishes an immutable independent World copy tagged with world, session, tick and publication revision including changes at the same tick. Stage tasks all drained before stack unwind. On ANY tick, command or snapshot preparation failure keep previous published snapshot and discard faulted mutable candidate; no success receipts are exposed for uncommitted changes. Runtime enters faulted and rejects saves/commands until an explicitly validated load restores coherent state under a fresh epoch. UI direct queue_cabin and LAN mutations route through owner; legacy wire stays separate. S19 immutable manifest part of checkpoint compatibility. Root owns interfaces.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Do not silently evict exact-repeat results or claim power-loss guarantees. Check constraints for denial of access or unsupported administrative features. Long-session journal storage beyond M01 replaceable bound documented. Root will record recovery outcome and tests.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Return READY or scoped correction for S16 and S15 first, followed by runtime. 2. List exact stalled/failed operation behavior. 3. Identify remaining prospective tests in rollback, queue capacity, duplicate and concurrency scopes.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
From game root git show -s --format=%H, rg -n 'save_world_file|queue_cabin|World::apply_command|World::step' app engine, inspect referenced existing contracts; no runtime build needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits, branch changes, external writes, children or duplicate investigation. Send early if S16/S15 ready.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Full roadmap approved. Root requested this follow-up specifically to resolve M01-F2 before starting those packages.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F3 READY/CHANGES_REQUIRED per scope with any remaining actionable failures and tests; no edits.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Preflight the real Win32 client, file and LAN owner adapters
|
||||
|
||||
Task ID: M01-F4
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root a4cf99c contains all independently reviewed primitives. S01-04 implementation in /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 at 2224299 awaiting review; public header and 10 tests exist. Planner M01-P2 and preflight F3 defined owner; current WM_TIMER still steps mutable world, saves synchronously and LAN11 poll writes directly.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Check precise adapter design for normal Win32 UI, asynchronous checkpoint files and existing two-slot LAN11, then give per-package green lights or bounded corrective requirements.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only M01 client wiring; existing public co-op compatibility and file use. No new public transport, encryption protocol or broad SDK. Existing S16 modern envelopes can be exercised with 2 internal clients; public network roadmap continues later.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual runtime public header + owner implementation in s01 checkout; viewer_win32.cpp WM_TIMER, start/stop/menus/new/load, local command reporters/blueprint rejection, title_screen; lan_session.hpp/.cpp protocol11 command/sequence/reconnect/send_snapshot, lan_wire; S15 checkpoint/save_service, initial rules catalog and document plan M01.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations, builds, shared Serena switches, branch/remote ops or children. Parent owns produced contracts and commits.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
File adapter (S15) uses one bounded Void background reader and approved SaveService (max_checkpoint_bytes). Caller obtains healthy published snapshot once; producer owns it and encodes on writer thread. Asynchronous load prepare from path/catalog only, with bounded bytes/check signatures, read one open file, legacy World::read_save migrates to new stable UUID/city+default rules; current envelope validates exact installed closure. Keep current 32x32 viewer dimension gate outside generic codec and validate before install. Futures retain immutable data, no background Win32 calls or raw runtime/viewer pointers. Shutdown drains. UI binds a runtime LoadTicket to each admitted load and rejects stale completions by epoch+latest request; report latest save/load per UI slot/request and older save completions must not overwrite newer status.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
LAN11 adapter (S16) keep existing poll(World&) entry/test; add preferred asynchronous host path driven by SimulationRuntime and a guest-only poll requiring no mutable authority. Maintain same exact frames/signature/2 trusted slots. Check authenticated wire request. Legacy numeration is World::next_command_sequence and ordinary domain rejections leave it live, while new envelopes use runtime published next_requests per slot including rejections. Compare incoming wire seq and use authenticated guest slot, serialize per-peer in-flight command so no stale snapshot mapping/multiple executions; return receipt only after committed outcome, current correct next wire sequence. Disconnect/generation/guest changes discard pending network completions without moving effects into new session. Never block network/UI waiting for owner. Exclude new public endpoint. Add verified real host/guest loopback via async path including wrong sequence, rejection and subsequent corrected same old number, reconnect. Keep original fixtures/binary interoperability.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Viewer milestone adapter: one shared_ptr<const World> consistent view (hold for entire frame including nested messages), one SimulationRuntime for offline/host. Guest consumes incoming const views only, transient old host connection fenced. WM_TIMER polls completions/views/network rather than advancing world. New colony/reset creates valid UUID+selected default-compatible manifest; expose real choice where alternative installed packages materially alter game creation (no cosmetic selector). Existing host authority/pause/title/file-dialog gating via set_ticking independent of World::paused; retries when Busy and don't flood queue. Local mutations incl legacy cabin route through runtime. UI needs acknowledged result before applying accepted-only changes; queue/futures and pending metadata reinsert blueprint or report typed rejection, FIFO contiguous modern IDs, handled Busy/OutOfOrder; snapshots can lag while multiple local inputs are pending. Ensure reads and command submission never block on a long tick. Keep modern save normal UI path; legacy saves still load deliberately.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Pay particular attention to Win32 reentrancy, old futures crossing reset/load, modal pickers, latest load after failed reading vs superseded earlier good, rollover UI state if save job from old session finishes, in-flight bounds and trusted peer rebind. A non-default rules subset must be truly compatible with hard-coded prototype game until more rule-driven mechanics land. Avoid accepting incompatible content silently or rejecting legacy corrected retries.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per file adapter, LAN and UI. 2. Concrete interface+tests for each, required handoff order and where existing code enforces assumptions. 3. Clarify what is safe to dispatch immediately and any consequence requiring product choices.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git status --short --branch, scoped rg -n 'WM_TIMER|world->step|handle_save_menu|submit_command|queue_cabin|handle_host|poll\(' app, read targeted actual source. No builds needed. Existing combined 82 core+4 LAN, S01-04 adds ten. Current CLI old baseline cross-version harness /tmp/stoneheart-verify.KoZwE4o8/interop.cpp.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits, external actions or other agents; no extension to public LAN protocol or unwanted UI. Report any ambiguous scope to parent rather than blocking independent file service.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, prior planner/preflight resolved ownership; this concerns concrete client integration choices within M01. Parent handles branches and git operations.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F4 verdict per package, exact corrections and compatibility tests, optional future distinction where implementation depends on another unbuilt seam.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Recheck concrete client and peer lifecycle contracts
|
||||
|
||||
Task ID: M01-F5
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Main at 512c9ef, previous F4 approved S15 and identified two LAN and three UI gates. Revisions are in /home/faumaray/Projects/stoneheart_at_home-worktrees/{s16,s18}/docs/agent-workflow/tasks/{S16-02,S18-01}.md. Runtime header is integrated; CheckpointFiles header is real in s15.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Check added conditions against F4 findings for early per-package approval before implementation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only recheck of contract adequacy, no review of future LAN/UI implementation. S15 already implementing.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read two task documents, M01-F4, normal Win32 title/timer/guest reset and LAN drop_peer lifecycle and actual runtime/CheckpointFiles headers. Match earlier evidence.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote requests/Git actions/children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Verify LAN default-only manifest gate, epoch reconnect, independent receipt tracking across peer turnover, legacy next sequence vs modern committed id and nonblocking completions. Verify viewer completion pump precedes all title returns, no old runtime joins blocking reset/new/join, one writer, receipt-driven bounded one-in-flight queue and profile guard, load supersession and safe guest/offline transition.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Review exact contract not summaries. Flag any missing precondition or undefined API behavior that prevents a worker from safely implementing a nonblocking compatible host/client.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
F4 read-only reviewer pre-existing; parent will perform integration after independent implementation. Root ensures reviewed sibling dependencies available to S18.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Watch stale future from disconnected client, latest failed load, modal reentrancy, old/new slot file ordering and unsupported manifest advertising. Genuine alternative module selection and texture/keyboard features are independently scheduled.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/targeted correction per S16/S18. 2. Bound any remaining actual gap and verification needed. 3. No implied release or approval to merge remotely.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read actual tasks including ownership, tests and stop gates and inspect relevant source from F4. git show 512c9ef --stat optional; no build required.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. Return LAN early if adequately scoped. Stop only for a material remaining omission.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root requests this F4 follow-up after exact corrections and user has authorized roadmap. No remote writes.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F5 S16 and S18 READY/CHANGES_REQUIRED with evidence and residual concrete runtime/native checks.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Recheck production identity safety and preflight a selectable colony rule
|
||||
|
||||
Task ID: M01-F6
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root at 60154bd. S04-01 contract in s04 checkout (4ba64f7) includes the two M01-V9 findings. In S19 M01-P4 examines new world profile selection reusing existing simple vs staged bed paths. Default built-in manifest content must remain compatible.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Immediately recheck S04 exact guards and, separately, preflight the first selectable rules behavior with a validated default/legacy compatibility policy. No actual code review or implementation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only S04-01 revised contract and S19 feature preflight. Exclude further stack/transfer/production implementation.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect s04/docs/agent-workflow/tasks/S04-01.md sections 6–10 and World::edit_object/CommandDispatcher::apply. For S19 read M01-P4, world.cpp bed construction, legacy codec/staged flag, generator/first_colony, rules_manifest, runtime/file/load and default-only LAN contracts. Implementation worktrees outside main have direct read evidence.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children or shared Serena activation. Other workers continue on their own files.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S04 confirm hypothetical exhaustion guards precompute post-demolition totals exactly across all affected supplies before erasing or queue changes, preserve accepted receipt semantics for proved cabin preflight Busy separately from mutation faults. Genuine v1/body1–13 and current2/14 mapping, negative checks and older file test version. Send scoped approval immediately if corrected.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S19 proposal: compiled default first-colony behavior stays staged recipes and two-package original frozen manifest, content digest unchanged; optional exact pinned, additive package selects existing simple/plank recipe path at world creation. Encode enacted policy in World at initialization, existing staged_beds state and manifest saved, normal creation can choose default/alternative. Add game-specific supported profile compiler using actual typed data and package closure; reject unsupported modified digest before installation by viewer, generic resolver/decoder retains broad catalog tools behavior. Important: previous v1 checkpoints and imported historical worlds could legitimately carry DEFAULT manifest with staged_beds=false, and inactive world is valid. Describe migration rule that preserves these old states/bytes; distinguish strict alternate invariant from accepted old default data, and verify clean subsequent saves on current envelope. Future S19/UI APIs and compatibility choices from M01-P4 confirmed by root prior to implementation.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S04 and S19 can use isolated branches; parent serializes shared World/factory/file semantics and S18 normal UI selector after core approval. Keep legacy LAN default-profile-only and preserve old default digest/test fixtures. Do not equate illustrative board ticks=8 with actual compiled tick count.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check nonempty real colony resources/producer/receipt for both bed paths, UI stone vs wood selection, immutable held snapshot and save-load continuation, partial bed materials, old format 1–13 valid imports, malformed optional profile/default unknown package gate, credible negative tests. No fabricated ACE parity.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate S04 corrected or material outstanding. 2. S19 preflight verdict with explicit compatibility and required exact negative/normal tests. 3. Record what can proceed with certainty and facts needing further root commitment.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read actual source/contract targets and M01-P4; compare default manifests/code and World legacy flags; no build required. Check git status/refs to identify exact code.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. Return S04 verdict immediately then S19. No new external service or changes to accepted user scope.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root requests follow-up after exact S04 corrections and planner-backed S19 technical preflight. User authorizes signed-off coding only through root.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F6 two scoped verdicts with evidence, precise blockers/solutions and pending real integration tests.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Check the contract for atomic reserved pickups and client rule selection
|
||||
|
||||
Task ID: M01-F7
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M01 parent 9a248c3 has S19-02 compiled profile and S06-ID data. S04-01 adds production identities and body14 in isolated s04. S18-01 canonical client still in isolated s18 resolving modal input findings. M01-P5 proposed a bounded reserved-quantity pickup used by actual meal and construction stops.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Preflight the first S06 quantity transaction and bounded S18 followup that wires approved profile to the New/Load/Host UI. Return separate actionable corrections before component implementation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
The S06 step preflights a single existing storage→resident pickup atomically, including all materials at one construction stop. Later stack identity, cancel, site ownership and replay ledger remain P5-dependent. S18 selection is only New colony and coherent support/legacy compatibility; no new game settings or traffic.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root world.hpp, world.cpp functions finish_meal_step/advance_construction_delivery/take_reserved_material/finish_production, profile public API/first_colony/tests, s04 working diff and actual s18 viewer_session/viewer_win32/title_screen, LAN default gate, docs S04/S06/S18/S19 and M01-F6.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root decides subsequent contracts and serializes worktrees/CMake changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S06 proposed NEW internal bounded reserved pickup with one validated StorageId per operation, max item_type_count distinct items (all lines at stop aggregated before any mutation), reject zero/None/unknown ID, reserved>physical, insufficient reserved/quantity or target sum overflow using Void::Numeric; commit all source counts/reserve/zero-stack removal/destination changes without further allocation or throwable effects. Success keeps meal, route cursor, order/worker behavior and v13 projection/corpora unchanged. Failure immediately leaves source+inventory and stop/actor bookkeeping unchanged; impossible invariant failure may fault owner while preserving last healthy publication. Existing non-pickup recipe paths must be accounted for. Identify any missing edge or side effect.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S18 followup proposed initial selector defaults staged, allows existing alternative single plank profile in title New, Continue/Open ignores current selection; factory+validator before runtime construct and after latest load prepared, preserve exact default old simple/inactive, refuse forged/extra or optional staged, both immediate and deferred legacy-host gates require exact default, failed admission leaves world/guest unchanged. Rename/conditionally hide staged base UI choices in plank-only worlds; confirm existing placement validation behavior. Verify title keyboard/mouse handling and no accidental persisted settings.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Depends on S19-02 and S18-01 review, S06-02 first consumer should merge after S04-01 with tests and version untouched. Root will own separate follow-up schema migration and M01-P5 final decisions; legacy cancellation compatibility remains.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check non-throwing commit including vector erase/multi-type and destination Inventory bounds, zeros/duplicates, capacity reserve for carpentry and any work cursor mutation. Check modal callbacks/error feedback, unsupported profiles advertised to LAN, save/restore exact active legacy mode.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per contract before dispatch. 2. Concrete trigger and correction for any inconsistency. 3. Exact tests that would fail on a partial batch and incorrect selection or post-load gate. The stages do not approve future implementation.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse at each worktree, scoped rg and direct source/graph coverage. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{tag,ctest}.log and existing client-session/GUI smoke source if needed. No new builds.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No new general inventory database, domain mechanics or UI expansion, no duplicate library issues. Report prerequisites immediately; defer review of actual changes until implemented. No charges/remote operations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, including stable single-owner items, selectable new rules, per-branch publishing and generic Void issues. Root retains mutation authority.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F7 PREFLIGHT disposition for S06 and S18 separately; exact invariants/tests and any blocking oversight backed by existing source.
|
||||
|
||||
Preflight required the pickup owner to validate the post-withdrawal occupancy and the carpentry output slot together, aggregate repeated lines, and preserve the state at pickup entry on rejection. Direct storage-to-recipe conversion keeps its own path. For profile selection, deny starting a legacy host while a replacement is pending, recheck after a modal menu, then check the installed authoritative default manifest immediately before either host call. The simple-bed house preview must describe the actual one-plank recipe for every house type.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Preflight durable custody, legacy projections and replay limits
|
||||
|
||||
Task ID: M01-F8
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root e6a01be includes production IDs, current14/outer2, compiled profiles and verified initial viewer. Quantity batch now ready in isolated s06 at a8cd7bb + changes. Detailed operational proposal from M01-P5 in NEW docs/plan/custody.md. This prescreen concerns the next persistent state model, not approval of implementation.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Examine the complete proposed data/operation/migration contract and find contradictions before assigning parallel core/codec/command owners. Provide first specific corrections quickly and feasible independent interfaces.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S06/S04 custody, bounded receipts, migration from raw1–14, v15/outer3, cancel and LAN legacy projection. Existing numeric/ID tickets #7/#8, duplicate support and preflight-before-mutation apply. No new gameplay or schema publishing yet.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root docs/plan/custody.md, tasks M01-P5/F6/F7, world.hpp, world.cpp, world_save.cpp (codecs, route/phase validation, old limits), checkpoint*, command_dispatcher*, simulation_runtime, actual app/lan_session_win32.cpp legacy publication and viewer costs; s06 new transaction source/consumers. Check existing fixtures and acceptance corpus.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root owns public actions and serializes source. Look at actual code, modern replay and schema context, consulting direct worktree sources for S06.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Check embedded unique stack identities, split/merge and reservation movement, checked monotonic world counters and batch preflight, one owner including production input, exact custody for resources, all recipes, grants, meals, canceled work and demolition, capacity claim backed by claimed input, no double-used space. Verify same-type lines and multiple source warehouses vs number-of-item-types limit; coordinate strict modern validation with real legacy accepted data. Specify robust migration for Working site, completed orders still carrying outputs without inventing supplies, raw import opening balance and modern projection of unrepresentable payloads.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Admitted execution TransferId with ordinal, retained exact input+result 4096 entries <=1KiB each part, remaining earlier ordinals stale forever under high-water; root accepts schema15/outer3, checked before-effect refusal vs stored admitted rejection. Establish how an exact retry of *creation/admission itself* is recognized across crashes if caller has not yet been given a TransferId; when legitimate repeated blocked work consumes ordinals; persisted capacity/hash checks, session/world identity during timeline rollback and monitor snapshot cost.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Core/registry implementation may be parallel with fixtures/validator/serializers only after exact public/internal data shapes agreed. Recommend useful checkpoints and ownership for S06 main data, S04 ledger/cancel and S16 unsupported legacy state. Normal v13/LAN11 baseline must match; unsafe-fallback exception must be caught before session UI/network effects, preserving live host. Choose measurable memory/latency acceptance.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Watch O(N²) owner+claim search, cross-transaction side effects after allocations fail, receipts shallow copies shared mutable in published snapshots, reparent/merge alias lifetime, callable external mutation through current prototype Inventory/Storage APIs, new IDs exhausted during split/recovery. Inspect resource-harvesting branch and raw1-8 sleep import logic. Legacy loader may accept snapshots with unused/trailing projected route metadata; avoid pathological blanket rejection of genuine saves.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED plus specific contract amendments. 2. Bound request/replay/IDs and failure atomicity at ordinary world hot paths. 3. Identify data-shape necessities for accurate P5 legacy import and modern pollution rejection. 4. Specify earliest branch-safe real end-to-end migration stage. 5. Name concrete validation tests that catch each risk.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse, graph search/trace and coverage for cited root paths, direct missed ranges. Check core/profile/production/identity/construction tests and raw serializer fields; no builds necessary. Existing logs in /tmp/stoneheart-milestones.xprJ2SVp.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No new generic public dependency/remote issue unless actual gap separate from #7/#8 is identified; root handles filings. Stop to report actual contradictions, keep analyzing independent parts. Do not review or edit the code of another upcoming assignment.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete implementation; root accepted pre-admission vs admitted rejection accounting, modern CancelProduction by durable ID, raw13 UnsupportedLegacyState and retained exact 4096 receipts, immutable stacks with a single quantity source, and input-backed capacity claims, subject to technical feasibility.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F8 PREFLIGHT verdict, concise exact corrections, schema and ownership constraints, regression fixtures and performance risks.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Preflight independent renderer frames and deterministic completion replay
|
||||
|
||||
Task ID: M01-F9
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root M01 66af7c5 includes client b7f18c0, current14, S06 atomic pickup. M01-P6 planner inspected current Win32/worker paths. Actual WM_TIMER pumps every 60 ms, scene packets borrow spans and camera-only paint rebuilds flat D3D mesh, while 20 Hz runtime is independent. Replay covers serial/2/6/12 and last berry but lacks proof of opposing real computation completion and semantic divergence diagnostics.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Preflight M01-P6 proposals for S17-W01 and S21-W01 before assigning separate implementation worktrees. Return separate corrections and concrete signoff conditions.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S17 independent presentation with one retained prepared flat mesh and 16ms dirty-only visible UI timer; S21 success observer for real worker callables plus deterministic arbitration/barrier/replay reporting. No M02 voxel geometry, native 60fps claim or GPU/backend replacement.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root app/viewer_win32.cpp, app/d3d_scene_win32.hpp/.cpp, viewer_session, app timer/lifecycle, tests/replay_tests.cpp/executor_tests.cpp/runtime_tests.cpp, engine/include/settlement/core/worker_pool.hpp, engine/src/world.cpp actual stage spans and quota; docs S17/S21/M01, M01-P6 and pinned FuturePool/Testing. Inspect temporary actual client handler smoke.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root assigns separate S17/S21 branches, and S18 owns ongoing title changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S17 verify packet owns world/camera/selection/overlay and prepared GUI inputs, UI-thread resource ownership, post-replacement pairing after pump consumes event, immutable pin across nested UI; D3D reuses existing flat GPU/CPU mesh for camera-only changes, avoid per-timer reallocation/hot spinning, hidden/title/minimized and zero-size restoration. Real actual handler test needs camera and render changes while owner/file blocked, safe destruction; respect existing WARP/offscreen/hardware capabilities and fallback HUD only.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S21 optional after_execute(index) on success after real callable returns, before future satisfaction; return void/value/references/move-only, same-callable exceptions including observer errors, no throwing destructor, no hook when absent. Existing Void #15 registered. Two gates for two known competitors, controlled opposing completions asserted; tests 2/6/12 + capacity1 fallback without deadlock; real generic job contest parallel, berry claim serial with parallel movement separately. Report object/field/owner/request for first divergence using public World and canonical current serializer as authority; gated old world vs queued same-world reload with fresh session and unchanged old snapshots.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S17 rendering work in new branch separate from S18 title/profile; avoid altering normal client command pumps. S21 production edit restricted to optional worker hook and tests/docs, no world mutation/codec changes. Future body15 normalize version selector after integration.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check exception lifetimes, reference dangling/extra move, re-entrance or UI init/failure, force order while caller coordinator blocked, guarantee test oracle actually observes completion, full terminal effects after faults/cancel. Potential thread-lifetime hang on assertion; GPU device generation invalidates cached upload after reset. Check path/store version key for camera-only frames and active overlay state.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. Concrete prescreen decisions, testable postconditions and residual limitations. 3. Meaningful assignment in each isolated subsystem without changing the product contract.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use source read and graph search/trace/coverage plus direct ranges; inspect actual m01-viewer-{build,ctest,ui-smoke}.log and client_handlers_smoke.cpp. No builds.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send prescreen first safe scope early. No apparent missing generic capability needs a duplicate issue; root filed Void/Library #15, immutable publication uses #5. Do not review unseen code or demand native-only validation for feasible Wine work.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap branches and tests; root accepts dirty-only 16ms timer, one retained flat mesh generation, optional success observation and semantic diagnostics subordinate to canonical bytes, subject to technical preflight.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F9 PREFLIGHT stage-specific verdict, corrections, exact test cases/source, bounded risks and practical blockers.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Map the authoritative runtime and dependent system branches
|
||||
|
||||
Task ID: M01-P2
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation at M00 904bdf8, M01-C/T in progress. User extended the goal to the full plan with commits, pushes and separate milestone/system branches. Pin 7b0fea6, Windows GCC16.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Design the next integrated M01 implementation after the deterministic reference. Give concrete separable packages, frozen APIs, branch order and runnable acceptance for S01, S15, S16, S19 and the viewer.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only plan for M01 and prospective compatibility seam for M02. No new product discovery; the approved roadmap controls. Do not replan existing serial/replay task.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect PLAN.md, M01/M02, S01/S15/S16/S19 and S04/S06 contracts, world.hpp/world.cpp/world_save.cpp, app/viewer_win32.cpp, app/lan_session.hpp and _win32.cpp, CMakeLists.txt and current tests incl LAN. Check actual world mutators, UI direct writes, reload/command cache hazard and exposed stores/indices.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Shared checkout; root owns branches/builds. Do not modify files or activate a different project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Indicate exact integration for a single-owner fixed-tick runtime publishing immutable snapshots; atomic candidate load/epoch rejection; versioned, city-scoped idempotent command results/authentication; rules manifest dependency validation/fingerprints; permanent ID and custody path. Preserve old format13/protocol11 with an explicit compatibility boundary for existing programs. Propose deliverable slices which independently add executable tested features.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Name specific NEW types and responsibilities separate from observed ones. Explain host identity, dedup key, conflicts with stale packets, pending versus committed epoch, queue bounds and failed save/load. Suggest a no-duplicate-serialization path, CPU cost/50ms budget and API for existing viewer reads.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Researcher separately investigates Void/primitives. Root authorizes scope, owns CMake integration, cross-system compatibility and push. One branch per milestone or system package fits the added user direction. New worktrees may be used for independent systems.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Call out deadlocks, stale load/worker results, snapshot lifetime, partially applied ticks, time spent in rendering, current hardcoded two slots and generator/script state. Keep more ambitious M09 features on M09.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source-grounded M01 package graph and first precise interfaces usable for concurrent implementation. 2. Boundaries for each acceptance criterion including existing gameplay/legacy callers. 3. Concrete, short next package to dispatch plus integration strategy.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git status --short --branch, git diff 904bdf8 --stat; rg -n 'WM_TIMER|world->step|world->apply_command|read_save|write_save|lan.poll' app engine; use scoped graph with coverage/direct checks for cited source. Existing integrated check is CMake + CTest Windows on Wine. No remote writes.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first independent work packages early when ready. Stop if evidence requires a product decision; keep useful read-only work going. Do not spawn.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User explicitly requested the full plan, local commits, remote pushes and occasional status. This assignment is planning only.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P2 READY/PARTIAL, package DAG, file boundaries and frozen API, behavior/risk/test matrix, what can ship first and which assumptions need owner confirmation.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Map durable item custody and stable entity references into the running game
|
||||
|
||||
Task ID: M01-P3
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
The integrated M01 branch /home/faumaray/Projects/stoneheart_at_home is at cf0cc2f. S01-03 groups logical state in a private WorldState in s01 worktree. S15-02 introduces a versioned modern checkpoint around validated legacy body and exact rules. S16-01 scopes command receipts to session. User's next gameplay requirement in M01.2 is stable IDs and conservation.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Specify an executable incremental implementation plan for M01 stable IDs/ownership through actual current game actions (production, resource haul, construction, inventory, demolish). Identify the first narrow end-to-end migration that can be dispatched immediately.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only S04/S06 and checkpoint/world integration architecture; distinguish current IDs from index-based fields and later M03 capabilities. No redesign of the whole roadmap, mod SDK, region/world geometry or unrequested product choices.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp, world_save.cpp, first_colony.cpp, viewer_win32.cpp, app/d3d_scene_win32.cpp/tests, plan S04/S06, M01 and M03. Inspect s01 capture worktree actual logical representation and detached checkpoint checkout. In pinned Void inspect public IDs/typed handles/registry if relevant and cross-check already documented matrix.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations, branches, external requests or children. Parent owns root task notes and Git. Do not change shared Serena project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Map introduction, assignment, transport, consumption, split/merge, cancel/delete, HUD, serialization and load validation by actual symbols. Plan monotonic counters never reused, ownership and transitions, stable typed references with bounded lookup and ordered arbitration. If legacy format13 must keep indices on the wire, convert at codec compatibility boundary, ensuring legacy snapshots can import deterministic IDs; modern checkpoints must encode actual counters and identities so rollback/mutations never reassign values. Identify exact compatibility mode for changing demolish behavior, preserve existing tests where game design allows. Avoid double representations that can silently diverge/lose inventories.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Specify NEW API and fields only after source check. Cover existing WorkJob.id, Agent.id, ResourceNode.id, Storage.id, ProductionOrder, MaterialReservation, ConstructionStop, ItemStack and private AgentInventory. Give ownership and migration sequencing for WorldState, routes, input/output codec, renderer, tests, and branches S04 vs S06. Recommend whether durable ID fields are domain-local or reusable generic Void capability needing issue; no remote writes.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Dependencies S01 snapshot/dispatcher/S15 versioned checkpoint. Root owns integration order. Send first safe independent task early with exact symbols, lossless old-wire export boundary and hard tests before broad changes. Multi-branch CMake/World ownership must be serialised.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check nonempty demolished storage (currently erases stored items), active reservations/held goods, room/floor target, duplicate/dangling IDs, counterfeit aggregate counters, overflow and million-record malicious saves. No behavior changes to LAN11 or wrong acceptance claims. Keep authoritative reconciliation deterministic for serial/parallel.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source-grounded table of stable vs positional identifiers and mutation sites. 2. First executable slice with narrowly owned files and disambiguated compatibility. 3. Subsequent DAG solves M01 reference/custody exit, tests after mid-carry load/cancel and ledger conservation. 4. Name any actual product decision needed, or bounded technical recommendation.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git status --short --branch, git show -s --format=%H, rg -n 'shift_index|reserved_slots|construction_delivery|MaterialReservation|production_index|stock_storage|finish_production' engine app tests; inspect actual pinned headers, current serializer/acceptance fixtures and exact removal semantics. No build needed for read-only planner.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No source/code modifications, deployment or tool state changes. Stop if pinned source unavailable or a consequential design decision is truly user-owned. Return useful independent conclusions immediately.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved entire plan and requested subagents. Root assigns this dependent architecture work within M01. F3 authority and failure decisions remain in force. Does not authorize a new public protocol/dependency or branch push by agent.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P3 READY/PARTIAL, concise path/behavior, implementation contracts, ordering, tests, upstream fit, unresolved facts. No children.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Map the first selectable rules to existing game behavior
|
||||
|
||||
Task ID: M01-P4
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Main 4ba64f7 has frozen rules manifests, checkpoint v1, Window-independent runtime. S18 initial UI preflight correctly permits only actually supported profiles. Present World::start_scenario hardcodes staged_beds_=true, while saved legacy worlds and recipes/game commands contain both staged and simple/plank bed behavior. Builtin colony manifest has a board work_ticks field (8) different from compiled SawPlank (12), so treating that as activated configuration would change prototype behavior.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Produce a narrow verified implementation proposal for M01 real module selection/new game/load, with an actual deterministic gameplay difference and unchanged default trajectory. Assess existing simple vs staged bed paths as the first selectable feature.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only S19 technical/product-fit plan for first actual setting, default compatibility and existing explicit script-state contract for M01. Keep new Lua runtime, complete mods SDK and public cooperations in planned later scopes.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect rules_manifest.{hpp,cpp}, world.{hpp,cpp}, world_save.cpp, first_colony.cpp, checkpoint.hpp/.cpp, checkpoint_files.cpp, simulation_runtime.cpp, actual title_screen_win32.hpp and viewer handlers, S19 W01–W03, master/parity/prototype fixture. Review test constructions of old v1/v2/current bed states, frozen digest fixture and handoff from S18.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote access or child agents. Parent owns root decisions and eventual branch contracts; keep shared Serena activation fixed.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Trace actual recipe/placement/material/progress behaviors under World::staged_beds() false/true, inputs/stock and ability to complete both. Propose a valid optional built-in rule package with explicit behavior and data (for example opt-in classic recipe always uses simple plank). Keep frozen default 2-package digest, current normal make_first_colony behavior and v1–13 imports. Give validation path from chosen catalog → Resolved actual game options → world initialization and saved rules → preinstall compatibility. Avoid merely switching labels/fingerprints without changing executed mechanics. Do not equate any early option with complete ACE parity.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Propose frozen NEW C++ APIs and file/branch ownership. Handle old scenario saves with staged_beds=false and legacy imported default manifest, custom unsupported manifests in generic readers vs retained exact viewer profile gate, default-only LAN11, authoritative rules invariant on loads, real user setting at new colony in existing Windows title flow. Identify any compatibility ambiguity requiring product decision. S04 changes raw body/current checkpoint in parallel; coordinate ownership and versioned format boundaries.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Dependencies S19 owns package/factory behavior; S18 UI can wire selector when accessor/factory verified; S15 owns generic file prepare, S01/S16 already identity/legacy gates. Keep selectable integer state/atomic script results on M01 contract only unless actual milestone requires executing Lua now. Use existing Void facilities, flag genuinely missing upstream primitive without externally filing.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Risks default digest change, explicit legacy import with previously valid raw data, failing to reflect actual selected mechanics after reload, stale display code assuming staged beds, repeated loading/selection under same world seed. Need exact tests for active-world refusal on incompatible compiled profile, variant supply/bed completion, replay and v1/cross-binary.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source-grounded selected pair or better alternative with clear real effects, no cosmetic difference. 2. First implementable core task and limited follow-up UI integration. 3. Testable legacy/frozen/unchecked-catalog/canonical behavior and precise pending script contract. 4. Name any real product decisions.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git rev-parse HEAD; rg -n 'staged_beds_|start_scenario|make_first_colony|BedStage|default_rules_manifest|builtin_rule_packages' engine app tests; inspect actual pinned API when relied on. No build needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first viable technical criteria early. No refactoring, remote writes, branch changes or children. If simple-bed feature is invalid by plan/source, identify a valid alternative with direct evidence instead of forcing it.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap and rules selection is explicit M01 deliverable; this design reuses existing gameplay/boundaries. Root retains scope and integration choices.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P4 READY/PARTIAL, actual source references, bounded interface/ownership design, exact verification targets, integration risks/native gaps.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Specify the first authoritative inventory and transfer operations
|
||||
|
||||
Task ID: M01-P5
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root M01 2a5df1a. S06 IDs 8260e09 are integrated. The developing S04-01 converts production orders/agent links to ProductionId, current save body14/outer2 and typed legacy import. Previous M01-P3 mapped object domains, but actual quantities still live in storage/resident representations and construction drops cargo on arrival. This is the detailed technical handoff for M01.2.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Freeze a small end-to-end migration for S06-02 and S04-02 with exact authoritative ownership, identity allocation, operations and backward projection. Suggest genuinely independent implementation segments that can be dispatched before large World edits.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Focus on objects/recipes already present, order-reservations/haul/consumption/cancel/demolition, no new gameplay, extra protocols, catalog or general database. Domain-level transfer retry/retention must have explicit bounds.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root docs/plan/systems/{S04,S06}.md, M01, M01-P3, engine/include/settlement/core/world.hpp and actual Inventory/Storage definitions, engine/src/world{,_save}.cpp plus tests for logistics/production/replay and resource/food handling. Inspect s04 worktree public diff for actual ProductionId and NEW current14 schema; never modify it. Review pinned Void Numeric, upstream #7/#8 linked in docs/plan/void-library.md.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posting, shared project switches or children. Parent owns root/remote and serializes World/codec ownership. Work from actual source and verified graph coverage.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Trace every quantity introduction, split/move, take_reserved_material, pickup, in-transit cancellation, construction worksite arrival/delivery, consumption, eating, storage demolition and factory stock. Identify minimum source of truth. Design checked before-effect atomic operations, stable nonzero StackId by world, one current owner per stack, explicit material balance opening/sink, exact held amounts, and reliable projection to old fields. Avoid persisting parallel quantity ledgers without enforced consistency. Characterize active/inactive imported orders to preserve v1–14 continuation, including mid-site delivery. Product keeps pre-existing demolition's removal of stock and records its amount/reason.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Give exact proposed NEW operation types, identities/high-water constraints, on-disk version steps, and API surfaces for S04 claims vs S06 actual stock. Pin behavior on outcomes AlreadyApplied/Duplicate/Conflict/Busy and stale retries even after bounded receipt retention and save/load, deterministic order vs multi-actor concurrency. Name genuine policy questions; choose bounded defaults for reversible design.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
An independently testable ledger module before World integration may be parallel if it has a real consuming path and fixed grounded seam. S04-01 must integrate first for worksite references, and S19 touches only scenario setup. Summarize actual changes needed in UI for preserving displayed amounts.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound memory by current existing file/collection capacities, handle zero and uint64/int quantity overflow, reserve IDs without partial mutation including splits/exhaustion, owner removal after pickup, no-free-space redirects, capacity races, negative/cross-owner dangling state, and loaded modern wrong digest. Avoid quadratic hot paths; identify realistic measurement checks.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source-grounded transition and migration tables; 2. First independently deliverable task with exact scope and tests that leads to real stock; 3. Subsequent isolated work packages with complete modern migration path; 4. Leverage correct Void utilities and #7/#8 where adequate; 5. Declare present limits in legacy raw13/network11 projection.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git rev-parse HEAD, actual scoped rg -n on add_item, take_reserved_material, advance_construction_delivery, finish_production, reserved_slots, item inventory and stock, scoped current/load/save comparisons, local Void pin as needed. Check graph identity/coverage for relied-on root code; isolated s04 working diff uses direct reads. No compilation required.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first technical seam early, then full report. Do not assign new IDs by vector position, silently destroy cargo on cancel, break legacy binary projections or start new worktrees/remote Git. If uncertainty materially changes the product scope, identify the specific branch and continue other evidence.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Approved M01 hard requirements and earlier planner M01-P3 permit this focused design of actual custody. Root decides integration order and product-preserving defaults. No release or merge to main.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P5 READY/PARTIAL, exact grounded operations and claimed invariants, owners/paths, test and version matrix, bounded retention/performance policy plus actionable blockers only.
|
||||
|
||||
The accepted decisions and historical format boundaries are recorded in [the custody contract](../../plan/custody.md). Source-backed corrections from preflight address creation retries, retained site stages, pending completion and representability on LAN 11.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Define the remaining client frame and replay acceptance work
|
||||
|
||||
Task ID: M01-P6
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root db0a872 merges S18 b7f18c0, S19 selectable rules, S04 Current14, S01 owner and legacy LAN. Actual client WM_TIMER pumps every 60 ms while camera input can invalidate on demand and scene Present uses 0. Existing replay on serial and 2/6/12, last meal, synchronous structural barriers and faulted owner recovery pass. M01 needs independent client frames and an evidenced worker completion-order adversary/first divergent IDs.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Prepare two independent real work packages for S17-W01 render frame delivery and S21-W01 deterministic replay diagnostics. Identify acceptance already satisfied vs missing. Recommend minimal source-grounded additions that can proceed alongside full S06/S04 custody.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
No implementation, new M02 terrain, mesh engine overhaul, native performance claims, general benchmark infrastructure or speculative production hooks. Preserve S18 title/rules changes and S06 current schema.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M01.md, systems/S01,S17,S21; app/viewer_win32.cpp pump_session/scene/view/HUD/camera/modal/WM_PAINT/WM_TIMER, app/d3d_scene_win32.* and public draw interface, existing client_* smoke and tests; engine worker_pool/world scheduling/hooks, runtime/dispatcher, tests/replay_tests.cpp/executor_tests.cpp/runtime_tests.cpp, benchmarks as pertinent.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote/children or Serena switch. Root plans separate branches, S18 owns title and profile logic, S06/S04 own inventory world paths. Use current root graph only after coverage check and read missed lines.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S17 identify how to prepare/pin immutable frame data once, main+child/software/D3D and nested UI callbacks, decouple scene refresh from event/network pump and authoritative 50 ms tick, avoid busy loop/rebuilding expensive static geometry solely for unchanged state, camera movement during gated world and file work. Match existing Win32 design and keep title/minimize/pause behavior; future D3D chunk cache is M02. State how real harness could assert camera changed and original tick stayed fixed without treating Wine fps as native.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S21 locate how last-item/resource arbitration relates to actual parallel batches and stable tie order. Design test/harness that PROVES opposing order of completed tasks (not just ordering hook starts/sleeps) for an actual contested outcome and canonical state. If after callback needed, preserve WorkerPool completion/exception/move-only behavior and use least invasive grounded seam. Check stale results after load owner barrier, real two client idempotent and save+camera. Recommend first-divergent tick/ID (inventory/actor/job/command) reporting and repeatable command entry/tag. Avoid duplicated serializers that drift; existing current14 soon current15. Derive calls/files from source.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Align S17 renderer-owned files vs S18 title/client profiles and CMake/worker code ownership. S21 can adapt test golden canonical encoding immediately independent of future custody, document which invariants extend after body15. Flag any truly missing generic primitive and check pinned Void facilities before suggesting upstream issue.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check UI timers/window events after destroyed, minimized/hidden, modal subloops and GPU resource lifecycle/race. Race tests deterministic using bounded waits and release cleanup even on assertion. Never rely on exact Wine wall scheduling or declare physical 60fps. Prevent deadlocks at 2 workers or queue capacity 1.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate executable contracts with exact paths and acceptance. 2. Clear proof of forced completion and stale fencing/diagnostic usefulness. 3. Real GUI cadence event and pinning acceptance with labels and stable source ownership. 4. Mark which existing evidence suffices. 5. No broad refactors outside M01.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git rev-parse HEAD; scoped graph search/trace and snippets plus coverage ranges. Read actual integrated CTest/GUI logs m01-viewer-{build,ctest,ui-smoke}.log and /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. No builds needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first independent S17/S21 seam early. Avoid new protocol/settings, general policy changes or altering product contracts in design. No remote actions/children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap and per-system development branches. Root owns product/integration/publication. Preliminary design may proceed while S18 title and S06 custody progress.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P6 READY/PARTIAL per system, current verified behavior, scope/paths, exact measurable tests, remaining gaps/dependencies and likely performance implications.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Verify Void contracts for runtime, persistence and modules
|
||||
|
||||
Task ID: M01-R2
|
||||
Role: astra_researcher
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Game root /home/faumaray/Projects/stoneheart_at_home at M00 904bdf8 on milestone/m01-authoritative-simulation; initial serial/replay tranche in flight. Public Void HEAD matched CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. User wants later systems implemented as well.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Find exact reusable Void APIs for M01 rules module/manifest dependencies and hashing, transactional saves/Windows atomic replacement, immutable snapshots/fixed clocks and idempotent command dispatch. Produce per-contract decisions so authors can begin without duplicating library code.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only evidence focused on S19/S15/S01/S16. Start by returning results for rules/manifest and atomic writes. M01-R already covered executors/replay.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect CMakeLists.txt, docs/plan/void-library.md, docs/plan/systems/{S01,S15,S16,S19}.md, current save codec, viewer save entry points, exact public Void pin, test and backend files and current upstream tracker. Verify source branches against pin, not co-located names.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Root owns all network writes. Other agents own game/test files. Do not change branches or active graph.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Check public API, real behavior, Windows flags and tests at pin e.g. Binary, Crypto SHA256, IO atomic replace, version/dependency graph/manifest. For each required generic gap give existing matching issue or minimal issue content, expected replacement check, local game path candidate. Distinguish domain ownership. Independently validate whether Windows build/link of candidates is feasible, no application writes.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Return precise API/units, guarantees and missing pieces (including byte/string handling, version compatibility and corruption behavior). Prefer supported existing routines over new custom equivalents.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
M01-P2 handles game integration. Root decides package ownership, upstream issues and commit/push. Authenticated tool available only if needed; use read-only upstream operations.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Do not leak private code, real data or credentials in external queries. Treat native Windows vs cross-test explicitly. Network, sandbox and subprocess errors must be reported accurately.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Runnable library reuse plan for each next M01 system. 2. Direct URLs/test paths and Windows constraints. 3. Actual tracked gaps or precise issue drafts with acceptance and migration test.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
From game root git show HEAD:CMakeLists.txt and from confirmed pinned checkout git show 7b0fea6095f603f9e1904f66dfdc7752f4be4792:<path>. Check live git ls-remote and read-only public issues. Reference existing cross env and use source fixtures as appropriate without changing project.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not create issues, fetch private data into public tools, or ship dependency changes. Return findings by priority, including partial early results. No children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User's plan requires library-first analysis, and separately authorizes authorized repository changes and branches. This task grants read-only investigation.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-R2 status, decision/evidence per feature, real gaps/practical issues and replacement criteria, current Windows evidence and unresolved questions.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Replay actual colony commands and compare every tick
|
||||
|
||||
Task ID: M01-T
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation based on M00 checkpoint 904bdf8. The baseline has 28 core and 4 LAN cases, reflection suites from pinned Void. Legacy task notes/.serena are untracked.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Build an executable M01 replay regression in the normal settlement_core_tests target, exercising the explicit serial reference and normal modes on the same saved starting state.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Own the test fixture, useful game scenarios, mode/legacy boundary assertions and minimal source registration. Keep every existing core and LAN case. No new runner or game production logic.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect tests/core_tests.cpp (save_contents and test_two_players_share_the_first_colony, resource/hauling and parallel job tests), tests/test_main.cpp, CMakeLists.txt, world.hpp, docs/plan/milestones/M01.md, docs/plan/void-library.md and actual game behavior.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: tests/replay_tests.cpp; CMakeLists.txt
|
||||
You are not alone. Core owner writes only world.hpp/world.cpp/world_save.cpp. Root owns docs and Git. Do not revert their changes; serialize your new file registration in CMake yourself.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Add a reflected Void Suite in NEW tests/replay_tests.cpp, register this file on existing settlement_core_tests. Mark new cases with tag replay. Use the actual write_save binary bytes as prototype oracle (no hashes or shadow codec). Record a fixed test-local set of PlayerCommand values including explicit player sequences and scheduled step attempt ordinals. Check expected receipts/rejections, tick/revision and pause/resume, then compare state bytes every attempt through meaningful colony output. See preflight requirements below.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW frozen API settlement::ExecutionMode::{Parallel, SerialReference}; World(seed,w,h, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel); World::read_save(stream, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel). Serial requires logical count 1 and reports worker_count()==1. Parallel 2..64 and ordinary one-worker rejection remain. Invalid combinations/unknown enum throw invalid_argument. Existing PlayerCommand, CommandReceipt, make_first_colony, resource/job APIs apply.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Core author implements the frozen API concurrently. Use an uninterrupted serial reference versus 2/6/12 from the same initial bytes. At a proven material-in-hand checkpoint resume another world per mode from bytes, keep uninterrupted reference alive and compare every subsequent tick. Use warmed path cache in the live history; report path counters and first differing tick/mode/object or byte offset if a comparison fails. Coordinate builds after both sides compile.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Cover empty, paused, one resident/fewer residents than workers. Include multiple competing generic jobs and an unreachable route forcing a retry to another job (all three dispatch points), and two eligible residents contending for the last item, with a specific winner and conservation after delivery/consumption. Choose meaningful positive outcomes to rule out all modes equally doing nothing. Compare bounded scenarios and avoid OS timing assertions.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Reproducible command schedule advances a real colony and checks accepted and rejected commands. 2. Exact byte equality every tick for serial/2/6/12 including reload vs uninterrupted; prove in-hand stop and useful work. 3. Contention winner and unit accounting, job selection/retry, and valid/invalid configs are checked. 4. Existing tag/CTest entry points still work.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
From game root source /tmp/stoneheart-verify.KoZwE4o8/env.sh; cmake --build /tmp/stoneheart-milestones.xprJ2SVp/windows --parallel 8 --target settlement_core_tests; wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag replay. Root built this directory from the exact clean Void pin. Report counts and time. Work with core owner if build awaits API.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not weaken old tests, compare only hashes/final counts, edit game files, change branches, stage/commit or spawn. Investigate actual source when a fixture fails; distinguish bad setup from real divergence and inform root.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested milestone implementation with subagents. This scoped M01 tranche establishes replay evidence before replacing the executor or changing the authoritative command format.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-T status, changes, fixture/expected state, counts and commands, any coverage you could not verify and integration notes. Send early if there is a real disagreement across modes.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Review the serial reference and replay checkpoint
|
||||
|
||||
Task ID: M01-V1
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Game root /home/faumaray/Projects/stoneheart_at_home on milestone/m01-authoritative-simulation, parent 904bdf8. User asks that reviewed milestone/system work be committed and pushed. Initial M01 tranche only. Pre-existing untracked .serena and older task files are outside the diff.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Review the actual integrated M01-C/T source and tests; give an independent defect-oriented verdict on this checkpoint before push.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Audit constructor/load mode, all worker dispatch paths, exact-state comparison, normal suite/CLI callers and documentation plus boundary to future work. Work on later M01 packages is planned separately.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read git diff 904bdf8 and NEW tests/replay_tests.cpp, docs/agent-workflow/tasks/M01-{C,T}.md, README and M01 plan. Check world.hpp/world.cpp/world_save.cpp, CMakeLists.txt, test_main.cpp, existing core and LAN suites against the frozen contract.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Do not change any shared checkout files or branches. No children, push or external writes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Inspect actual worker lifetime, order, exception handling changes since baseline, empty/paused/one-resident cases, mode validation and save ingress. Review each new case for effective contention, warmed-cache checkpoint and positive useful progress. Check mode-specific reporting, new API compatibility and CMake discovery.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Parallel rejects 0,1,65+ and serial admits only 1 logical lane, with zero pool threads. Preserve save13/LAN11, existing commands and parallel results. Full M01 authority/async saves belong to later packages.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
M01-C/T complete. Root observed an independent original-ABI Windows probe vs candidate serial/2/6/12, 365 attempts (361 ticks, 5 meals), 738386 bytes of saves and receipts identical bytewise. Five replay tests pass under Wine. Full CTest and build on integrated state in /tmp/stoneheart-milestones.xprJ2SVp/windows; logs m01-first-build.log and m01-first-ctest.log.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check directional reference equivalence when candidates all target same work and routes retry, stable movement/jobs state and flag any newly widened lifetime risk. Native Windows/GPU remains outstanding. Do not waive failed assertions.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Return verdict on first M01 execution tranche. 2. Concrete severity, affected callers, reproduction for bugs and proposed fix. 3. Report untested risks and distinguish them from observed regressions.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
From game root git diff 904bdf8 --stat; git diff --cached --check; source /tmp/stoneheart-verify.KoZwE4o8/env.sh for any targeted read-only testing. Review /tmp/stoneheart-milestones.xprJ2SVp/{replay-tests,m01-first-ctest}.log and actual new file. Do not start a competing build.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read-only. No docs or fixes, no commit/push. Return bounded findings promptly so root can integrate and continue the active goal.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes implementing, committing and pushing each milestone/system. This review covers the first M01 tranche and does not declare the milestone complete.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V1 READY/CHANGES_REQUIRED/INSUFFICIENT_EVIDENCE, findings by severity/location, observed checks, unrun checks and remaining milestones.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Audit the live LAN owner bridge and interactive session integration
|
||||
|
||||
Task ID: M01-V10
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S16-02 in isolated /home/faumaray/Projects/stoneheart_at_home-worktrees/s16 based 8c4c1fe. Contracts S16-02 and M01-F5 closed peer+epoch issues. S18-01 in sibling s18 has reviewed S15 a063894 merged, viewer in progress; LAN candidate will enter its checkout after review. One independent review per product path.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Review actual S16 adapter now for branch integration. Later when root supplies final S18 commit/diff and evidence review normal Win32 entry for events, snapshots, async files and lifecycle, with separate verdicts.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S16 compatibility host/guest integration and S18 normal client wiring. Legacy protocol remains 11. No public additional transport or deployment.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect s16 tracked diffs app/lan_session.hpp/.cpp, tests/lan_tests.cpp, docs S16, frozen runtime header and actual command/snapshot logic. S18 later inspect actual all new viewer_session code/tests and viewer_win32.cpp, CMake, S15 CheckpointFiles and normal entry + smoke. Read M01-F4/F5 and the assignments.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children/project switches. Other workers own code. Use direct source for isolated worktrees. Ignore their summaries until checked.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S16 validate default-only authenticated legacy slot, session replacement, coalesced/wrong/rejected old sequence vs modern next_requests, pending future capacity/incarnation/peer tags, reconnect with in-flight owner mutation, truthful Wire11 receipt and first snapshots, consumer of take_result accept/reject vs prior take_rejection, correct future lifetime and no blocking poll on game work. Cross-verify old/no default rules or disconnect and correct generation in actual state transitions.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S18 later validate consistent immutable world on paint/menu including nested window callbacks, pumped title/modal completions, no per-reset UI join, one file service check latest ticket + dimensions/supported rules, healthy save capture max, correct current epoch after commands, reject and retain draft, receipt routing and bounded local IDs, short locks and cleanup, actual normal new/continue/title load and LAN. No live mutable world assignment through UI.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root merges S16 into S18 to actually build/test full client after S16 review. S18 source is incomplete initially; do not approve unseen future work. Public test port uses loopback only. Native acceptance separate.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check state across TCP rebind and network packets/receipts allowed on aborted session. Saturation/old guest fixed sequence, authoritative exceptions. UI must handle busy/faulted futures, avoid stale changes after failed newer load, process-level save ordering and bounded memory. Compare baseline behavior only within approved compatibility.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per phase with concrete sources and triggers. 2. First confirm real 5/5 lan-owner, 92/92 core, 9/9 LAN and original/new binary interop in both directions. 3. S18 after actual signoff + build/smoke logs; name any missing evidence for end-to-end status.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git -C s16 diff --check; inspect /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-final-{build,ctest,tag}.log and lan-owner-interop.{cpp,py,log}. For S18 compare named parents once available and logs client-* in shared temp dir. Read-only inspection only.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Return S16 review early. If blocked by outstanding S18 dependency, confirm stage A and await final evidence without premature approval. Inform root immediately of a verified actionable defect.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete plan and system/milestone commits/MRs accumulating on roadmap. Root owns external actions/normal integration.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V10 separate S16/S18 findings with actual tests, changed paths and limitations. No children.
|
||||
|
||||
The S16 adapter has been integrated at `aa4e271` (parents `60154bd` and `09545bf`). Recheck the transport, legacy codec and test blobs against the reviewed branch, confirm the absence of merge edits to the owner or file adapter, and inspect `m01-lan-{build,ctest}.log` before publication. This additional check is read-only. The combined suite passed 106 core and 9 LAN tests.
|
||||
|
||||
Stage A passed the integrated review at `aa4e271`. For stage B inspect the actual tracked and new S18 files in the `s18` worktree based at `eef69ca`, including `viewer_session`, the Win32 entry point, CMake and the viewer suite. Inspect `client-{build,ctest,ui-smoke}.log` and `client_ui_smoke.cpp` under the temporary evidence directory above. The smoke used three real viewer processes with isolated save data. Check title, modal navigation, successful and failed load, guest transitions and truthful pending-blueprint outcomes. The contract still distinguishes the initial compiled default profile from the separately scheduled S19 selection. Return a defect report or READY for S18 without changes to the checkout.
|
||||
|
||||
Stage B initially required three corrections. Recheck the finished fixes for identity after modal demolition, rejected guest rejoin preserving the retained replica, and ticking acknowledgements across fault recovery. Inspect the updated committed-quantity and request-path checks in `client_{handlers,regression}_smoke.cpp`, the corresponding `client-{handlers,regression}-smoke.log`, the final viewer build, the three-process smoke and `client-ctest.log` (99 core, 9 LAN, 10 viewer). Separate integrated audit follows when root supplies the merged ref.
|
||||
|
||||
Stage B fixes passed review and were committed as `b7f18c0`. Integrated commit `db0a872` has parents `5354241` and `b7f18c0`. Confirm that the resident panel uses approved resource/storage/production IDs while the view remains pinned, both UI and core suites register, and the merged application’s three-process smoke passed. Check `m01-viewer-{build,ctest,ui-smoke}.log` under the temporary evidence directory.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Review durable order identity and compiled colony profiles
|
||||
|
||||
Task ID: M01-V11
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Independent review in two phases. S04-01 isolated worktree s04 based 4ba64f7 with production order IDs, body14 and outer checkpoint2, existing schema1 real fixture. S19-02 isolated s19 based 60154bd with first optional package/profile, old default retained. S19 and S04 are expected to touch adjacent World declarations/CMake; root will supply combined refs for final checks. Baseline S16/S06/S15 already published.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide separate disposition for actual S19-02 and S04-01, then for a root-supplied integrated result if requested. Alert root quickly on reproducible failure before workers retire.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S19 backend, old/new data and S04 current changes including codec, command handling, real placement/reservations and lifecycle. S18 screen/selector verification belongs to a separate client review. This review covers the public core seams that later UI calls.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual tracked/untracked files in sibling worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s19,s04}, including all new headers/sources/tests, full surrounding world, checkpoint/readers, rules_manifest, first_colony, command_dispatcher, changed CMake and docs; baseline legacy tests + new fixtures actual consumed bytes. Read contracts S04-01/S19-02 there and root M01-F6.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote postings or children. Parent owns commits/resolution. Use direct scoped reads for separate worktrees, shared root graph with coverage/direct missed lines if used. Do not change project activation.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S19 audit exact old default manifest/hash, optional package deterministic compile of real recipes vs forged/missing/additions and unsupported profiles, factory UUID/canonical rules, no mutable after-start rule switching. Check active staged optional refusal, default raw/simple/inactive/saved historical compatibility, actual input requirements/duration simple vs staged, finished beds and room. S04 review full ID allocation, batch production scheduling incl replenishment simulated post-demolition, before/after failures transactional, exact Busy narrow no domain next seq mutation; new ID in all actor references, cancellation, finishing order and find; explicit codec boundaries, bounds/duplicates/noncanonical/high-water/dangling, v1 authentic + modern pair and replay.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Public profile functions colony_rules/compile_colony_rules/make_colony_checkpoint/validate_colony_checkpoint and staged/default initializers preserve calling contracts; strict profile policy only at game/client gate, generic codecs/runtime remain reusable. ProductionId 0 absent, MAX exhausted with last valid MAX-1. Compare both double dispatch (legacy/direct/modern) where relevant to tests.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Order of branch signoff independent. On integrated stage confirm the raw/outer and profile gates and all added tests coexist under root CMake/World changes. Native hardware/real LAN separate. Root will send ready marker and evidence directory for each phase; do not approve unseen results.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Watch O(N²) references in hot/hostile save path, exhaustion partial mutations after storage erasure/cabin terrain / counters/room placements, v13 and LAN11 byte drift, accidental implicit fallback on unauthenticated or modified data, restoring historical default simple and optional staged mismatch. Confirm authentic fixtures frozen using prechange binary; never log private data.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component with concrete reproduction and severity. 2. Compare targeted/final logs and actual old corpus bytes, not just worker report. 3. Root integration evidence after selected branches merged must identify any new cross-contract issue. 4. Document unverified native/product gaps.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git -C <wt> rev-parse HEAD; git -C <wt> diff --check and --stat; read status/new paths and inspect source directly. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{baseline,tag,ctest,compatibility}.log and production-id-{final-tag,ctest}.log plus archived production replay/corpus logs as provided. For merge phase compare relevant actual branch/HEAD blobs and final CTest logs.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Give findings as soon as evidence warrants; no remote or code writes, no plan beyond requested changes. Hold component approval if final tests not yet recorded or actual source still changing. Two failed same-cause fixes escalate via root.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes roadmap/push/MRs/upstream issues; root alone owns those actions. Preflight M01-F6 explicitly passed under default simple/inactive compatibility policy and scoped capacity exception contract.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V11 S19/S04 separate verdict, file/line, trigger, actual tests/artifacts and remaining gaps. Later verify corrected diff or integrated refs when supplied.
|
||||
|
||||
Both component reviews returned READY. Audit integration commit `a8cd7bb`, parents `9a248c3` (which includes S19 `2759563`) and S04 `2a3ec92`. CMake kept both new test sources during conflict resolution. Check the merged World initialization and stable production fields, old/new checkpoint and profile behavior, selection tests using the real current encoder, and the unchanged legacy host gate. Windows x64 logs `m01-orders-profiles-{build,ctest}.log` cover 122 core and 9 LAN cases. S18 initial viewer and follow-up title selection have separate reviews. Scope here is the integrated core and runtime LAN behavior.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Review atomic pickup and the title profile selection
|
||||
|
||||
Task ID: M01-V12
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S06-02 at sibling s06 a8cd7bb plus implemented checkout. Targeted quantity tag 14, whole 136 core+9 LAN at isolated branch and two prior corpora. S18-02 at sibling s18 e6a01be in progress. Each had explicit M01-F7 preflight corrections. Root will signal when to inspect S18 implementation and integrated refs.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently review actual atomic pickup now, title/profile integration when ready, then combined branch evidence before remote publication.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S06 subset meal/construction stop only and preserved direct recipe processing; S18 visible title selection, exact compiled acceptance/host gates, old profile compatibility. Durable custody in design F8 is separate.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root M01-F7, sibling s06 S06-02, its new inventory_transaction.hpp/.cpp, narrow World integration, actual new quantity_transaction_tests.cpp/CMake/docs, contextual World/WorldSave/Immutable runtime. For later S18-02: actual title_screen_win32/viewer_win32/viewer_session/tests, S19 factory/validator, LAN and GUI/handler smokes.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root publishes and owns merges. Direct scoped worktree source incl untracked files mandatory; shared root graph with range checks only when relevant.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Pickup verify one storage at the current stop, multiple and nonadjacent duplicate line aggregation, no underflow/overflow or invalid type indexing, exact target count, checked final storage capacity including one first-ingredient output reservation at the correct stop. Late rejection leaves original count/slot inventory, routes/cursor/state from pickup entry. Ensure commit has no allocation/throw, erases correctly and preserves stack order, body14/raw13/LAN11 outputs unchanged. Ensure tests enter real meal/multistop/carpentry and runtime fault behavior and direct finish_production is preserved.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S18 later validate title-only New choice, accurate simple Miner description/controls, both initial and latest async candidates use accepted compiled profile & 32×32, historical default simple/staged/inactive, malformed latest after superseded prepared candidate, exact-default legacy host both immediate/deferred/after modal and explicit pending-load refusal before listener effects; S18-01 guest rollback/modal epoch and ticking fixes remain.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Send independent verdicts as available. Root may request follow-up integrated comparisons via updated refs/log paths. Wait for actual S18 ready marker; no future-code signoff.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check arithmetic touched only accepted input, multiple erased stack lifetime, max 11 types vs unbounded input lines, true atomic output-slot commit, current state unchanged after failures, actual compiled probes and real Win32 entry. Test data mutations must remain scoped to fixtures. Do not equate Wine with native Windows.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. Source-grounded findings with concrete triggers/severity. 3. Confirm actual logs and golden files/GUI smoke. 4. Integrated review only when refs supplied.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git -C <wt> status/rev-parse/diff --check; read new source and relevant tracked full contexts, /tmp/stoneheart-milestones.xprJ2SVp/quantity-{config,build,rebuild,tag-final,ctest,probe-build,golden}.log and actual checksums. S18 final logs will use client-profile-* in same temp directory.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No code/Git/remote changes; if a blocking defect appears report promptly, then re-review actual corrected source on request. Do not assume dry approval of new receipt registry or future schema15.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes roadmap/push/MRs/upstream issues; root owns all external actions. Prescreen fixes incorporated before implementation.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V12 separate S06/S18 verdicts, real files/paths/tests, exact remains and native caveats, later integrated check as assigned.
|
||||
|
||||
The S06 component passed and is committed as `3c997ed`. Compare integration `66af7c5` (parents `e6a01be` and `3c997ed`) to each parent. Inspect actual `m01-quantity-{build,ctest}.log`: Windows x64 under Wine passed 136 core, 9 LAN and 10 viewer tests. S18-02 is still a separate pending review.
|
||||
|
||||
The integrated S06 check passed. S18-02 now has finished production changes against `e6a01be` in the s18 checkout. Inspect both real title/handler sources in the temporary evidence directory and `client-profile-*` logs, including a real two-process title choice/save/open, normal GUI regressions, held-load Host refusal and 14 viewer cases. Validate the actual six edited files, costs and initial/async gate along with the compiled profile and LAN boundaries.
|
||||
|
||||
The S18 component passed and is committed as `180506d`. Integrated `37fb6a8` has parents `f6493e2` and `180506d`. Inspect the combined selector/quantity source against those parents, CMake and `m01-selection-{build,ctest,ui}.log`. The real application smoke used the executable in the integrated build directory.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Audit deterministic completion evidence and immutable presentation frames
|
||||
|
||||
Task ID: M01-V13
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S21-01 sibling s21 at 66af7c5 with new optional success hook and actual replay/fault barrier tests; branch final pass imminent. S17-01 sibling s17 same base with immutable packet/render caching and test target in progress. Original contracts S21-01/S17-01 and preflight F9/P6. Root cumulative currently 5a64a27 includes S18-02 profile chooser.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Review CPU observer/real replay/diagnostics and independent GUI presentation as separate completed components and later combined integration. Send all actual blocking findings immediately.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S21 worker adapter and tests/diagnostics/docs; S17 frame packet creation, D3D mesh/upload, lifetime/timer and actual test path. S06 custody15 beyond scope except future compatibility noted.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual tracked/untracked files and exact contracts in siblings. S21 world.hpp/world.cpp stage layout, WorkerPool submit/admit, tests/executor/replay/runtime, new diagnostics, end-to-end old corpora and logs. S17 actual Win32 handlers, scene packet and D3D, tests/viewer_frame_smoke.cpp, CMake, involved S18 session/GUI, Win32 smoke and docs.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch; siblings outside root graph require direct source. Check diff --check and new source separately.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S21 success-only invocation (void/value/reference/move-only, throws, overload and before_submit/before_execute failure), original no-hook semantics and capacity. Validate opposing actual completions (two real candidate calculations, separate driver/hook release), lower ID winner, serial berry claim vs parallel advancement, no flakiness/deadlocks, stale load barrier and modern Current14, domain mismatch reports and tests incl byte fallback; inspect fixture/scoped source and actual logs.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S17 after ready marker verify one immutable prepared packet held across nested callbacks even during release/install, candidate not sampled while changing before consumed Replaced, owned overlays and HUD, true camera-only reuse of prepared physical geometry and GPU upload keyed over all visuals incl reset, no extra work hidden/resized/destroyed; original camera input, GUI titles/profile and normal LAN/events still work. Check actual settled tests including two real windows, blocked file/owner, saved content, offscreen/native fallback and helper includes.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Stage A S21 ready first; stage B only on finished status, separate integrated approvals requested later. No sign-off until actual cross-component evidence and fixes are available.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Pay particular attention to return category/dangling references, accidentally recording pre-completion, capacity1 coordinator deadlock, exceptions in optional hook, tests changing data outside owner. For S17 camera/cursor geometry keys, offscreen rendering and clipping/nested frames, pending parent/child window messages, backend recreation and save/peer replacement while rendering. Do not equate Wine with native Windows.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. State source/trigger/severity and corrective acceptance per defect. 3. Verify actual logs with issue #15 link and stable old corpora, new frame target and prior GUI smoke. No unsupported physical 60fps claim.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git -C <wt> rev-parse/status/diff --check; read new files and surrounding actual consumers. In /tmp/stoneheart-milestones.xprJ2SVp inspect s21-replay-* and s17-frame-* logs and harnesses once supplied. Eventual merged refs and logs will be appended.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Check actual completed source, no early approval of another component. No source/branch/Gitea changes/children. After corrective commit re-audit relevant behavior per root instructions.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system development and Gitea, root owns all external operations; published reusable missing completion test support upstream #15 and existing publication issue #5.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V13 S21/S17 independent findings, inspected source/logs/limits, then integrated recheck when supplied.
|
||||
|
||||
S21 branch `ef980af` passed component review. Integrated root commit `048268a` has parents `5a64a27` and `ef980af`; inspect `m01-replay-{build,ctest}.log` and check its actual merged adapter, registered suites and unchanged core/GUI. S17 code and docs have also frozen in the sibling worktree at the original base plus working source. Read the actual committed-path smoke source, all tracked edits, and `s17-frame-*` logs. Verify the corrected pre-Replaced fence and stable rendering/cache/lifecycle conditions before branch approval.
|
||||
|
||||
Final S17 integration `455630f` joins reviewed `1cf8bd0` and `e9e7e82`. Cross-check S18 title/profile/host eligibility and S17 packet replacement, timer, GPU and cleanup against both parents. The build, verbose four-target CTest and separate multi-process real profile smoke are in `m01-frame-build.log`, `m01-frame-ctest.log` and `m01-frame-profiles.log`.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Audit live item ownership and checkpoint migration across real game actions
|
||||
|
||||
Task ID: M01-V14
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Independent review on root M01 at 2211144 vs a47e850. S06+S15 share ccd50ec plus validated phase/ID changes 4f4c038. Contracts M01-P5/F8, S06-03, S15-04 and docs/plan/custody.md. Real saved old v1/raw<=13, v2/raw14 historical f6493e2 world fixtures, new v3/raw15. One pending correction deduplicates consumed effects when one site input merges pooled supplies and rejects invalid duplicate result rows (root supplies refs later). User requested real upstream gaps, #7 and #8 exist. S04/S16/UI are independently reviewed.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Review full ownership/ID/transaction/replay invariants and raw15/checkpoint3 encoding, real migration + strict malformed input behavior. Send source/trigger/scope for high-confidence defects early. Recheck repaired areas and eventual integrated evidence prior to publication.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only M01 S06 physical stock/reservation/transfer logic, receipt lifecycle, balances, migration/projection, bounds/format and validation. Cross S04/S16 entry when determining effect/reservations but leave UI/transport review to peer. No code, tests, performance redesign or external effects.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect real 2211144 vs a47e850 delta in engine/include/settlement/core/{world,custody,inventory_transaction,checkpoint}.hpp, engine/src/{world,custody,inventory_transaction,world_save,checkpoint}.cpp, tests/{custody_tests,custody_migration_tests,checkpoint_tests,snapshot_tests}.cpp and tests/fixtures/custody_v14/{capture.cpp,fixtures.hpp,README.md}; M01-P5,F8,S06-03/S15-04. Look at unchanged scheduler/job/cache and replay owners as needed. S06/S15 sibling and stable historical f6493e2 source in /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14. Actual logs in same temp directory.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations, builds (root/implementers run builds), Git/Gitea changes/shared project switches or children. Review real sources, not worker summaries. Root M01 graph identity matches main worktree, check freshness/file coverage; direct source for parsed gaps and all siblings.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Trace actual grant, depletion, admission, meal, cancel while fetching/working/partial, split/merge/delivery, final generated material, retired stacks IDs and replay. Verify preflight of count/capacity/exhaustion incl multi-actor effects plus before allocating memory, no state changes after late failure, no duplicate issue on retries. Audit request key shape/cache/misses/highwaters for exactly-once and ring wrap despite losing prior receipt after retirement; differentiated source/dest refs across ops. Clarify caller-owned scheduler advance vs recoverable repeat endpoint; look for actual repeated/public invocations causing duplicate effects. Validate balance equation and max 5 material/8 claims/11 effects vs true recipes and multiple stores.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Check current/legacy save schema pairs, bounded typed extensions/no trailing bytes/digest, active vs retired references, ID allocator ordering, source/sink balances, strict phase/live ownership/claims/cache and backed capacity, genuine historical Working & routes & generic jobs, mixed/canceled blocked/suspended/unrepresentable legacy error before writing. Distinguish representable historical migration with Opening from true current state. Confirm 4096 fixed retained results and canonical order despite physical wrap. Normal file/guest/corrupt loads preserve old world. Verify resource-limited loops/allocations/drift and that doc performance describes actual configurations.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Component baseline 4f4c038 and root 2211144 are stable snapshots; sibling latest duplicate-row/consumption adjustments are ongoing and not pre-approved. Report first pass immediately, wait for frozen fixes and final root acceptance. S21-02 will incorporate Current15 authoritative replay separately; original raw13 corpora remain.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Watch valid images silently rejected at supported count/phase, malformed modern input creating economic value/alias, algorithmic overrun from untrusted huge small-on-wire counts, pre-commit partial effects, underflow on pending timer0, MAX issuance and persisted retired ID lookup. Only high-confidence findings with source & concrete realistic reproduction/impact. Native Windows limits noted.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. READY or changes required for both core and format, with precise counterexample and verification. 2. State source evidence and inspected logs of authentic schema tests, exact old outputs across modes and actual scoped benchmark/limits. 3. Audit zero-byte legacy refusal and current persistence consistency. 4. Final verdict on supplied frozen fixing ref and integrated root evidence only.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git diff --check and git show/diff a47e850..2211144 for relevant paths; git log for history. Probe logs /tmp/stoneheart-milestones.xprJ2SVp/s06-custody-*-final.log, *compare.log, s15-custody-{strict*,*migration*,*ctest*}.log, m01-custody-*.log. Read actual fixtures/capture.cpp and origin 2 corpora + metadata if needed, note no tests run yourself. Follow root graph coverage skill and direct reads for sibling files.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No additional models/tests or reproduction that mutates checkout. If same defect already under repair, mention coverage and wait for actual new source. Do not equate reported passing tests with independent correctness or native Windows. Report unresolved exposure rather than accepting a moving target.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, normal pushes and filing real library gaps; only root owns all external operations. Grants/receipts business contract in docs/plan/custody.md, retain functional old projection for normal worlds.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V14 staged defect-oriented findings with citeable file/line/domain, correction and verifiable example; state final actual refs/outcome only after recheck.
|
||||
|
||||
Final economic and codec candidate `e348a42` incorporates S06 `120db6c` and S15 `d613b73`/ `67fba6e`. It is merged into M01 `86b5fb3`, followed by documentation-only `2ba4b3f`. Inspect the actual canonicalization and issuer verification, live/terminal disjointness and operation-specific terminal states, acquisition/hauling/working/tending/meal/return phase and source/capacity rules, validated historical retained routes and ring. The final migration logs `s15-custody-final-{build,migration,ctest}.log` contain the 14 authentic and re-signed test cases. The root will attach the final combined game/transport evidence.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Audit live order controls, peer cutoff and integrated viewer recovery
|
||||
|
||||
Task ID: M01-V15
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Independent review at M01 merged 2211144 parents a47e850 + c183de1, plus 9bc52ea that includes root test fix 596b491. S04 control branch 13b4665, S16 final 6cc59b4 plus integrated data c183de1. S17 was independently accepted at 455630f. New S04 typed SessionPayload, UI and real Win32 menus; S16 gates raw13/protocol11 hosting on stable represented state and handles queued bytes/outstanding receipts; V14 peer owns core/codec details. S21-02 modern replay will be added to final source.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Read the complete actual cross-branch changes from both parent sides. Check authenticated command idempotency, exact target and presentation generation, all legacy host/rules/wire and old-binary handling across same-epoch cancellation, and S17 snapshot HUD/frame lockstep. Later issue final integrated verdict when all repaired sources and logs provided.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Review modern cancel/resume session/GUI, S16 legacy compatibility admission/drop, S18 test fence, integration boundaries including S17. Do not duplicate exhaustive core/format inside V14; identify cross-boundary contract flaws and relay either owner.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect engine/include/settlement/core/{command_dispatcher,world,simulation_runtime}.hpp, engine/src/{command_dispatcher,simulation_runtime,custody}.cpp, app/{lan_session_win32,viewer_session,viewer_win32,d3d_scene_win32}.cpp, lan_session.hpp and lan_wire.cpp, tests/{production_commands_tests,production_controls_tests,lan_tests,viewer_session_tests,viewer_frame_smoke}.cpp, S04-02/S16-03 and M01-V13, CMake and actual logs; preserve exact S18 profile/held world behavior. At final recheck inspect S21-02, actual current-canonical comparisons and instructions.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/commits/Gitea/children or shared Serena switching. Use root graph verified identity plus direct actual sources/missed lines; branch specific source via read-only git show/diff.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Inspect complete command admission and dispatch sequencing through trust gates, ledger conflict/replay, stale world/incarnation/city, refusal revision and pending local async UI. Follow open modal/quick selections, exact durable ProductionId, all orders/same cell after paging and generation/connection replacement, guest hide/synthetic action, actual game handler uses active frame. Trace protocol11 hello/auth/input/partial or queued output and completion from both standalone World and Runtime; active default 32×32 exact profile, actual legacy-representable predicate with nonprojectable mixed returns/suspended, ability to continue locally, earlier admitted results retained, later queued command refused. Question race windows at message receive/send/completion vs changing latest() when cancellation occurs in same epoch.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Old protocol unchanged, authentication maps to authoritative context. No leaked stale/partial snapshot or receipt or reapplication after disconnect; host still healthy, rejoin when eligible. User displays precise refusal/return/wait and preserves old title/profile choices, S17 immutable frame synchronization, null replacement fencing and nested modal. Test helper new bounded flush_owner retries documented RuntimeAdmission::Busy but must still assert Faulted, not mask regressions. Consider classic tests that assert immediate admission despite try_to_lock.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
At a47e850 S17 + S21 accepted. Actual 2211144 integrated core&UI+protocol. Root fresh CTest prior to helper has 5/5 targets. 9bc52ea includes helper with 24 successive viewer-suite executions in S18. Stage final includes newest core duplicate-row fixes and S21 modern replay; root appends exact ref/evidence before final verdict.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Pay attention to outstanding owner completion survives peer drop, replacing/reconnection with distinct session & same player ID, partially drained FIFO bytes vs disconnect handling, state sampled before committed result, race between readiness and send, actual old binary cross-play both ways. Aggregate genuine observables rather than promising TCP can recall bytes already sent. Prior flaky test must be protected by legitimate Busy handling and bounded wait.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. READY or changes required for S04,S16 and their S17/S18 integration independently, reproducible trigger and correction for defect. 2. Verify evidence for six real normal window controls, stale modal, real guest, old compiled two-way interop, held frame+file, prior variant profiles, actual previous signs. 3. Final merged source/CTest consistency, no unsupported native Windows performance/real LAN claim. 4. Review last S21 replay data when new ref provided.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git diff --check <relevant range>, git show --stat, actual files and surrounding calls. Logs in /tmp/stoneheart-milestones.xprJ2SVp/ s04-cancel-ctest-complete.log, s16-custody-{interop,target-ctest,legacy-corpus}.log, m01-custody-{build,ctest}.log, s18-fault-fence-repeat.log, m01-frame-profiles.log. Look at real harness/fixtures, not summaries. After appending final ref inspect corresponding logs; never require additional physical PCs to certify a Wine run.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No external operations or peer implementation, tests maintained by root/workers. Report actionable actual defects early; if correction only pending on one surface, report other subsystem separately. Never approve unseen final changes.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized all milestones, branches and Gitea, root owns remote side effects. Existing product P5/F8 authorize cancel/resume and old-peer fence; full contract in docs/plan/custody.md and S04/S16 work orders.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V15 separate source-anchored component verdicts and after final root recheck combined verdict; identify code/evidence refs and limitations.
|
||||
|
||||
Final M01 combined candidate `4bac17d` includes the S16 conditional-admission repair `447a1cf`, S17 full-custody frame assertion `f6402eb`, S21 current-canonical replay `a347337`, S18 bounded fence `596b491` and V14-reviewed economics `e348a42`. Read `s16-published-admission-{before-test,after-test,ctest,interop}.log` for the deterministic real-peer race, successful compatible retry, already admitted work and original binary exchange. Review the publication mutex and stale/Busy/null/fault paths in the actual changes. Combined build and five-target CTest are in `m01-exit-{build,ctest}.log`; independent latest executable GUI/profile, original/current interop and both old byte corpora are recorded in `m01-exit-*.log`. [Library proposal](https://git.faumaray.com/Void/Library/issues/16)
|
||||
@@ -0,0 +1,48 @@
|
||||
# Review the independent executor and rule package changes
|
||||
|
||||
Task ID: M01-V2
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Milestone integration root /home/faumaray/Projects/stoneheart_at_home at 8d2870a. Actual candidate worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s01,s19} both based on 8d2870a. S01-02 and S19-01 have test evidence, root owns integration.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently review each actual system diff and return separate merge-ready verdicts. Include new untracked files, not only git diff or implementer summaries.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Check correctness/regressions/compatibility and possible new test defects in the two bounded packages. Scope excludes later authoritative runtime and native release acceptance.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect each worktree's docs/agent-workflow/tasks/{S01-02 or S19-01}.md, CMakeLists.txt, new engine/src/rules_manifest.cpp/public header, rules_tests.cpp, worker_pool.*, world.cpp/world_save.cpp/world.hpp, tests/executor_tests.cpp and replay_tests.cpp. Use exact upstream headers at pin in /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No edits, branch/Serena switching, new builds, network writes or children. Worktrees are isolated; check cwd for each.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S19 inspect public API and actual bounded StrictJson handling, duplicate key/definition/ID diagnostics, exact SemVer incl build, canonical SHA of simulation content, order permutations, dependency closure and conflicting providers, malformed constructs and failure diagnostic. S01 inspect task capture lifetimes and guard destruction order, reserved capacity, overload retention, stop/start/error handling, expected/future semantics, partial startup, nested dispatch assumptions, injected tests and threading on Windows.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Verify original M01-C replay public default behavior and format13/LAN11; new rule identity needed by S15. User expects appropriate Void APIs and references for gaps (#4 resolver). Check public compile/link feature propagation and competing CMake edits for root.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Evidence for S19 in /tmp/stoneheart-milestones.xprJ2SVp/rules-final-*.log (9 tagged +42 core/4 LAN). S01 build /tmp/stoneheart-milestones.xprJ2SVp/executor-build; additional capacity-one replay and throwing move case being finalized with original 5 normal replay cases. Baseline 33 core/4 LAN. Root owns final integrated CMake and each system commit.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Inspect actual changed and new lines before verdict. Avoid assigning unchanged historical limitations as new bugs; label native filesystem/Windows physical checks outstanding. Read-only isolation excludes shared Serena switching. Capability process notes are not test evidence.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate S19 and S01 verdicts, P0–P3 real issues with reproduction/locations/fixes. 2. Verify evidence and exposed contracts. 3. Report integration risks and targeted regressions. Give early S19 verdict to unblock persistence integration.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Run git -C <actual-worktree> diff 8d2870a --stat and git -C <worktree> status --short; read the actual new files. Review each ctest log and check git diff --check. Optional existing binary smoke under known Wine env; no competing rebuild.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not approve unseen final changes, or perform external or repo writes. Stop once bounded evidence suffices and send findings early.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized branch-per-system development, commits and pushes. Root requested independent final review.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V2 verdict for each branch, findings with severity/observed effect, verification and anything unrun. No application edits.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Recheck executor teardown and integrated system target linkage
|
||||
|
||||
Task ID: M01-V3
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root at de38aff S19; s01 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 based on 8d2870a. M01-V2 accepted all production paths and S19; P2 concerned only promises and shared future destroyed before WorkerPool joined on assertion unwind.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
First re-review the one-line test lifetime repair in s01 and its rebuilt evidence. Then when root sends the staged integration, verify actual combined target graph for S01+S19 and any contemporaneous reviewed S16/S15 layers expressly identified.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Independent read-only review of precise previously identified risk and later integration overlap. Code/design outside changed boundaries retains its separate reviews.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect s01/tests/executor_tests.cpp test_capacity_retains_move_only_work_and_exceptions, s01/docs/plan/systems/S01.md and M01-V2. Integrated CMakeLists.txt, test registry, system target interfaces, actual git staged merge. Root provides integration refs/results at that point.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Do not mutate checkouts, shared Serena or Git. Others own code; report findings only.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Reason through reverse destruction on early failure, ScopeExit ordering, async future captures. Consult actual targeted runner log and receipt; send READY/CHANGES_REQUIRED per component. Later verify merge parent trees and union of observed features without re-reviewing unchanged code.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Core composable Windows consumers need transitive public Void::Async (cxx_std_26) and other headers' dependencies. Retain pure SHA, correct enabled modules, all sources/cases including executor/rules/replay. New S01/S19 docs report actual benchmark with Windows/Wine scope.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns merge, CMake conflict resolution, clean build and pushes. First verdict unblocks the branch commit. Remain available for integrated changes.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reversed destruction must keep promises, shared_future and borrowed worker data alive through join; guard releases before join. No native Windows or performance overclaims.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Live source + actual rerun validate lifetime finding. 2. For integrated stage identify any lost component or unintended changes in overlapping files and verify real aggregate suite counts. 3. Report verdict separately per stage.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git -C <s01> diff --check; read test lines 104–136 and /tmp/stoneheart-milestones.xprJ2SVp/executor-recheck.log (8 of 8), root reran CTest core and LAN PASS. At stage two use git -C <root> diff --cached --stat and inspect actual CMake vs named parents, link/test results root sends.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits, new roles, external writes, branch changes or builds touching worker build dirs. Stop on uncovered shared behavior or missing evidence.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Parent authorized this follow-up to M01-V2 on the specific finding; full roadmap scope permits integration after evidence.
|
||||
|
||||
## 14. Return format
|
||||
Send first verdict immediately; second when integrated staging and results are available. Findings severity, location, impact, fix and actual evidence.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Review accepted-command retention and Windows save publication
|
||||
|
||||
Task ID: M01-V4
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Separate isolated worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s16,s15} at 8d2870a. S16-01 and S15-01 each add a concrete service + tests. S16 build 43 core/replay/session incl ten session and four LAN, native Win32 writer verification finishing. M01-F3 accepted contracts. Root owns Git and app integration.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Perform fresh defect-oriented independent audit of both actual diffs. Send S16 signoff/finding early and S15 when its final test run finishes. Initial review covers independent component behavior for subsequent integration.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only S16 and S15 actual code and new paths, test quality, CMake/public API, NFK Windows error semantics. Later integration review is separate. No UI, scheduler or broad networking architecture.
|
||||
|
||||
## 4. Files to inspect
|
||||
In each isolated checkout inspect git diff + git ls-files --others --exclude-standard; source/header/tests for command_dispatcher, save_service_win32, session_tests, save_service_tests and CMakeLists. Read S15-01/S16-01 there and M01-F3 in root. Read actual World::apply_command, queue_cabin, pinned Void Async/Uuid/FuturePool, and original synchronous viewer save as needed.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations, branch actions, builds into active build dirs, shared Serena activation, external writes or children. Reviewers did not implement either change.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S16 reserve before effects; exact complete payload comparison; bounded cached accepted/rejected receipts; trusted separate player, UUIDs and city; valid new request mapping, out-of-order detection and paused/prior-world exact repeats; Before/After fault observer must poison uncommitted ledger and expose previous commitments only. Confirm all domain input validities incl extreme coordinates before arithmetic. S15 inspect FIFO identity, concurrent submission reentrancy, producer ownership on acceptance/rejection/completion, no writes before validation, bounded work/bytes, OS-level staging ownership/exclusive temp, close/flush/publish point, recovery and shutdown.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Independent API must give strong failure boundary, cloneable dispatcher with candidate staging and exact unchanged legacy format13/LAN11. S15 single writer, atomic same-directory replace; share denial may return prepublication failure, preserving old bytes. Requiring replace-through-held-handle across all Windows filesystems is outside game contract. For that specific error test prove visibility flags, unchanged old data and next success after closing.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root merges CMake with other branches preserving Void::Core public and previously reviewed Async/Rules. Later runtime consumes these primitives; no new native/cross-platform durability claims. Compare upstream actual API and latest registry before raising feature gaps.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check exception surfaces, future lifetimes, retained failures, no success exposed after partial domain mutation, no unsafe catches/rolled-back state claims; UUID/session fence; Windows Unicode paths, sharing, race before/after rename, close errors, relative path rejection and whole contents for readers. Do not equate program-crash publication with durable power-loss protection.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate scoped READY/CHANGES_REQUIRED for S16 and S15 with actual locations/impacts. 2. Compare accepted F3 contracts to implementation incl test-on-failure cleanup and producer concurrency. 3. Check real tests, counts and flags. 4. Distinguish legacy limitations from introduced bugs.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
From each checkout git diff --check; git status --short; inspect explicit new files and matching ranges. /tmp/stoneheart-milestones.xprJ2SVp/session-final-{build,ctest,tag}.log and /tmp/stoneheart-milestones.xprJ2SVp/save-build/Testing/Temporary/LastTest.log and final save-tag/build logs when ready. All computed tests Windows x64 under Wine.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. Return actionable findings immediately. No external writes or blind reruns. If either component needs a repair, identify distinguishing check before re-review.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized plan, system branches and remote MRs to main. Parent retains authority to publish and rechecks merged components. Review doesn't approve main merge.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V4 S16 and S15 independently, actual files and tests inspected, severity/code location/rationale for any defect, native and integration gaps.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Audit snapshot ownership and checkpoint compatibility
|
||||
|
||||
Task ID: M01-V5
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S01-03 actual implementation in /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 at 68f91a2, S15-02 in ../stoneheart_at_home-worktrees/checkpoint detached de38aff. They independently implement immutable owner captures and persisted modern envelopes. Other reviewers cover writer/dispatcher and past S01/19. M01-F3 remains controlling for failure/publication.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Read-only final independent review of both real source diffs before branch commits. Send per-branch verdicts early. Later integration will be separately verified.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Review exact changed snapshots/logical field partitioning/lifetime and checkpoint/rule catalog extraction/format gating, tests/limits/headers/CMake. No runtime owner or future custody field required from these narrow slices.
|
||||
|
||||
## 4. Files to inspect
|
||||
Each worktree git status, git diff (tracked changes), explicit new files. Review world.hpp/.cpp, snapshot_tests.cpp, surrounding const rendering/WorldSaveCodec, checkpoint.hpp/.cpp, checkpoint_tests.cpp, rules_manifest.hpp/.cpp, target and actual pinned Void Binary/SHA/Uuids. Read S01-03/S15-02.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children, shared Serena project stays at main game. Direct check worktree source and evidence; you are not an implementer.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Snapshot: reason about every logical field vs executor/cache, copied nested state and observability, no callbacks/pool/references retained, C++ construction/copy/move/const escape/lifetime on exception, no silent public ABI caller break. Checkpoint: check endianness/checksum coverage, length/overflow/allocations before validation, bounded work/memory, no eager megabyte unbounded allocations for tiny malicious body, compare entire installed closure order-independent, identity/tick matching, unsupported versions/trailing data, SHA >16 MiB, named error, independent candidate.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Existing raw save13/LAN11 APIs and exact bytes unchanged. Running captured world is read-only. Modern binary envelope has stable nonnil UUID/city/rules/tick, current body on existing serializer, no on-disk active session/ledger. CMake public types propagate Void::Core.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns CMake/Git and cross-component integration. S01 path will underpin renderer/background saves, S15 prepares candidate; do not claim they're connected in this slice. Fresh win native/physical tests unavailable here.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Investigate invalid input triggering count-based huge allocations despite small outer blob, default/moved-from rules objects, empty rule sets whether legal in resolver, stream consumption/trailing and portability. Catch definite problems in changed surface; distinguish historical legacy-parser behavior. Snapshot test failure-path lifetime/drain warrants attention.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. Identify file and precise trigger/consequence for defects and proposed focused regression. 3. Report current actual build/test evidence and any unverified claims.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git -C <wt> diff --check; inspect new files with real paths, /tmp/stoneheart-milestones.xprJ2SVp/checkpoint-{build,ctest,tag}.log (8 checkpoint, 50 core and 4 LAN). S01 capture is 4 snapshot plus full suites and benchmark in same temp folder as capture-* when available. No rebuild needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Remain read only; send urgent actionable findings after validating reachability. No speculative redesign, external actions or other agents.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved roadmap and PRs. Parent owns commits/push and review acceptance; local independent branch certification doesn't approve merging main.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V5 S01-03 and S15-02 verdicts, actual evidence, limitations and any re-review scope. Send first ready ASAP.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Verify the combined M01 systems and preflight stable storage references
|
||||
|
||||
Task ID: M01-V6
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M01 main worktree /home/faumaray/Projects/stoneheart_at_home commit 2224299 vs earlier integrated cf0cc2f. Reviewed component tips 84a78ef S16, fd17a2f S01 capture, 3844ebb S15 writer, 15da3f4 S15 checkpoint (parent de38aff S19), combined S15 db4ac30. Reviews M01-V4/V5. Separate prospective S06 slice proposed by M01-P3 planner.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
First adversarial integration audit of 2224299 and db4ac30, including actual target union and cross-file operating limits. Second, read-only preflight for replacing runtime positional storage/node references with existing durable IDs. Separate verdicts.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S01/S15/S16/rules integrated surfaces and upcoming first S06 migration. Owner/runtime not yet in integrated commit. No implementation.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect git diff cf0cc2f..2224299, all merge parents, s15 CMake db4ac30, primary headers checkpoint/save_service/world/command_dispatcher/rules_manifest and normal callers; logs. For S06 World::edit_object/gather/assign/finish, Agent/MaterialReservation/ConstructionStop, WorldSaveCodec::body/validate/load, viewer resident detail, tests.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations, branches, external actions, children or shared Serena switching. Other agents own future changes, compare named commits only.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Audit merged code vs exact source commits for lost fields, ABI or modules, transitive flags; verify actual native-target build reports core tag counts and compatibility. Check whether max_checkpoint_bytes and SaveService limits align for explicit caller config, typed capture/dispatcher/codec work together. Record any unmet obligations to runtime instead of claiming integration already wired.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
First S06 proposal: stored Agent/MaterialReservation/ConstructionStop references to existing sorted Storage.id/ResourceNode.id migrate from index/sentinel to nonzero actual ID/zero none in live memory; bounded lookup via lower_bound or equivalent. Legacy byte layout retains positional fields only inside WorldSaveCodec: stage raw positions during deserialization in separate bounded temporary structures, resolve against fully parsed pools before domain validation; encode inverse mapping and reject invalid refs before writing. Existing public code/callers updated where needed; vector order/indices are transient iteration only. Stable production, transfers and item IDs follow separately. Verify there is no non-reference zero or order interaction that breaks this. Present recommendations for const accessors/source compat as needed.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Run-time 20Hz, UI/file/lifecycle wiring and larger S04 IDs are future; new S06 can progress with disjoint package files while runtime owns separate files. Root merges/updates Gitea. F3 controls fault bounds. No branch push from reviewer.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Review save13/LAN11, root's complete CMake stack and old caller behavior. S06 legacy unordered/invalid data, max sentinel, moving/deleting unrelated earlier elements with active reservations; encoding cost O(N log M) not quadratic searches. M00 goal records nonempty demolition intentional confirmed by human choice; any accounting change separate.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate integrated READY/CHANGES_REQUIRED with actual evidence 82/82 core and 4/4 LAN; S15 59/59 +4. 2. First S06 task READY/needs correction with concrete narrow stop conditions and reproducible tests preserving canonical save13. 3. No approval of unseen runtime or native acceptance.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git diff --check cf0cc2f..2224299 and git show --cc db4ac30; compare source blobs to each branch, inspect /tmp/stoneheart-milestones.xprJ2SVp/{m01-candidates,s15-combined}-{build,ctest}.log. For S06 inspect real world/codec/HUD paths via targeted graph + source, reachability and smoke fixture behavior.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits/builds/Git/remote mutations. Send integrated review immediately. Stop if older valid format or dependency would force distinct migration beyond current scope. Return actionable findings, no speculation.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all system/milestone branches, commits/push and merge requests into main. Root alone publishes cumulative integration. This is final integrated review plus prospective S06 technical gate.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V6 two verdicts: integrated M01+S15 and S06 preflight. Evidence, limits, actions and native gaps.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Recheck S06 allocation limits and audit the simulation owner
|
||||
|
||||
Task ID: M01-V7
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M01-V6 accepted system assembly 2224299 but required one S06 design correction. New task S06-01 is in /home/faumaray/Projects/stoneheart_at_home-worktrees/s06 at a4cf99c. Runtime S01-04 implementation is in sibling s01 worktree at 2224299. Reviewer did not implement it.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
First confirm that revised S06-01 resolves the sole preflight finding. Then independently inspect the actual integrated runtime/World/command/clock/publication contracts and new tests before its branch push.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Stage A preflight limit/failure invariants only. Stage B actual S01-04 core changes, CMake, tests and docs. UI/transport/disk integration not yet present.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read s06/docs/agent-workflow/tasks/S06-01.md sections 6–10 and World allocation positions, S01-04 spec and new simulation_runtime.hpp/.cpp, runtime_tests.cpp, CMakeLists.txt, docs/plan/systems/S01.md. Check previous M01-F3, S16 receipt staging, load API, const captures, pinned headers with actual worker join/clock behavior.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children or shared Serena switching. Use direct actual isolated sources (outside graph). Parent owns all fixes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
A. Confirm MAX terminal, allocation MAX-1 publishes successor MAX before exhaustion, use checked successor before vector/terrain effects, factory overflow vs command Busy, loaded MAX valid, include direct field/mine + add_storage/PlaceStorage. B. Critique single owner restart/load and epoch ordering, short locks, healthy/faulted snapshot read, receipt transaction, active+queued completion and shutdown, fixed deadlines across pause/suspend/exhaustion, concurrency, manual-clock tests and real worker drain.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Read actual SimulationRuntime new header, RuntimeSubmission/Result, LoadTicket, commit/wakeup and scheduling code. Freeze public API only if no correctness gaps. Record how caller retries transient Busy and obtains new contiguous IDs after completed rejects; latest snapshot meta must agree with committed ledger. Check latest request vs current epoch immediately before installation and preserve old publication on failed install.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns integrations. S06 work begins on stage A verdict. S01 acceptance is limited to tested core; GUI/S15 adapter must acquire healthy immutable save capture and limit bytes. Platform is Windows x64 under Wine.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Look for timing regressions from owner using admission clock timestamps, unchecked overflow, transaction window with visible successes after fault, queued mutators in faulted state, settlement of pending loaders/receipts, captured aliases and mutex hold during disk/tick/owner join. Check repeated and failed calls on background owner and teardown.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Return stage A feasibility verdict immediately and stage B independently. 2. Compare source+tag tests to F3 and all required observability/fault/stale boundaries. 3. Report any reachable defect with cause and precise regression. Native acceptance separate.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
use git -C s01 diff --check; read new files, /tmp/stoneheart-milestones.xprJ2SVp/runtime-{final-build,final-ctest,final-tag}.log. Run no competing builds. For A inspect new contract plus actual world.cpp 396–425, 770–803 and world_save.cpp validation.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. Stop if phase evidence not ready, but return the other independent verdict first. Contact parent for code changes and bounded follow-up if needed.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes roadmap, pushes, MRs and upstream issue tracking. Root requests corrected preflight and fresh code review before integrating core runtime. No external actions by reviewer.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V7 A/B READY/CHANGES_REQUIRED with file/location/evidence, expected symptoms/urgent fixes, counts and residual native/UI risks.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Audit the storage and resource identity migration and file adapter
|
||||
|
||||
Task ID: M01-V8
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S06-01 isolated worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s06 baseline a4cf99c, separate S15-03 in s15 baseline 8c4c1fe. M01-V6 and corrected V7 preflight S06. M01-F4 accepted S15-03. Both packages have single owners; this reviewer is independent.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Verify S06 actual full migration/legacy bytes and then S15-03 actual file reader/writer adapter implementation when ready. Give independent per-branch verdicts with real evidence.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only two component reviews; do not infer viewer is wired or production/stack identity finished. Scope new code only plus changed cross-file contracts.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect git diff/status plus new files in both worktrees, actual WorldState/World/WorldSaveCodec/body/validate/HUD/identity_tests and S15 checkpoint_files header/source/tests, SaveService/modern envelope and project tasks. Compare against pinned Numeric/Async/UUID and actual command/loader callers.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children or shared Serena switching. Others own code. Read exact worktree files directly if outside graph.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S06 exhaustively check migration sites including partial no-ref (tending, meal), erase/shift, validated sorted IDs and lower_bound, no deref absent pointers, constructor/command MAX and MAX-1 behavior before effects including mine changes/command sequence, codec preserving old positional bytes, loading malformed pool order/IDs/dangling refs before validation without out-of-bounds. Review real tests and any new allocations/complexity.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S15-03 check one handle path read under bound incl growth/trailing/truncation/EOF, modern magic + bad version cannot downgrade to legacy, fresh stable legacy UUID and default compatible rules, load future and diagnostic/caller action, max_checkpoint_bytes writer, one bounded reader queue plus in-flight, concurrent shutdown, no live worker pointers, progress of writer while reader stalled, snapshots/futures release resources safely under failures.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root merges S06 and S15 work; UI and other packages are independent. If S15 not ready yet send S06 verdict first; parent will provide ready files/logs. Per-component review only; native Windows integration later.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check actual pre/post baseline bytes and high-water exhaustion semantics; preserve intentional demolition behavior. Inspect kernel calls and archive validation handling hostile/malformed data defensively. Guard test teardown and multi-GB file size observations. Do not equate program exit with physical durability.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. Report precise reachability + fix/regression for material issues. 3. Check observed test completeness, external trajectory compatibility and tool limits. 4. Name additions needed before combined normal entry.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git -C each worktree diff --check; inspect /tmp/stoneheart-milestones.xprJ2SVp/identity-{build,ctest,tag}.log and identity compat/trajectory binaries using wc/sha256sum. file-adapter-{build,ctest,tag}.log when ready. Check newly added files not yet staged for whitespace if appropriate.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. No competing builds. Send an early confirmed finding or verdict on S06. Report S15 only against complete available implementation.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root requested two independent checks, user authorizes roadmap system branches/MRs and cumulative pushes. Root retains mutation authority.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V8 two scoped reported verdicts, real files/commands/counts, untested native or integration requirements and re-review scope.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Verify merged logistics references and preflight modern production identities
|
||||
|
||||
Task ID: M01-V9
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Main checkout milestone/m01-authoritative-simulation c2d9d8d (parents 512c9ef, S06-01 8260e09); S01-04 integrated at 8c4c1fe. Reviewed S06 and compatibility corpus M01-V8. Next owner migration M01-P3 calls for persistent production IDs in S04 while legacy format13 remains stable.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently verify merged S06+runtime and preflight the concrete S04-01 modern identity + codec migration. Send integration verdict early.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Integration of actual components only, no assumption viewer already uses runtime. Preflight production IDs only, no broad transfer registry or new region architecture.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect git diff 512c9ef..c2d9d8d, both parents and CMakeLists.txt, WorldState/world.hpp, world.cpp, world_save.cpp, checkpoint.hpp/.cpp, S06 identity tests, normal consumers, compat traces. S04 plan M01-P3, existing save13 and checkpoint-v1 writer/parser plus legacy import adapter in s15.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children or shared Serena activation. Other workers continue on their own worktrees.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Verify application blob equality vs reviewed S06 apart from merged CMake and actual registrations/linkage: Math for checked_add, Time public for runtime, tests identity/runtime all active. Analyze unsupported legacy boundary for next stage and identify every order insertion and caller that must reserve a whole ID batch before normal return.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S04-01 proposal: ProductionId nonzero, stored ProductionOrder::id, Agent::production_id (0 absent) and copyable persistent WorldState::next_production_id_. All three insertions (queue_production + two PlaceRoom loops) and every recipe/room/cabin batch share checked allocation, sorted ID vector/lower_bound; valid MAX next terminal never wraps. No partial ordinary acceptance/rejection. Reuse Void Numeric checked operations, upstream #7. Existing raw World::write_save default still v13, exact position projection for older readers; explicit modern raw body v14 includes order IDs, next counter, durable agent refs. Checkpoint encode becomes v2 using v14; decode preserves authentic v1 + old bodies incl valid old legacy imports and rejects inconsistent v2 body / bad version/IDs. New modern canonical replay includes all durable fields; old files import IDs deterministically in vector order with next greater than all. Game session/UUID untouched. Reject duplicate/zero/dangling/current ID, invalid/exhausted batch before mutation; erasing highest then reloading modern snapshot must not reuse it. Isolated S15 file signature classifier uses shared envelope magic, keep unchanged. Legacy wire13 loss of new auxiliary ID history accepted only at its explicit export boundary.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns cross-component integration. S06 and S04 touch shared World/serializer, so sequence them. Viewer branch will update one resident production lookup during merge; avoid changing S18 normal UI design. Existing legacy public code and normal current renderer must keep working. Require exact statement if prior v1 had stricter/looser body behavior.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Inspect O(NlogN) lookup, checked arithmetic including batches; post-decode forward reference resolution; cache/loader behavior incl ordering. How to preserve old test fixtures while schema bumps: freeze old known bytes with successful read. No overwriting current schema fixture pretending compatibility. Watch allocation without effects vs retry/reporting in dispatcher (must preserve world when returning Busy).
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per integrated S06 and S04 preflight. 2. Concrete blockers/acceptance e.g. continued mid-carry world, removed order before unrelated active target, MAX-1 vs >=2 batch, wrong outer/inner pairing, replay serial/2/6/12. 3. Report real aggregate evidence 99/99 core+4 LAN; use old/new binary comparisons from S06.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git diff --check 512c9ef..c2d9d8d; git show -m --stat c2d9d8d, compare selected paths to 8260e09 and 512c9ef, inspect actual /tmp/stoneheart-milestones.xprJ2SVp/m01-identity-{build,ctest}.log and identity compat hashes, scoped source/caller reads. No builds needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. Send confirmed integration verdict promptly, then preflight scope. No speculation without source validation.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system development, pushes, PRs and upstream linkage; parent retains publication/merge authority. These are final integration and design gates.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V9 integrated and S04 preflight verdicts separately, concrete failure scenarios/test boundaries and unverified native state.
|
||||
|
||||
## Additional merge under review
|
||||
|
||||
The root subsequently merged the independently reviewed S15-03 commit `a063894` into `c2d9d8d`, producing `4ba64f7` with an automatic CMake merge. Check the added checkpoint file service, classifier, test registration and their actual blobs against the S15 parent alongside the integrated stable-reference codec. Verify `git diff --check c2d9d8d..4ba64f7` and the real `m01-files-{build,ctest}.log` under the same verification directory. The combined suite passed 106 core and 4 LAN cases. Send this bounded verdict separately under the same read-only restrictions.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Review finite voxel region contracts before implementation
|
||||
|
||||
Task ID: M02-F1
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Read-only preflight of M02-P1 initial design from actual 455630f M02 worktree. The signed 32³ sparse page foundation is independent of M01 custody 539cea0 now in progress. Existing renderer already uses z as vertical height via x−y, (x+y)−z and existing viewer picks the z=0 plane. Library first M02-R1 confirmed pin 7b0fea6, upstream #11 signed division and #14 sparse atomic edits, #12 ray traversal, #13 revision readsets, #10 RNG; actual public math/binary/hash available.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently decide whether bounded S02 geometry/generation contract is safe to implement now. Review the later S03/normal runtime/save/presentation boundaries insofar as they constrain S02 data. Send foundation verdict early; root may later supply planner final addendum.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only M02 correctness preflight with first S02 slice priority. No implementation, release/PR acceptance, M03+ design or approval of unchecked future code.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read real M02 worktree docs/agent-workflow/tasks/M02-P1.md, M02-R1 and plans M02/S02/S03/S15/S17/S18, void-library.md; root existing world.hpp, world.cpp WorldState::capture, worker_pool, world_save and checkpoint, app/map_camera.hpp, d3d_scene_win32.cpp shader, viewer_win32.cpp pick_grid, first_colony and actual tests; private current15 in /tmp/stoneheart-milestones.xprJ2SVp/combined-custody. Inspect exact graph root only if relevant; direct sibling sources required.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posting, shared project switching, user contact or children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Attack proposed NEW VoxelRegion/value view with nonzero RegionId, int32 voxel xyz, finite half-open bounds, ordered key directory/sharing immutable 32³ pages, generator keyed by exact seed+version+absolute xyz, queries separate outside/unloaded/loaded air. Page publication precedes ready only at logical designated step. Edits validate all expected revisions/bounds/materials/caps/unsupported operations, finite canonical order and no partial mutation, publish touched revisions once and invalidate face neighbors without fictitious content changes. Focus on material id stability, thin bounds intersecting pages and border operations. Query correctness at both signed extremes and boundary examples, no pointer/reference mutation. Check which exact domain is expected to be represented.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Review ownership/constructor/geometry exposure, immutable page pointers vs mutable alias to page/cache/directory, exact all-or-nothing publication, result visibility/cache invalidation incl reads of inactive/neighbors, validity of one stable geometry revision for render and path when head changes due to activation/deactivation. Propose minimal interfaces and stable tests without duplicating future WorldState. Check D3D renderer z-up and slice/face tie contract.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Foundation worker has isolated file ownership in NEW voxel_region.hpp/cpp/test plus CMake and S02 docs. World/runtime/save protocol integrating with S15/16 requires final agreed schema and cannot clobber S06 custody15. Preserve protocol11 by explicit representability; original 2D first colony must remain readable/playable.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Negative division at INT_MIN and max half-open bounds, dirty neighbor overflow at extreme chunk ids, seed sign/ordering/algorithm version, bounded page/batch memory and worst-case old snapshot retention, revision rollover/admission, no-op/duplicates/conflicting expectations; negative/zero ray incl edge tie, stale auth, work/tick exposure, failed chunk activation/crossing. Differentiate genre policies/materials and requested Void issues.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. READY or BLOCKED with precise mandatory first-slice fixes and testable criteria. 2. State if parallel independent implementation is sound within compiled M02 base before M01 finished. 3. Capture edge behavior and feasible tests for generation, bounds, stale atomic recompute, immutable view, deterministic batch and subsequent consumers. 4. Mark unknown physical target verification. Do not review a future code diff prematurely.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse and source refs in the M02 and combined worktrees. Compare pinned source with M02-R1 and note no binary evidence unless reading actual existing logs. Project index root-only; direct reads for sibling files. Later CTest should use exact Windows x64 GCC16/Wine test setup in M02-P1.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No approval of M01 scope or M02 implementation, no code, no Git/Gitea changes/children. If a substantial missing contract is identifiable, provide counterexample and precise remedy without tacking on speculative features.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested end-to-end milestone implementation and library gap filing. Preflight gates first edits, not engineering judgment on reversible local choices. Root integrates findings into worker specs and owns upstream effects.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-F1 preflight with earliest foundation assessment then notes for remaining consumers, actual source references, required tests and stop conditions for implementation.
|
||||
@@ -0,0 +1,49 @@
|
||||
# Review the authoritative voxel scenario and checkpoint transition before coding
|
||||
|
||||
Task ID: M02-F2
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Second-stage M02 technical preflight at real region+M01 base13dc673/4bac17d and actual S03 at7a7ff32. M02-P1/F1 foundations passed, one integrated S02 session and strict M01 V14/V15 with custody15. M02-P2 developing exact owner/codec/rules seams now. Need review sufficient constraints for safe parallel World+S19+S15 activation & GUI integration.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Validate the proposed authority/scenario/language boundary, inventory and durable job semantics, activation and serializer evolution. Earliest verdict on independent S19 compiled profile/new factory and World interface so coding can start promptly. Produce concrete corrections, not a feature redesign.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only preflight M02 bounded playable region; no app edits/merge approval or speculative full future city economy. Do not review S02/S03 implementations, separately reviewed. Use their frozen contract as dependency.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read actual world.hpp/world.cpp (2d access, step and capture), custody.cpp/world_save.cpp/checkpoint.cpp, simulation_runtime.cpp+command_dispatcher, rules_manifest.cpp/colony_profile.cpp, viewer_session.cpp/lan/session compatibility, M02 P1/P2/F1 and M01 custody doc, actual sibling S03 voxel_navigation.hpp and S02 region. Include current coordinate types and schema readers and scenario paths.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote/children/shared project switch. Report to root, do not change app or tasks. Direct evidence in separate worktrees.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Adversarially map GridPosition.z=0 for historical records vs one canonical foot in voxel mode; existing flat maps and x/y commands must not alias a different elevation. Compute how typed region/session/observed revisions, stable TerrainOrderId and actor progress, retained terrain target/cargo and actual S06 balances survive failure and reload. Need atomic prospective edit+stock/reservation durable issuance with no-throw publication, accepted cancel retries no duplicate yield, and no loss if storage full. Distinguish extraction operation from ResourceNodeId to avoid wrong source resolution, normal distribution checks and checked allocator. Reconcile system ownership and dependent header freezes.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Validate explicit finite profile & compiled generator/material package, retain byte-identical old two profile manifests and historical modes. Proposed raw16/checkpoint4 pairs and legacy before-byte rejection; new z on applicable physical positions/route, terrain order highwaters and source claims/opaque receipts, canonical generator/deltas, required activation state/revisions, fresh session rekeys no replay of stale external work. Snapshot freeze cheap; save after removal of a future support must preserve target, current safe foot, cargo and next logical choice. New World mode controls stale typed commands without breaking old players.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Activation barrier must operate before any logical step mutation: target due_tick/required keys, background read/generate/validate returns identities and immutable data, all due batch publishes in sorted order or none. Read failure publishes a recoverable fault, stable old snapshot remains, load/shutdown cannot join a blocked data task inside owner. Exact work remains for S19(profile), S01(owners), S02(file prepare), S15(schema), S17/S18(runtime UI). M02-R2 separately validating Void options; use actual #5/#9/#13/#14/#15/#16 where applicable.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Test when same material read/target cross2 pages, support under current person/structure or next planned step, phase=complete still full, single-grant before resource/writing receipt, unknown material/generator/deltas shape, uint32 overflow, observed revision changes on inactive/missing neighbors, obsolete I/O completion after rollback of same region, elapsed clock during wait must not create simulation debt/extra ticks. Physical Windows cannot be asserted.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Earliest scope/lifetimes for S19 formal profile and core public interface sufficient for coding in disjoint files. 2. Concrete counterexamples and remedies for ownership/atomicity or migration data loss, plan constraints for source/bounds/IDs. 3. Achievable real tests marked per cross-component responsibility. 4. Distinguish open P2 confirmation vs actual blocker. Return verdict once planner final available.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only direct current source and git rev-parse/show per worktree. No runs or claims of tests of proposed code. Use pinned library source for specific claims, or refer to upcoming R2.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No user contact, remote posts, implementation or pretending future code pass. Do not demand physical PC or unneeded larger product choices for first bounded code. Report immediate corrections as found.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved roadmap; root delegates technical choices and owns all publication. This preflight supplements M02-P1/F1 for actual playable integrated scenario after S02/S03.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-F2 PREFLIGHT with earliest S19/World actionability, actual file references, required tests/failure boundaries and any resolved/remaining blockers.
|
||||
Preflight accepted the integrated contracts after the viewer explicitly supported the 32×10 terrain region, contact selection required a stance still supported after excavation, and execution lifetime allowed install and shutdown before a blocked old preparation returned. The first due boundary uses requirements from a previously published snapshot. Scope covers the contract only; real gameplay, schema and runtime reviews follow implementation.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Design the first playable editable voxel region and its integration
|
||||
|
||||
Task ID: M02-P1
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
The user approved implementing M00–M12 on milestone and system branches. M01 currently provides a 50 ms authoritative World, immutable snapshots, authenticated commands, released rules profiles, protocol11 and modern checkpoints. M02 worktree at 455630f has S17 immutable frames and S21 real scheduler tests. Local M01 candidate 539cea0 adds modern raw15/checkpoint3 transfer persistence. An independent pin/API audit M02-R1 at Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 found library gaps reported as Void/Library #10–14. This is a preparatory design while M01 exit evidence is in flight.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide actionable dependency boundaries for M02 and the first implementable S02 region/chunk/component that can be built now without conflicting with M01 custody work. Continue to cover S03, S17/S18, S15 and normal owner/runtime end to end so the first terrain output has real consumers.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only milestone architecture and phased, playable acceptance. Focus limited M02 editable voxel scenario through two levels and chunk edge. Defer M03 colony storage/building changes, water, other worlds, plugin changes and release. No arbitrary lowering of approved roadmap scope or new UI product choice.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/milestones/M01.md and M02.md; docs/plan/systems/{S02,S03,S15,S17,S18,S21}.md, docs/plan/void-library.md and M02-R1; engine/include/settlement/core/{world,simulation_runtime,command_dispatcher,worker_pool,deterministic_rng}.hpp and world/first_colony/world_save CPU paths; app/d3d_scene_win32.*, map_camera.hpp, viewer_win32.cpp, tests/frame/replay/identity/checkpoint. Use actual names in results. Read sibling custody.hpp and checkpoint.hpp at combined 539cea0 to avoid schema collision. No fetching private data outside project.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No edits, branch/remote ops, builds that modify worktrees, project switch or children. Parent persists results. Root and sibling agents are working in separate checkouts. For isolated M02 use direct files and avoid changing shared Serena project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Map owner/tick/frame/file architecture, deterministic generation keyed by signed world location, gates for snapshots/cache and async activation. Specify finite 32³ sparse page representation and signed Euclidean division, fatal and retriable edit paths, exact row/coordinate order, native Win32 interaction scenario, known old-save/old-LAN behavior and how these can be tested using real consumers. Identify the first S02 slice that can receive an independent concrete coding contract at once; send it early.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Propose NEW clear types and methods by responsibility with essentials only: region identities/int coords with z up, bounds/limits, material query/source/support+edit revision set and undo on failure, copy-on-write pages immutable to snapshots, deterministic per-chunk source and edit overlay; S03 use cases incl stable ties, minimum profile/door/stairs and consulted revision sets incl misses and neighbors; ray/pick face from D3D Y-up conversion and actual commands; M02 persistent version/generator identity; reconcile normal M01 World lifecycle, actual public source/test consumers and authored test scenario. Distinguish proposed APIs from existing ones.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root reconciles M02-R1, planner, independent preflight and starts S02 in an isolated branch before coupling to mutable M01 sources when safe. Make ownership/dependency ordering and concrete integration points clear. Source-only private S06/S15 candidates must never be treated as published.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound coordinate overflow (INT_MIN, ±32), sparse memory and checked edit count, stale/mixed revisions, border invalidation, optimistic deterministic admission/queued jobs, signed normal/cell at equally crossed faces, old saves and LAN projections of edited maps, delayed/out-of-order and corrupted chunk I/O, camera/view consistency and finite scheduling. Respect pinned Void API/tests and replacement cases for #10–14 in repository matrix.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Concrete HOW/WHAT for S02 first worker including new files/headers/CMake and behavioral tests with cross-boundary negative coordinates, immutable snapshots, failed multi-page edit and independent generation. 2. Bounded follow-on packages S03, authoritative/edit/tick+save, real UI and exit verification with actual dependencies. 3. Identify genuine missing library contract only after checking pin and issues. 4. Normal small scenario is visible, editable, traversable and survives save/restore across thread order.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git -C <m02> rev-parse HEAD/status/diff and git -C /tmp/stoneheart-milestones.xprJ2SVp/combined-custody show as needed; use direct source in sibling worktrees. Give real proposed CMake GCC16 cross and CTest commands for later workers based on /tmp/stoneheart-verify.KoZwE4o8/env.sh and existing target. Native Windows cannot be asserted from Wine.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop and report if a required product choice truly blocks first slice; use reversible decisions matching approved M02 otherwise. No source mutation, speculative library ticket, user messages, or children. Do not claim test execution.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User explicitly asks to implement all milestones, reuse library APIs and file concrete gaps. Root owns all side effects. User authorization already covers bounded M02 foundation and branch/MRs.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-P1 PLAN with early immediately implementable S02 slice, dependency order/ownership, immutable contracts, concrete tests/risks/source refs and remaining evidence. No approval or merge decisions.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Freeze owner, terrain work and persistence contracts against the new voxel APIs
|
||||
|
||||
Task ID: M02-P2
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M02-P1/F1 established architecture. S02 frozen and component-reviewed 1ca481b, actual S03 navigation public header at sibling e7046a9 (implementation/tests soon), actual M01 final custody/conditional admission at root4bac17d. M02 worktree13dc673 contains raw15/checkpoint3, S02 and C++ rules; next is a real playable topology with authority, durable work, 3D save, selected profile, render/pick and nonblocking logical activation. A separate worker is building S17 D3D surface/picking.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Resolve exact interfaces and ownership/order for immediately implementing the complex M02 authority and persistence integration, including yield to S06, mode & position adaptation, atomic support edits, logical activation/resume and old save gate. Return first implementable independent owner package early.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only second-stage architecture of approved M02, ground it in actual immutable S02/S03 types and new M01 version. No M03/multiregion/water, fake demo or rewriting all old economics simply to get pictured. Prior plan is accepted; extend missing seams only.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read M02-P1/F1, M02 plan/S02/S03/S15/S16/S19 and docs/plan/custody.md, actual merged world.hpp/world.cpp (GridPosition, mutable economic work and capture), custody.cpp/world_save.cpp/checkpoint.cpp, simulation_runtime.hpp/cpp state/load/fault/publication, command_dispatcher.hpp/cpp variant ledger and session UUID, first_colony.cpp, colony_profile/rules_manifest, viewer_session gates. Inspect exact s03 header and S02 region implementation; S17 CPU pick in design.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote/children/shared project switches; root will persist reconciled interfaces. Isolated m02/s03 use direct reads; do not query root index as if identical.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Map minimum full normal gameplay journey: player selects terrain profile, actual resident starts at canonical 3D foot, path through two-cell open/closed door + traversable stairs to cross-chunk upper face; issue excavation order, work from safe adjacent cell, mutate terrain + real material yield with ledger exactly once, close/open door/remove support and recover path, save at that boundary, load and deterministic continuation. Choose precise failure/receipt semantics when any staged operation cannot run. Keep normal actors/stock/stable IDs (no uncorrelated duplicate resident list). Formulate schema proposal for new fields and highwaters and adaptation of old2D.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Specify NEW APIs and minimal concrete owned paths for (i) S01/World terrain metadata, GridPosition.z compatibility, durable terrain orders/actor progress/route and highwater + S06 grant/reservation integration; (ii) required chunk activation: actual work/visibility demand, prepared immutable backing page or regenerated natural + deltas, stable due_tick/reasons, handle root owner publication if waiting/faulted, recover same request or load, bounded CPU/I/O/stale fences; (iii) separate S15 raw16 /outer4 including exact explicit old mappings, route goal/position/deps and fresh session, transactional fallback before first byte for raw13–15 incapable of representing new terrain. Defer performance features while preserving tests and normal enablement. (iv) S19 exact profile/compiled data and current/legacy validation, S04/S16 modern typed edit and client hooks.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Your P1/F1 work covered baseline. Now target actual available types so core/codec/profile/runtime developers can work simultaneously on frozen header without overlapping files. Direct dependency on S03 valid real header + later library implementation. Temporary detached WTs for M02 system packages allowed by root; one per published milestone/system. Separate geometry source/checked memory before side effect.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Stairs and headroom, unsupported occupant/occupied cell cannot be removed, coordinate vs interacting face/adjacency, edits may cross 2+ pages, revision set stale after partial fulfillment, wait-before-effect while full storage, durable exact chosen region/worker/target, rollback/new session re-key route readsets without accepting stale pending execution. Existing WorldState type-copy/inventory caches and old `GridPosition` equality/subscript. Bounded file/scope staging and possible O(N) deep copies. Loaded invalid geometry/queue errors must leave previous snapshot. No synchronous permanently blocked I/O in owner or destructor on replacement.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source-grounded immediately dispatchable WHAT/HOW for first owner plus peer stages with exact data types/fields/ownership. 2. Minimal integrated test scene exercising real commands, route, stock, save/load, old 2D and held activation. 3. Acknowledge genuine potential wider interaction e.g. legacy 2D methods interpreting z and give guard/fallback. 4. Distinguish what directly exploits existing Void vs any confirmed generic missing guarantee (researcher covers async).
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git rev-parse/status/show actual m02 and s03 and root refs, direct source/surrounding tests. Produce feasible existing Windows GCC16/CMake/Wine and targeted CTest commands for later packages. No bringing up auxiliary services or claiming own tests.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No application edits or published issue, extra scope or approval loop. Recommend concrete principled tradeoff with verification where bounded/reversible. Immediate send first typed public seam as available. Two separate files cannot both own the same source; identify serialization points honestly.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User asks full implementation and delegates choices. Approve core first, task assignments and Gitea sends all root-owned, earlier design residence one cell/two height, upper worked excavation yields material through S06, no old-LAN new-mode projection.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-P2 PLAN with early affected-code ownership/interfaces, real file/symbol refs, dependency graph/failure cases, contract for scope-independent development, decisions needing F2/next verification.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Verify library support for voxel coordinates, chunks and surface picking
|
||||
|
||||
Task ID: M02-R1
|
||||
Role: astra_researcher
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Approved game roadmap, M02 follows M01 and calls for an editable finite voxel region with 32³ chunks, consistent coordinate/picking/navigation interpretation. No M02 code or branch started. Game root current 60154bd/aa4e271, Void exact CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792 confirmed equal upstream HEAD, source/tests available locally.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Prepare reusable API and missing-feature evidence so S02/S03/S17 can start under the user's Void-first dependency rule when M01 entry gates settle.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only M02-specific official/pinned API audit, exact target semantics and minimal verification/issue ideas. Not a game implementation, upstream write, or M02 completion claim.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/milestones/M02.md, systems/S02/S03/S17, prior void-library matrix and first_colony/world terrain/render picking, deterministic_rng.hpp. Pin clone /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src including CMake modules, include and tests. Inspect official library headers before claiming absent.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations to tracked/user data, Git/remote writes, public issue creation or children. Parent owns upstream tickets. Temporary isolated compilation probe in /tmp allowed if evidence is genuinely needed; no editing any shared build dir.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Determine exact public support for (1) signed 3D integer coordinates with correct floor division at negative boundaries, checked conversion, fixed-size contiguous chunk index and 6 neighbors; (2) deterministic seed/coordinate hashing and stateful portable random streams with fixed parameters and import/state or existing game RNG; (3) bounded sparse/finite chunk storage, generation version/edit delta/revisions; (4) grid DDA/voxel surface hit and path invalidation by touched chunk revision. Test/document any claimed coverage. Distinguish math primitives to use directly from game-specific policy and genuinely reusable missing capabilities. Check actual dev/test modules/adapters on Windows x64.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Return concrete interface names when present with source/tests at pin and what they guarantee. Root needs precise issue titles, reproducible inputs and replacement tests for actual generic gaps only; avoid a broad request to build the entire game in a shared library. Cover local coords at -1/0/31/32, extreme ranges, 3D axis convention and cross-chunk picking ties.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
M01 stable world ID/epoch/snapshot/checkpoint ownership upstream, future S02 data constructor and S17 ray picking consume that. No assumption M01 fully done; preparatory research only. Confirm whether upstream moved relative to pin via read-only ref if necessary.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Do not suggest library nondeterministic RNG for authoritative state when serialization/stream portability absent. Observe D3D renderer right-handed coordinate/picking constraints locally, storage limits and floating vs integer choices needed. Cite files, no private data outside approved repo/library.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate supported modules with test evidence vs missing subcontracts; 2. Bounded ownership and exact replacement tests for future implementation; 3. Identify native/other gaps and M02 code dependencies. 4. Relay first actionable library finding early.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git rev-parse HEAD and git -C <pin> rev-parse HEAD, targeted rg --files and rg -n on actual symbols and tests, project graph with coverage/direct reads for current app/World when relevant. Source /tmp/stoneheart-verify.KoZwE4o8/env.sh for any standalone Windows probe, no global changes.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not open remote tickets or implement new types; notify root with exact evidence. No speculation solely from CMake module names. No further agents.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User mandates Void support/issue linkage for real gaps; root authorizes this preparatory evidence in parallel with M01 work, without marking M02 started or complete.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-R1 VERIFIED/PARTIAL, pinned paths/API/test names, minimal concrete missing-feature cases and upstream lookup/filing suggestions, native/target limitations.
|
||||
|
||||
The Windows x64 probe passed under Wine 11 with GCC 16.2. Native Windows and MSVC remain unverified. Numeric, canonical little-endian Binary fields, FNV-1a, seeded raw Xoshiro output and graph traversal limits are available on this target. Each missing reusable operation has its consumer and replacement check in the [dependency matrix](../../plan/void-library.md#подготовка-воксельного-мира-m02). Upstream records cover [restorable random streams](https://git.faumaray.com/Void/Library/issues/10), [Euclidean division](https://git.faumaray.com/Void/Library/issues/11), [grid ray traversal](https://git.faumaray.com/Void/Library/issues/12), [revision dependencies](https://git.faumaray.com/Void/Library/issues/13) and [atomic sparse volume edits](https://git.faumaray.com/Void/Library/issues/14).
|
||||
@@ -0,0 +1,49 @@
|
||||
# Verify pinned support for logical chunk readiness and bounded persistence
|
||||
|
||||
Task ID: M02-R2
|
||||
Role: astra_researcher
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M02 now has actual S02 paged region and immutable prepared pages; S03/public nav and S17 ray consumers ongoing. M01 final raw15/checkpoint3 and FIFO files on Windows x64; logical activation must wait for all pages due at a logical tick while owner can still load/shutdown, keep old snapshot during I/O failure and discard obsolete work. Existing Void #5/#9/#13/#14/#15/#16 cover distinct earlier needs. Pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792 == upstream HEAD last verified.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Inspect real pinned published API/tests to distinguish directly reusable pieces vs genuinely missing generic scheduled work/barrier/storage capabilities. Check coverage for typed terrain rules representation and explicit seed/revision persistence only as relevant. Send concise concrete evidence and any issue candidate.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only official-source feasibility, registry matching + downstream consumer/replacement tests, no application edits or remote writes. No filesystem/network crawl, new Nix dependency, generic world design, or unrelated library issue filing.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read M02-R1/P1/F1, plan M02/S02/S15/S01/void-library; VoxelRegion::prepare_generated/prepare_restored/activate, SimulationRuntime loop/fault/load/worker options, CheckpointFiles/World save size caps, S21 observer semantically. Pinned exact library include and matching standalone tests for Async (FuturePool, TaskScope, tasks/operations), Binary Reader/Writer/Budget, file/storage/transaction and any actual stateful ordering/barrier module with name found. Gitea existing upstream issues3–16 can be read via authenticated tool or prior matrix; no secrets.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No working tree edits, Git mutations/remote comments, credentials or other project data, or switching shared Serena. Actual sibling git roots confirmed by parent; pinned isolated source direct. Independent of M02-P2 owner design.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Check exact semantics for bounded submissions (retained payload/full queue), completion wakeup without blocking actor/control loop, ordered barrier over required keys at logical step, supersession/cancellation/stale results, fault/recovery while preserving still-running work/ownership. Determine if directly using future readiness/TaskScope provides every contract; do not turn purely game-specific tick policy into an unnecessary library ticket. Check relevant real API source/tests and feasible Windows availability.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Return named actual modules/public methods and important limits, whether resources submit/update/cleanup fit M02 nonblocking owner. Consider if existing #5/#13/#14/#15/#16 already cover actual reusable subcontracts (reuse matching issue). For any distinct genuine gap, write narrowly scoped, library-general input/result, shutdown/late completion ordering and replacement test involving two prepared operations in opposite order and one obsolete generation. Include pinned source/test URLs or paths; no public posting.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root will use findings in M02 owner/codec/activation spec and file any genuinely missing issue before local integration. No approval of application code or code changes needed. Current prepared pages/region activation, historical raw15 /128MiB work as known consumers.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bounds such as largest 256 pages/4096 edits, seed/version deterministic rebuild, storage/sidecar optional vs existing saved file, Windows closed handle/decode budget, pool task holding old World on replacement/Shutdown. Prefer exact recorded behavior over guesswork; never read token configs or transmit private content outside configured repos.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. State directly composable pin-level facilities and tests. 2. Identify missing guarantee vs application-specific policy; map replacement tests/issues and avoid duplicate. 3. Record real native/cross limits and any unchecked uncertainty.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git -C <pin> rev-parse HEAD; rg --files/header+test direct evidence, root/subtree source check for current owner. Optional read-only official Gitea issue listing allowed. Temporary /tmp trial compile only if necessary for an uncertain important contract. No code snippets containing private user projects to third parties.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No speculative upstream issue or tests claimed unrun. Report early distinguishing existing primitive even when other details pending. Stop if exact pin missing and notify root with supported fallback.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User expressly mandates verifying VoidLibrary and filing missing reusable features in that project. Root handles all actual issue writes and links to local implementation. Paid services and installs outside scope.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-R2 VERIFIED/PARTIAL, actual APIs/source+test, genuine reusable gaps/issue candidates or existing records, exact downstream test for possible substitution.
|
||||
Pin `7b0fea6095f603f9e1904f66dfdc7752f4be4792` provides bounded `FuturePool::try_submit`, movable immutable inputs and exception-carrying futures. ThreadExecutor joins on destruction, and the game adapter may run overloads inline. The application therefore requires a separately owned bounded executor, true readiness notification or short readiness polling and application-level bounds on completed/obsolete pages. Existing Void issues 3, 5, 9, 13, 14, 15 and 16 were verified open; the due-tick rule uses the existing facilities. The reviewed Void Storage FilePort at this pin is POSIX-specific. No new standalone runs in this research packet.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Audit immutable terrain mutations and their navigation consumer
|
||||
|
||||
Task ID: M02-V1
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M02 foundation candidate 1ca481b in identical s02 and m02 worktrees, compared to 0d71bcf. M02-P1/F1 set signed32 coordinates/64bit endpoints, finite bounds/canonical generation, disjoint worktree ownership. S03 branch initially 6d1123e with incomplete implementation; review that only when final evidence announced. Actual S02 full 4/4 CTest, 155 core includes14 voxel,9 LAN,14 viewer plus real frame; checks in temp.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independent defect-oriented source review of completed section S02-01, then S03-01 and both combined after frozen. Send first S02 verdict as soon as possible. Root uses that sign-off and integration checks for real new branch/PR.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Coordinate math, generation, immutable lifetime and edit failure contracts, then separately path/query/cache invariants. No gameplay/codec/render implementation or approval of unchecked future M02 integration.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read actual include/settlement/core/voxel_region.hpp under engine/, engine/src/voxel_region.cpp, tests/voxel_region_tests.cpp, two CMake entries, S02 docs, S02-01 and M02-P1/F1. Review exact pinned Void Numeric/Binary/Hash APIs and #11/#14 if relevant. Once S03 is frozen, read voxel_navigation.hpp/cpp/test plus CMake/graph interfaces/region consumers and S03-01. Use direct sibling source; do not activate shared Serena. For Stage A m02 HEAD=1ca481b.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote effects or children. Parent and workers have exclusive separate WTs. Stage A must use actual committed code plus standalone allocation-probe source and logs, not just worker statements.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
For S02 trace equals/extremes, join/split INT_MIN/INT_MAX, checked half-open bounds and partial pages, stable index/neighbor overflow, deterministic seed encoding, generator consistency at seams and version, opaque candidate/provenance validation for multiple activation, immutable directory/const page/ref lifetimes, aliases from import retained data. All-or-nothing activate/edit for stale duplicate invalid/no-op/resident/revision/alloc failures with output arrays. Test transactional/caller-retained memory boundaries incl actual charged value vs std::vector capacity, incorrect estimates, dirty-face list canonical with boundary cells and unaffected pages. Evaluate actual failure-injection probe rather than counting a synthetic status.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Passability helpers must agree with mission: soil/stone support, DoorClosed blocks body, DoorOpen/Air permit clearance only, generator natural. Queries distinct outside/unavailable/air, stamps identity consistent at partial and extreme bounds, after activation previous unavailability stale. Request ordering should not alter same group revision/result. Multiple independent copies sharing original base can diverge; document expected caller/session/view assumptions and distinguish actionable bug from absent future feature.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Stage B only after linked S03 and complete worktree. Check actual Void BFS worklimits incl scratch allocations, bounded index dimensions, zero-length fast path legality, input/refusal/cancel/unknown, blocked/clearance reads incl passage and support from neighboring pages, exact path/interaction/cost, stable deterministic ties, affected negative invalidation vs edit in off-route region, safe next step. Actual two-floor scenario and interaction consumers belong to later packages.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reject overstated memory/benchmark claims, unsafe reference/worker lifetime or future worlds using stale pages after region handoff. Check wrapping revision/limit results with no dirty mutation. Compare actual content and live normal edge flows vs only invented tests. Later path results cannot authorize newer session, through walls or truncated search marketed as unreachable.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Stage A/B verdicts independently with actual refs, exact location, trigger, impact and fix/verification for each defect. 2. Affirm or refute saved earlier views/rejected edits/accurate neighbors, 1 vs 2/6/12 genuine tasks, branch evidence. 3. Stage B inspect real upper floor stairs/door/material semantics, limited and unavailable results plus missing/unchanged revisions. 4. Final integration verdict only when source/logs provided, report native target limitations.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git -C sibling show/diff --check and actual files, no builds. Inspect /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-{build-complete,ctest-complete}.log, s02-voxel-allocation-probe.cpp/s02-voxel-allocation.log, targeted info and S03 logs when supplied. Source-only facts separate from logged runs. Sibling paths outside verified root index, direct reads appropriate.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No approving the S03 implementation mid-flight. No fake workloads/claims or extra upstream issues without a genuine uncovered API. Send earliest actionable finding immediately. No source/branch/Serena/remote changes.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User supplied fully approved roadmap plus branches, Gitea and issue workflow. Reviewer role independent. Root owns all side effects and roadmap acceptance.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-V1 Stage A (and later B/combo) READY or CHANGES_REQUIRED with actual evidence and source refs. Include any untested platform/hardware behavior.
|
||||
|
||||
Stage A `1ca481b` passed component inspection. Combined region / current M01 source is `13dc673`; build and CTest evidence are in `m02-region-{build,ctest}.log`. The finished S03 component is `7a7ff32` on top of the actual linked S02 base. Inspect the new navigation header, implementation and tests with `s03-voxel-{build-final,focused-final,ctest}.log`. Stage A and B verdicts may be returned separately before the later combined navigation check.
|
||||
Corrective checkpoint: the two reported S03 defects are fixed at `17389b2`, and the integrated code plus all M01 corrections is `c40d9b2` in m02. Inspect the actual 7a7ff32..17389b2 source and tests, including proof of both old failures, possible/inconclusive reachable edges, all four max-size calls, and all combined status/geometry contracts. Evidence is in `s03-voxel-review-{before,final-focused,final-goals-ctest}.log` and `m02-foundation-{build,ctest}.log` when complete. Root requests an independent final Stage B and integrated foundation verdict; no review of future unpublished gameplay.
|
||||
Final interaction-window correction at `2017e56`, integrated with final M01 at `14987b2`. Reinspect actual 17389b2..2017e56 including omitted contacts, both missing and known exits and enclosed start, side effects on budgets/direct goals. Component proof and full results `s03-interaction-{before,after,after-build,after-ctest}.log`; combined build/CTest `m02-foundation-final-{build,ctest}.log`. Return final source and Stage B/combined signoff after logs.
|
||||
Final review accepted `1ca481b`, `2017e56` and their combined implementation `14987b2`. Logs contain both old failure classes and the clipped-contact regression before and after repair. All 14 focused navigation cases and all five integrated CTest targets pass under Wine. Native hardware and the future normal gameplay integration remain outstanding.
|
||||
@@ -0,0 +1,49 @@
|
||||
# Review bounded signed voxel meshing, D3D11 height slices and picking
|
||||
|
||||
Task ID: M02-V2
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Foundation S02/S03 accepted at 14987b2. Actual frozen S17 slice component 37a08d4 in s17-voxel vs 13dc673, and combined 129d7f2 in m02-render vs 14987b2. Normal S18 client hookup is subsequent and deliberately not claimed yet. Independent reviewer has not implemented this code.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Adversarial code/contract and recorded-test review of real WARP and CPU mesh/picking/retained packet. Provide quick actionable findings for any code or claimed evidence problem then verdict on component and combined.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S17 geometry/limits/session/readset, render/camera/pick agreement/surface and exceptions, D3D integration and regressions. Later gameplay/codec/S18 UI out of scope. Native physical hardware separate.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/{voxel_scene,d3d_scene_win32}.{hpp,cpp}, tests/voxel_scene_tests.cpp, CMakeLists.txt, docs/plan/systems/S17.md, S17-02 task, S02 navigable geometry/header, existing frame smoke/shader code. Exact sibling worktrees outside root graph; direct source and git diff/check. Never change shared Serena project.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No file/Git/remote mutations, commands for read-only inspection; no subagents. Root gathers actual runs. S17 worker completed implementation separately.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Trace projected coordinates vs shader (foot origin/local offset/z-up, signed extremes, camera fractional pan/zoom, cap distance and overflow); DDA direction/ties/zero component, missing/invisible paired open door, cut at inclusive slice and border of region. Check visibility of internal/edge faces, admission/culling budgets before allocations, stale/empty session and actual frame/pick consistent for held publication.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Retained immutable VoxelScene uses actual VoxelRegion directory and readstamps, preserve source data through newer edits. Mutable GPU resources must keep old prepared geometry working after failed preparation and avoid treating device mismatch as valid. Verify tested D3D11 WARP color readback vs mathematically chosen surfaces and real default frame path. Ensure terrain/unknown materials draw accurately with z-buffer and DDA at shared boundaries.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Compare original 13dc673 and 37a08d4; combined 129d7f2 includes corrected S03/current M01. Evidence resides /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-final-{build,ctest}.log and m02-render-integrated-{build,ctest}.log when complete. Void #12/#13 existing links and proposed replacement conditions; no extra novel gap absent evidence.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound read/face/vertex bytes, allocation failure, effective public camera/view dimension and signed-coordinate endpoints, ambiguous corners, overflow D3D limits, HRESULT lifecycle, capturing prior immutable GPU packet from another device, stable rendering while world or save busy. Discern correctness vs explicitly declared renderer limits/performance.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
Concrete trigger/ref/impact/correction plus before/after validation for any finding. 15 focused behavioral pixel/CPU cases and full 6-target CTest + new integrated code must match actual logs. Give verdict only for what was built, distinguish real WARP readback/visible legacy frame/physical Windows or untested GPU failure injection.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git show 37a08d4; git diff --check 13dc673..37a08d4 and 14987b2..129d7f2; inspect files and /tmp/stoneheart-milestones.xprJ2SVp/{s17-voxel-final,m02-render-integrated}-{build,ctest}.log. Component 6/6 in17.60s reported; verify independently. Full combined build still running; send initial findings independently.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No changes, credential or remote writes. No reliance solely on existing summary. No false approval for end-to-end editable game until S18/World integration. Send first defect early even if waiting on remaining logs.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized milestone/branches; only root commits/pushes/opens issues. This contract covers independent technical review, not external merge.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-V2 READY/CHANGES_REQUIRED per component and combined, exact source refs, concrete experiments, checked logs and platform limits.
|
||||
Independent review accepted the S17 component at `37a08d4` and joint renderer/region/navigation tree `129d7f2`. The rendering branch merge `f2ff1ce` has exactly the same tree as the reviewed component. The combined run passed all six CTest targets under Wine 11, including 15 voxel scene tests with real WARP pixel captures. Generated signed terrain contained 1,998 faces for 6,528 inspected cells. Separate work connects this API to the resident, preview, pointer controls and saved session.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Adopt the pinned Void executor and drain each simulation batch
|
||||
|
||||
Task ID: S01-02
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s01, system/s01-simulation at 8d2870a. Main working directory belongs to another task. Serial+replay passed at 8d2870a. Precise M01-R/R2 upstream pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. M01-F2 approved below failure tests.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Replace the homegrown WorkerPool thread/queue implementation with pinned Void::Async::ThreadExecutor + FuturePool. Preserve existing World parallel and serial outcomes, guarantee lifetime of all admitted batch tasks across exceptions, and demonstrate useful-work/latency effects.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Scope S01 executor migration only. No UI, scheduler, S15 persistence or gameplay redesign. Keep public submit(std callable)->std::future<Result> and thread_count() compatibility where useful; small game-specific pressure/fault seams allowed for real observations.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect engine/include/settlement/core/worker_pool.hpp, engine/src/{worker_pool,world}.cpp three submissions, engine/include/settlement/core/world.hpp, tests/replay_tests.cpp, benchmarks/colony.cpp, docs/plan/void-library.md. Upstream headers and tests pinned in /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/src/world_save.cpp; tests/replay_tests.cpp; engine/include/settlement/core/worker_pool.hpp; engine/src/worker_pool.cpp; engine/src/world.cpp; engine/include/settlement/core/world.hpp; tests/executor_tests.cpp; CMakeLists.txt
|
||||
Not alone. All writes only to named branch/worktree using explicit workdir or absolute paths. Other systems have separate checkouts, root merges CMake. No change of shared Serena project, Git commits or branch switches.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use Void::Async::ThreadExecutor::create/start and FuturePool::try_submit. Preserve original count>=2 for legacy pool and zero pool in serial. Choose explicit non-dropping policy for overloaded work (e.g. synchronous invoke/future of untouched callable); stopped/error distinguishable. Use per-batch lifetime guard or equivalent that waits ALL accepted work before locals unwind for later submit/first-future exception, reserve storage before submissions. Keep stable result order, avoid extra tasks in serial and stop/join exactly once. Verify startup/queue exceptions against actual API, zero duplicate result. The public Async usage requirements must reach consumers whose headers include Void. Only add module Async and necessary transitive closure.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Existing worker adapter remains game-owned translator of Void contract. NEW test fault/pressure settings should be minimal, e.g. create worker with capacity 1 and a start hook; preserve ordinary defaults. Determine actual original exception type/semantics and deterministic error behavior. Reject waiting on the same worker's own execution. Provide runner-exercised integration proof for World using migrated adapter.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns authoritative runtime and remote issue filings; use supported pinned executor, no new generic thread pool. Initial core/replay state 33 core +4 LAN. New tests are in existing core suite and tagged executor. Compile in your own system worktree.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Required failures: capacity saturation with retained move-only callable, propagation of callable exception, start failing after a thread already launched, destroyed pool drains admitted work, capture lifetime survives later admission/future exceptions. Avoid polling sleeps in concurrency tests; use promises/latches/barriers with bounded waits. No OS-specific perf assertions.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. All old and replay tests pass. 2. Fault/pressure/drain tests prove no lost work or surviving task at unwind, including world/batch paths. 3. Small/larger existing colony benchmark runs with a fixed seed compare before/after completed work and timings, clearly labeled Wine (historical native times only contextual). 4. Include any observed regression or residual failure boundary; preserve old path as historical baseline.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/executor-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Select --tag executor and --tag replay under Wine. Use 50/500 residents 6 workers with existing benchmark.exe for measured comparisons against /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_colony_benchmark.exe; report work and 32 warmup/240 measured if used.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if pin backend cannot build or semantics contradict contract, report distinguishing probe. After two failed repair cycles send both results to root. No unauthorized remote actions, shared checkout edits or child agents.
|
||||
|
||||
Additional integration check approved by root: append defaulted WorkerPoolOptions to read_save, forward to the constructed world, and exercise the existing command/reload fixture under capacity one (tests/replay_tests.cpp). Preserve original replay coverage and the save format.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved full plan and branch-per-system development. Strong implementation owner assigned for high-risk cross-thread failure/critical path. Root integrates and pushes after review.
|
||||
|
||||
## 14. Return format
|
||||
Return S01-02 status, actual API/files, failure semantics and lifecycle checks, build/test and benchmark results with commands and baseline, residual risks and integration implications.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Capture immutable world state at a completed simulation boundary
|
||||
|
||||
Task ID: S01-03
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01, system/s01-simulation at 68f91a2, verified S01-02. World owns complete data, execution mode/pool/caches; WorldSaveCodec reads and validates that data. M01-P2/F3 and upstream Void/Library #5 cover immutable caller-built snapshots.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide NEW World::capture() const -> std::shared_ptr<const World> for const renderer/serializer/snapshot users. Held snapshots preserve all observable data after subsequent live mutations, or when live World is destroyed.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
World snapshot representation and focused tests, no coordinator, UI, checkpoint, rules or generic atomic snapshot mirror. No byte roundtrip/allocation of a worker during capture. Capture must be called by owner at finished command/tick barrier.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp, world_save.cpp, worker_pool.*, tests/{replay,executor,core}_tests.cpp, benchmarks/colony.cpp. Identify all persistent fields, visible counters, worker and transient cache state, const views and nested paths/inventory containers.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; tests/snapshot_tests.cpp; CMakeLists.txt; docs/plan/systems/S01.md
|
||||
No editing other worktrees, Git or Serena state. You are not alone and other agents own runtime, rules, persistence, dispatch. Preserve S01-02 exactly apart from necessary representation changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Group copyable logical World data in a single copyable representation such that future gameplay fields naturally join one copy. Keep executor, worker callbacks and cache out of captures (cache independent of future behavior; if a read-only getter exposes hit or path counters, preserve its observed value). Preserve source worker_count() reporting where practical, and forbid mutable snapshot access by type. Favor private or internal state and simple direct World access; no hand-maintained second serializer, dozens of copy assignments or per-capture thread starts. Reuse existing WorldSaveCodec public behavior. Validate current construction/layout/implicit move caller compatibility.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW public std::shared_ptr<const World> World::capture() const. Propagate normal allocation failures to the owner, source remains untouched, no mutation or pointer aliases to source vectors/agents. Existing factories, modes and format13 unchanged. Include upstream #5 link plus replacement criterion where publication is discussed.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root will plug capture into single-owner publication, sampled under one owner, snapshots can cross renderer/I/O/threads. This feature can compile from 68f91a2 without S16 or S19. No alternate restore API unless natural and actually required.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Snapshot retains owned nested inventories/routes/reservations, current pause, workshop, hidden sequence/revision/counters and profiling data needed by reads. Capture while a task is running is outside caller contract. Pools/hooks not allocated/retained by read-only view. Test held snapshot can be read on a worker while source advances without using sleeps as ordering controls. Bound benchmark scope to actually measured World/runs.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. compare canonical bytes immediately and after source changes/destruction incl mid-carry fixture; assert stable views/counters/pause. 2. Capture+serialize on actual const read path; callback ownership released with live world even if snapshot lives. 3. Cover 2/6 and serial or existing replay tests for legacy behavior. 4. Measure capture cost at 50/500 residents in x64 Wine and report exactly what was measured, no native claim.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/capture-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <build>/settlement_core_tests.exe --tag snapshot, git diff --check; evidence including benchmark protocol and measurements. Separate output files from S01-02 logs.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not alter formats, owner scheduling or save/LAN fixtures. No unrequested generic server/runtime framework. Stop if renderer has mutating access disguised as const or impossible copy semantics. Escalate after two failed repairs of the same defect.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Parent owns all commits and pushes. User approved roadmap; planner/preflight accepted independent copies at owner barrier. This is the first S01 immutable-publication component.
|
||||
|
||||
## 14. Return format
|
||||
Return S01-03 READY/BLOCKED, exact API/files, fields/cache/executor boundary, actual tests/counts, measurements, limitations and contact on any compatibility risk. No children.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Run the single-owner simulation clock and publish committed snapshots
|
||||
|
||||
Task ID: S01-04
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive s01 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 fast-forwarded to 2224299. Actual S01::World::capture, S16 CommandDispatcher+SessionIdentity and S15 WorldCheckpoint + rules exist in this tree; S01/S19/S15/S16 reviews M01-V3/V4/V5. M01-F3 defines fault, epoch, capacity, and load fencing. Pin 7b0fea6 provides Time::MonotonicClock/SystemMonotonicClock/ManualClock, Uuid::try_v4, Async executor. Public library snapshot gap https://git.faumaray.com/Void/Library/issues/5.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Build NEW SimulationRuntime, sole mutable World owner on a background worker, 20 Hz at normal speed and real immutable publications. Provide a usable asynchronous adapter for commands, save capture and load replacement before later viewer integration.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Core scheduler, snapshot, bounded commands, validated installs, compatibility with existing serial/parallel World, tests/docs. UI, LAN packet codec, file dialogs, disk decoding/reading, stable-ID internals and content selection UI have other owners. Keep standalone old World entry points compatible.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual engine/include/settlement/core/{world,command_dispatcher,checkpoint,save_service,rules_manifest}.hpp + implementations, app/viewer_win32.cpp timer/menu/pause/command placement, M01-F3 and relevant systems, pinned Void/Time/Clock.hpp, Void/Core/Uuid.hpp and Void/Async. Use stage barrier capture() exactly as documented.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/simulation_runtime.hpp; engine/src/simulation_runtime.cpp; tests/runtime_tests.cpp; CMakeLists.txt; docs/plan/systems/S01.md
|
||||
Do not change any other worktree, Git refs, existing command/save interfaces or shared Serena activation. You are not alone; other workers own viewer, library and custody concerns.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Single mutable owner, initial validated WorldCheckpoint (already contains stable world_id, city, rules) or explicit initial equivalent. Generate ephemeral session UUID for each start/install, including rollback of the same stable world. One stable PublishedSnapshot (identity/tick/publication revision, shared_ptr<const World>, shared immutable RulesManifest, command request metadata as needed). publish prepared snapshot/ledger results only after complete tick or command. Reader snapshot retrieval never waits for a tick or disk work. On any active tick/command/preparation exception: retain previous publication, drop/disable partial working world and uncommitted ledger, make observable Faulted, complete queued futures predictably, retain old exact committed receipt lookup. Ordinary domain rejection and failed install/file validation leave healthy owner alive. Keep owner responsive to queued work while paused, external presentation suspend independent from in-game pause. Target fixed logical 50 ms steps using pinned MonotonicClock; process elapsed debt deterministically bounded per pass, no starvation or time skipping; re-anchor on suspend/paused/resume so idle time cannot burst into gameplay. Provide manual-clock wake/test barrier so tests avoid arbitrary sleeps. Publish revision changes even for accepted commands at equal tick. Use atomic or short critical sections, no locks around World::step/capture, I/O or joining. Efficient ledger staging: avoid copying the ledger on each tick or replay. Unexpected post-effect failures never return success.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Expose a bounded try_submit(TrustedClient, CommandEnvelope) + future/typed result with immediate admission outcomes and safe always-completed accepted requests. Allow viewer to allocate correct contiguous per-client IDs (normal local queue/order and retries). Provide trusted read-only snapshot for UI and a coherent capture_for_save that checks health at its linearization point. Expose begin_load()/install(ticket, independently validated WorldCheckpoint) or equivalent with latest requested serial and expected active epoch, rechecked immediately before publication incl concurrent newer load during preparation. Failed/superseded install keeps current publication/owner/ledger. Honor F3 even if faulted and guarantee recovery by a valid newest load. A fresh epoch discards old command history and fences stale commands/errors. Provide a simple clock notification or deterministic owner fence for tests. Communicate frozen signatures early to root; UI/transport packages depend on them.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns CMake integration, app adapters, Gitea and current ports. Runtime must be usable from Win32 WM_TIMER to poll latest view and command futures while rendering. Prefer existing Void supported primitive for generic work/time (standard condition-variable/synchronization where appropriate). Service writer owns disk background; use capture API without calling writer on the owner thread. Link #5 + replacement criterion in docs. Default config limits consistent with existing M01 subsystems.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Stress lifecycle races: complete all accepted work on shutdown with normal/Closed/Faulted status, no borrowed tasks after World destruction, success never races visibility. New accepted work has deterministic FIFO/admission and explicit capacity; ensure load recovery possible after fault, old work only commits in old session. Faulted current view still valid for read-only rendering. UUID/allocation failures during load leave old state unchanged. Document shared snapshot ownership memory tradeoff. Test reads return previous stable view while deliberately blocked tick is running. Determine nonfatal invalid inputs before owner mutation.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Under manual time, exactly 20 ticks per second (or observe per step) with same canonical data as direct reference. Commands can pause/unpause while no ticks progress, same-tick publications update. 2. Two clients exact repeats, old session after rollback, altered payload, load supersession, capacity and orderly shutdown. 3. Inject stage failure / after command mutation / snapshot preparation, verify last publication and committed receipts survive, no fresh mutation/save silently succeeds, queue futures all settle, valid load recovers cleanly. 4. Gate real long tick and show a UI reader and immutable save capture return previous completed state. 5. Whole x64 Wine suite passes, no native claim.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/runtime-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <build>/settlement_core_tests.exe --tag runtime, full verbose CTest, git diff --check. Name logs runtime-* under /tmp/stoneheart-milestones.xprJ2SVp. Communicate before schedule/contract changes.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No external services, branches/commits/push, children or template frameworks. Stop if a shared API makes F3 impossible. Two failed fixes for same problem -> distinguish failure and escalate to parent for re-diagnosis. No scheduling behavior on UI or disk paths.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes whole roadmap, separate system branches and PRs. Planner/preflight M01-F3 and reviewed implementations freeze the conditions. Root decides integration and release separately.
|
||||
|
||||
## 14. Return format
|
||||
Return S01-04 status, early exact public header/contract for viewer, concrete timing/fault/install/ID outcomes, files, actual compile/tests/counts, open native or integration limitations. No subagents.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Implement immutable finite voxel regions and atomic multi-chunk edits
|
||||
|
||||
Task ID: S02-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Actual isolated system/s02-voxel-world at 0d71bcf, parent milestone/m02-voxel-world. M02-P1 plan and F1 independently accepted first slice. Existing first colony WorldState copied on capture and flat terrain remains, renderer z-up. Cross-toolchain CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. Void Math::Numeric checked arithmetic, Binary::Writer and Hash public, signed split/atomic pages absent and tracked upstream #11/#14. M01 final custody in isolated siblings, no overlapping source needed.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Build a tested, ready-to-integrate finite authoritative voxel region with deterministic versioned terrain, signed coords and immutable chunk pages, checked all-or-nothing multi-page edits and accurate surface invalidation. The first file consumers are S03 nav queries, S17 surfaces and M02 World/serializer/activation. Freeze a usable header early and send actual declarations to root.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only memory representation, generation, prepared page installation, querying and edits for the finite one-region M02 foundation. No unrelated RNG, terrain viewer, WorldState or format edits, S03 path solver, resource ledger, gameplay or network. Input/outcome types below are NEW and may be named idiomatically.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M02.md, systems/S02 + S03, dependency matrix section M02 + actual pin headers/tests for Math/Numeric, Binary and Hash. Inspect world.hpp/world.cpp capture, default 2D semantics, actual 3D shader at app/d3d_scene_win32.cpp, CMake targets and registered Void::Testing suites. S06 / S15 provisional custody data unneeded. Read M02-P1/F1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: NEW engine/include/settlement/core/voxel_region.hpp; NEW engine/src/voxel_region.cpp; NEW tests/voxel_region_tests.cpp; CMakeLists.txt only two source/test entries; docs/plan/systems/S02.md
|
||||
Your isolated s02 checkout only. Others work in separate WTs, do not overwrite or revert their changes. No Git/remote operations, shared Serena switch, children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Define checked nonzero uint64 RegionId, int32 xyz with z-up, int64 half-open endpoints verifying within [INT32_MIN,INT32_MAX+1], strictly positive volume per axis (finite coordinate bounds need not densely allocate), chunk/local split no -INT_MIN, x-fast 32³ index. Stable material identifiers air/soil/stone, configurable bounded resident pages (default256), edit count (default4096), and actual checked staging/result/directory sizes (default allow full bounded batch). Region copies or dedicated immutable views share complete directory/pages via const ownership; no retained mutable aliases or mutable raw span. Immutable generator candidate is keyed by metadata/coords, source initialized independent of job ordering, deterministic generator1 with plausible soil surface/stone below and canonical absolute-coordinate encoding via actual Void Binary/Hash, uses no shared RNG. Mask all cells outside partial region.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Ordinary query distinguishes outside bounds vs unavailable vs loaded air; returns stable coordinate/read stamp matching caller lifetime. Separate pure generation/preparation from explicit all-or-nothing publication so later M02 owner controls logical tick. Region may not install result from a different region/seed/generator/coordinate or expired expectation. Keep page/availability paths usable by future persistence. A bounded atomic edit requires exact revision expectations for each touched chunk (including no-op), rejects duplicate cells, unsupported material/coords/bad expectations before publishing. Empty/all-identical edit has no changes. Sort changed cells/pages and actual neighbor invalidations canonically; increment once per truly changed page, unchanged neighbors keep material stamp, loading must be observable by dependencies. Extreme revision denies change before first effect. No need for unload until a later consumer, if implemented prevent ABA with persistent stamp. Define what finite bounds/unavailable neighbor contributes to dirty key.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Host only builds Windows; unit checks linked in actual settlement_core_tests. Root merges S02 into M02 and cumulative only after review. Need write stable header before dependent S03/S17 and alert parent if implementation materially changes contract. Other workers own old World/codec/camera, never edit those. Local implementation explicitly references Void/Library #11/#14 in S02 docs with exact replacement tests.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Widen origins, local indexes and neighbor math before conversion; avoid INT overflow/padding/endian and unbounded directory/grid construction. Bound working + staging memory before allocations and reject insufficient limits unchanged. Stage all pages and result list before final nonthrowing swap; preserve original content/pointer/revision on bad batch, allocation failure and MAX counter. External retained snapshots own memory separately, state its limit precisely. Prefer compact materials and deterministic column generation; full active 256 pages must not cause unrelated pages to be recopied on each edit. No nondeterministic unordered serialization or generation.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Exact split/join and x-fast indices at INT_MIN,−33,−32,−1,0,31,32,INT_MAX incl [max,max+1) and partial negative/extreme bounds. 2. Canonical full material content and revisions independent of forward/reverse/parallel preparation, real neighboring signed coordinate continuity/golden seed, precise different availability/air. 3. Two-page edit succeeds atomically and old view unchanged; stale second/unloaded/duplicate/unknown/budget/MAX fail unchanged, unchanged writes validate expectation and do not increment; correct face vs edge neighbor invalidation across boundaries. 4. No additional unlinked generic shim outside #11/#14; real release compilation and focused/full CTest, report actual footprint/copy behavior and evidence. 5. Document useful public operations in S02 and share frozen header.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run --tag voxel-region at your build, complete CTest -V (coordinate any real windows via root) and git diff --check; logs /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-*.log. Native Windows beyond cross tests not verified. Test revision exhaustion via meaningful persistence/import or narrow deterministic seam without exposing an unchecked arbitrary setter.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not silently expand M02 to full renderer/World or change prior save formats. If dependency contract missing, verify pin plus check existing issues, report exact consumer/guarantee and root handles any filing. Two unsuccessful same-cause fixes escalate with original contract/evidence. No publishing or other checkout edits.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system coding, Gitea PRs and true Void gaps. Root chose region identity and finite signed z-up cells, M02 product decisions in milestone doc; planner/preflight complete for this slice. Concrete bounded storage/container choices delegated.
|
||||
|
||||
## 14. Return format
|
||||
Return S02-01 READY or PARTIAL, early frozen API and relevant coordinate/frame assumptions, controlled failure cases, working paths, actual verification counts/measurements/limits and remaining integration seams.
|
||||
|
||||
The M02 door uses two stable non-generated cell kinds, `MaterialId::DoorClosed` and `MaterialId::DoorOpen`, appended after Air, Soil and Stone. A closed door blocks body clearance; an open door and air permit clearance. Only Soil and Stone provide standing support. Publish NEW `voxel_blocks_passage(MaterialId)` and `voxel_provides_support(MaterialId)` queries for the navigation and presentation owners. Both halves of a door can be changed in the same checked edit batch. Invalid materials remain rejected. The generator produces natural materials only, and the gameplay owner controls who may operate or mine a door. Add tests for these shared semantics, both updating over a page boundary if applicable, and tell root when the adjusted header is frozen. This prevents a second source of door geometry, occupancy and invalidation in navigation.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Find and revalidate settler routes across editable voxel chunks
|
||||
|
||||
Task ID: S03-01
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Actual isolated system/s03-navigation worktree at 6d1123e has frozen region API voxel_region.hpp, S02 implementation/registration arriving from sibling before testing. M02-P1/F1 reviewed source/algorithm limits; M01 flat assignment_path keys are two-dimensional and World::step advances without revalidation. S03 is disjoint from existing World and S02 implementation. Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 supplies IndexedGraphView/bfs/shortest_path_unweighted WorkLimits. Generic consulted revision sets absent, already tracked #13.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement tested bounded 3D ordinary-settler path query, interaction positions, consulted effective chunk revisions and transition revalidation. Ready for the authorized M02 World movement/mining owner to consume; send actual frozen public API early.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only new voxel navigation module, real standalone tests, CMake entries and S03 docs. Use shared S02 data; leave old flat A*, World/serializer/actual HWND/drawing to their assigned M02 consumers. No new navmesh, multi-region streaming, liquids/animals or future profiles. Do not copy any unfinished S02 source.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M02.md, systems/S02/S03, void-library.md and M02-P1/F1/S02-01; frozen engine/include/settlement/core/voxel_region.hpp at6d1123e, root engine/src/world.cpp assignment_path/advance, headers command_dispatcher.hpp::SessionIdentity (UUID epoch), CMake/tests. Official pinned Void/Algorithms/Graph.hpp plus tests in pinned tree, see real limits, edges, start==target early success.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/voxel_navigation.hpp; engine/src/voxel_navigation.cpp; tests/voxel_navigation_tests.cpp; CMakeLists.txt; docs/plan/systems/S03.md
|
||||
First three paths are new. In CMake add only your source, test and, if needed, a link to the already enabled Void::Algorithms target.
|
||||
Other people work in separate WTs; never overwrite/revert their work, never change shared Serena project. No Git/remote ops, children, edits to S02 files, existing World or M01.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Represent foot at one voxel, two vertical cells clear, support directly below. 4 horizontal cardinal neighbors with level/one-step up/down, no unsupported pure flight or diagonal wall/corner clipping. Evaluate the swept body under up/down (needed headroom over raised/descending transition). Reuse S02 voxel_blocks_passage/voxel_provides_support and stamps; DoorOpen+air passable, DoorClosed blocked; soil/stone support only. A stair flight is a sequence of supported steps. Provide single-hop validation and standing check from same queries as solver, and separate API for adjacent accessible task interactions (range/line of contact cannot mine through wall/above unreachable geometric separation).
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW request/result includes region and session/incarnation from existing actual UUID type, bounded search volume/goals (deterministic ties), route/current to goal route semantics documented, cost, failure reason, sorted deduplicated consulted chunk stamps incl support/head/blocked/unavailable neighbours, and stale check via Region.matches + owner session. An unrelated edit must preserve result. Opening previously unavailable gateway invalidates negative result, same ID and numeric revisions after world reload still require new session. Distinguish invalid inputs, truly unreachable, unavailable/awaiting activation, boundary/budget and cancellation errors. Small finite known search uses Void::Algorithms::bfs or shortest_path on bounded IndexedGraphView; respect start==goal check before library fast path. For multi-goal choose canonical shortest (distance then stable coordinate and neighbor order); restrict result to reachable interaction positions. Do not allocate full coordinate extent on sparse huge region. Check vertex count, edges/step/aggregate scratch, size_t/int64 computations and bound read-set. Non-exhaustive clipping/budget must not masquerade as proven unreachable.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Parent gives compiled S02 implementation and test registration via local merge after worktree is sealed when ready. Can compile your TUs against header first; no mock replaces genuine final evidence. Future M02 authority, persistence, frame/picking will use foot positions/goal and read stamps. Protocol11/legacy file unaffected. Local revision set #13 to be linked with its exact replacement tests in S03.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Include INT extremes/partial bounds/overflow, headroom at source+destination, missing vertical support in a different page, start==same blocked target, path/missing pages and time/epoch; cannot mutate captured VoxelRegion. Keep memory bounded by explicit realistic work limits; e.g. 256*32³ cells must not allocate 136MiB per worker to traverse a four-cell corridor. Check allocation failure/too many input goals gracefully. Avoid per-node heap allocations for bounded neighbor enumeration where appropriate. No hiding application bugs in arbitrary timeout/different path cost.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Real S02 volume route through two-cell open door and cross-chunk stair to upper interaction; closed door/headwall/no support block and reason. 2. Remove next future support while traveler still safe, route/stamps stale, next-hop rejects; reopen, route returns; unrelated chunk change preserves validation; unavailable-to-loaded negative becomes stale; new session stale. 3. Stable exact cost/goal/tie path on small fixtures vs independent exhaustive reference + multiple worker schedules, direct same-goal invalid case. 4. Explicit bounded-limit behavior before dense allocation/partial proof, integer extremes and deterministic sorted queried stamps. 5. Real cross-build/full tests with S02 and docs issue linkage.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s03-navigation-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. After link run --tag voxel-navigation, full ctest -V and git diff --check with /tmp/stoneheart-milestones.xprJ2SVp/s03-voxel-*.log. Native Windows unavailable. Before full interactive CTest contact root to avoid simultaneous keyboard-driven smoke test.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No invented S02 or Void API; if integration contract insufficient, send precise new dependency to root and continue self-contained cases. No alternate user workflow, new external tickets, or duplicate library pathfinder. Two unsuccessful same-cause attempts escalate. No remote or children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested all milestone/system coding, actual upstream library gaps and per-branch MRs. M02 architecture accepted ordinary one-cell-wide/two-tall profile, one step max; root handles publishing.
|
||||
|
||||
## 14. Return format
|
||||
Return S03-01 READY or PARTIAL, early stable interface for M02 owner, actual code/test limits, work bounds and cross-branch evidence including cross-boundary route/invalidation and distinct failure outcomes.
|
||||
|
||||
Review at `7a7ff32` found a confirmed negative-result bug. On a solid, loaded z=0 floor a downward candidate may sample an unloaded z=-1 support while the known solid destination foot conclusively forbids the transition. A two-high closed wall then appears to be waiting for unrelated activation. Retain the actual sampled stamps but classify missing data as a potential frontier only if the corresponding transition, standing goal or reachable continuation cannot already be ruled out. Add the walled-floor regression and a positive genuinely unavailable frontier. Check analogous search-boundary handling and real interaction targets. Keep the existing signature and scoped files.
|
||||
Independent interaction clipping finding at `17389b2`: a known blocked list of in-window contacts does not prove a global negative when additional valid interaction candidates lie outside the finite window and the reached search frontier can leave it. Reproduce in a flat 8×8×4 fixture, start (1,1,1), search upper.x=4, target stone (3,3,1), blockers (2,3,2), (3,2,2), (3,4,2) and (3,3,3). With a reachable contact at (4,3,1) the narrow search returns SearchBoundary; upper.x=6 must reach it. Preserve all prior fixed direct-goal and unknown-frontier contracts. Include cases without any traversable exit and with an unavailable exit, freeze actual before/after code and run 13 previous focused cases, new regression and full CTest under the shared GUI lock.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Persist production order identities and allocate complete command batches atomically
|
||||
|
||||
Task ID: S04-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s04 system/s04-jobs-reservations base 4ba64f7. WorldState includes capture, S06 durable storage/node refs. S15 envelope v1 accepts raw World v1–13. M01-P3/V9 identified all insertion and refusal paths including storage demolition replenishment and LegacyCabinPayload in S16. Upstream durable allocator #7.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Give every production order a persistent World-scoped ID, remove stored positional production references, preserve identity history in modern checkpoints while keeping original saves/wire exact, and make all order-allocating business commands reject exhaustion without partial effects.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Production identity, high-water mark, ABI/caller migration, modern raw/envelope generation and validated v1 import. Keep zero none, leave new stack/ownership/transfer records and broad economy behavior to later slices. Preserve historical default formatting/encoding and v11 public network.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp all insertion/erase/use sites and missing_carpentry_orders, world_save.cpp body/validate, checkpoint.cpp/.hpp/checkpoint_files.cpp, command_dispatcher.cpp catches LegacyCabinPayload, viewer resident detail, existing tests and old baselines. F3/F5, M01-P3/V9. Inspect/preserve exact pinned Void Numeric/Binary/Crypto and prior deterministic corpus.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; engine/src/command_dispatcher.cpp (only legacy cabin exhausted outcome); app/viewer_win32.cpp (resident production details only); tests/core_tests.cpp; tests/identity_tests.cpp; tests/replay_tests.cpp; tests/production_identity_tests.cpp (NEW); tests/checkpoint_tests.cpp; tests/checkpoint_file_tests.cpp; tests/session_tests.cpp; CMakeLists.txt; docs/plan/systems/S04.md
|
||||
Only touch listed affected tests/callers as needed. Other owners touch UI, files, profiles elsewhere. You are not alone; root integrates branches. Do not edit other worktrees/Git/Serena.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Add real ProductionId, immutable order identity, WorldState::next_production_id_, Agent::production_id (0 absent), bounded sorted lookup, erase without index repair. Centralize all order insertion incl queue_production and both direct PlaceRoom loops. Calculate exact whole ID requirement and incrementable successors before any command/domain side effect. Single and multi-order (bed, loom, workshop, rooms/furnishings, direct cabin and implicit replenishments) precheck numeric exhaustion as well as vector allocation. MAX terminal valid, last allocatable MAX-1. Calculate EXACT post-demolition missing carpentry counts across products/requirements WITHOUT erasing/mutating storage first, reserve all IDs before deleting stock or appending any order. If full batch cannot fit return nonmutating Busy with exact old storage/stock/sequence and counters. For LegacyCabinPayload use explicit testable pre-mutation exhaustion result/exception, narrowly translate THIS proven refusal to completed Busy in CommandDispatcher::apply, retain exact repeat while session remains healthy. Do not catch a generic error that could follow partial mutation. Other unexpected errors use F3 fault boundary. Avoid duplicated independent registries.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Default World::write_save(std::ostream&) still emits exact v13 bytes and historical positional links, old callers incl LAN11 unchanged. Add explicit modern World write mode v14 (new actual enum or method) using same codec/body, include stable refs / order IDs/high-water; now World::read_save handles appropriately. Checkpoint encode becomes schema2/modern body14. Decode authentic schema1/inner1–13 and schema2/inner14 only, verify signature & checksum using common codec, latest high-water after deleting last/highest/all survives. Historical import assigns IDs deterministically in vector order with next > live max; no new UUID on modern reload. Validate sorted unique nonzero ProductionIds, strictly larger next (MAX valid), referenced target existence/state before indexing. Keep envelope magic unchanged. Old file-adapter test hardcodes unsupported next value 2: change to actually unsupported value and retain a true pre-change v1 fixture, not just changing expected bytes. Tell root exact frozen API early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns final merge. S18 worker also touches UI but not resident-detail lookup; S19 profiles separate. File reader matches same signature and uses generic decode; ensure outer/inner pairing tests even when attacker recalculates both checksums. Registry consumers continue using const World. Use existing checked arithmetic; local implementation+replacement link Void/Library #7 in docs and allocation source where useful.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Avoid O(N²) repeated scans of million-record parsed data; legacy index projection/import bounded as in S06. Active resident must keep same original order when lower deleted. All domain normal refusal keeps previous capacity/contents/command seq; last accepted identifier remains unaffected by vector erasure, world capture or save. Ensure no different command arbitration/legacy behavior on ordinary non-exhaustion. Preserve legal old v1–v13 payload behavior. Do not overwrite any user save.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Deleting lower/highest/all orders followed by v2 reload + allocating another never reuses IDs, actual mid-haul agent remains bound; corrupt ID/dangling/current combinations rejected. 2. MAX/MAX-1 single and multi batch incl room/cabin/stock demolition with multiple products, verify byte-identical complete current state/unchanged seq after Busy, and exact replayed cabin Busy with healthy runtime. 3. Authentic checkpoint v1 lower inner and v13 accepted, wrong pairing incl v1/14, v2/13 rejected with valid checksums. 4. Per-tick MODERN canonical replay including ID state across serial/2/6/12, old default v13/legacy benchmark data compare exact. 5. All cross suites pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/production-id-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag production-id, full verbose CTest, git diff --check; fixed binary compatibility corpora at /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin, baseline 4ba64f7 artifacts. Save logs production-id-*. No synthetic recreation of a golden old checkpoint with the new encoder.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No broad rewrite or custom replacement for supported Void primitives, branch changes or further agents. If existing unknown pre/post mutation exception means a Busy lie, stop and send contract+counterexample. After two failed repairs raise distinct hypothesis with evidence.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system features, commits/push and merge requests. M01-V9 requested exact demolition and cabin corrections; parent obtains narrow preflight recheck before dispatch. Root owns all side effects.
|
||||
|
||||
## 14. Return format
|
||||
Return S04-01 READY/BLOCKED, public format and ID APIs, actual coverage of all allocation sites, clean failure outcomes, compatibility corpora hashes/tests, and remaining later custody/native risks. No children/commits/push.
|
||||
|
||||
The middle-of-delivery assertion in `tests/snapshot_tests.cpp` also reads the removed production index. The implementer owns its equivalent check of the stored nonzero production ID.
|
||||
@@ -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 <that dir> --parallel 6, run ctest --test-dir <that 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.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Resolve stored logistics references by stable storage and resource IDs
|
||||
|
||||
Task ID: S06-01
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s06, system/s06-logistics begins a4cf99c. M01-P3 mapped World+codec+UI references, M01-V6 requires checked exhaustion for all storage/node allocation paths. Actual WorldState groups the complete capture; modern v1 checkpoint embeds format13; legacy tests 1–13/LAN11.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Migrate live Agent::resource_node_index and storage_index, MaterialReservation::storage_index and ConstructionStop::storage_index to the selected objects' existing nonzero IDs. Deleting an earlier unrelated element must preserve all targets and quantities. Cover restoration and ID exhaustion.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S06-01 storage/resource references and checked allocation at all existing sites. Production index and next agent/job/production counters have their own later contract, stack/reservation/transfer identity comes later. Preserve deliberately confirmed stock demolition behavior. No public new network protocol, geometry, checkpoint schema or UI feature.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp, world_save.cpp, first_colony.cpp, viewer_win32.cpp resident detail, graphics/callers including benchmarks, core/replay/snapshot/checkpoint tests. Read S06/S04, M01-P3/V6, pin Math/Numeric.hpp checked_add and Core/Counted.hpp. Use stable-vector ordering validated by WorldSaveCodec. Verify existing API users by rg.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; app/viewer_win32.cpp (existing resident-detail reference access only); tests/core_tests.cpp; tests/snapshot_tests.cpp; tests/replay_tests.cpp; tests/checkpoint_tests.cpp; tests/identity_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S06.md
|
||||
Other code owners operate in isolated branches. You are not alone; do not revert others or change Git/shared Serena. Modify existing tests only for changed ref semantics, not to weaken checks.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use zero as missing typed ResourceNodeId/StorageId, remove positional fixups for these members everywhere. Expose read-only bounded ID lookup and reuse ID-ordered lower_bound or equivalent. Keep indices ephemeral inside assignment and validation count arrays. Encode ID→old positional one-based/sentinel fields exactly; decode raw positions in explicitly bounded loader temporaries then convert to IDs after referenced arrays are populated and order validated, before world domain validation/use. Reject out-of-range/missing ID before indexing. Keep production_index/no_entity_index independent. Preserve ordering, deterministic routes and complete old wire bytes. Write source comments with linked replacement test for Void/Library #7.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
ID exhaustion: UINT64_MAX in next_* is a legitimate terminal high-water mark, last allocatable ID is MAX-1. Precompute checked successor with pinned Void::Numeric::checked_add before world/vector/terrain effects in World::add_resource_node, World::add_storage AND direct Place{BerryField,TreePlot,FlaxField,Mine} and PlaceStorage command paths. Only commit counter after successful construction/insertion. No returning zero, wraparound or duplicate IDs. Direct factory exhaustion raises std::overflow_error, commands return non-mutating Busy without consuming legacy sequence. For MAX-1 exactly one insertion then a stable serialized exhausted world. Validate invalid refs and preserve existing stronger invariants/canonical old bytes.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns CMake merge, dependent runtime/GUI packages, Git and upstream. Void/Library #7 covers restorable checked sequences; #8 is later custody, pinned Void Numeric handles arithmetic now. Preserve current std::unique_ptr<World> factories/mode, Render const path, standalone tests. No compatibility alias which silently restores use of vector indices.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Mid-carry before/after erasing earlier store/node, pantry meal, site tending with no storage, construction multi-stop delivery, carpenter output reservation, active targets remain protected by existing rules. Guard lookup for none/dangling, sorted IDs and caches. Ensure fast logarithmic lookups; avoid O(N²) scans or per-agent linear scans during codec, no duplicate durable map to synchronize. Check max vs max-1 inputs, failed insertions and byte-level determinism. Use pre-migration external baseline or saved corpus to verify exact bytes when gameplay equivalent.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Live references preserve meaning after erasing an earlier unrelated store/node; no shifted refs remain in runtime. 2. Capture, legacy save13, checkpoint roundtrip and serial/2/6/12 trajectories agree mid-haul. 3. MAX/MAX-1 at every allocation path, including mine blocked-cell/cache on rejection. 4. Damaged legacy indices reject candidate, no partial live mutation. 5. All tests/cross build pass incl baseline, focused identity tests and project docs.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/identity-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag identity, verbose CTest, git diff --check. Cross-baseline compare relevant old outputs; root shares /tmp/stoneheart-milestones.xprJ2SVp/trajectory.cpp & old-trajectory.bin. Report actual bytes/scenarios and time if performance measured.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No side effects outside checkout/build/log temp. Stop if current wire cannot represent migrating these existing IDs without loss, or a supported caller needs out-of-scope change, or after two failed repairs of the same issue. Do not silently drop malformed/legacy data.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system implementation, upstream issues, commits and PRs. M01-P3 proposed slice and M01-V6 preflight correction is incorporated here; root confirms narrow corrective re-review before dispatch.
|
||||
|
||||
## 14. Return format
|
||||
Return S06-01 status, actual files/lookup and legacy conversion boundaries, overflow/Busy semantics, commands/counts, cross-baseline byte evidence, remaining limitations. No children/commits/push.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Apply a complete reserved pickup to one resident atomically
|
||||
|
||||
Task ID: S06-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated system/s06-logistics worktree s06 at a8cd7bb (S04 ProductionId/current14, S19 selectable rules, S06 stable StorageId). Meals and construction stops call take_reserved_material then Inventory::add, and a carpentry output reserves a new storage slot at its first ingredient pickup. Earlier M01-P5/F7 require whole-stop preflight. Existing finish_production also calls take_reserved_material for direct storage→recipe consumption, a different operation.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement checked all-or-nothing physical pickup in both real meal and construction stop paths, including a carpentry output slot when applicable. Retain normal simulation bytes/timing. Cover overflows, split duplicate material entries and late failure before mutation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
No save version, StackId, worksite ownership, reservation ID, journal, general-purpose database or protocol change in this slice. Keep existing direct recipe consumption in finish_production. Stage only future work in appropriate system notes.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read engine/include/settlement/core/world.hpp Inventory/Storage/ItemStack/MaterialReservation, engine/src/world.cpp named consumers, world_save.cpp validation/legacy split records, tests identity/production_identity/core/replay, and S06 documentation/linked Void #8. Consult pin include/Void/Math/Numeric.hpp checked_add/sub. Root baseline cumulative a8cd7bb.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/src/world.cpp (narrow meal/construction stop pickup and related local helper); NEW engine/include/settlement/core/inventory_transaction.hpp and engine/src/inventory_transaction.cpp if needed for a shared testable operation; NEW tests/quantity_transaction_tests.cpp; CMakeLists.txt only source and test entries; docs/plan/systems/S06.md
|
||||
Exclusive to your isolated s06 worktree. Others work in sibling worktrees. Do not revert others' changes or edit unrelated methods/world_save/UI or shared Serena state. Root owns Git and remote.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use one bounded operation over a single Storage and resident Inventory, evaluating present source/reserved counts, aggregate duplicate participating lines per type, and checked destination increments. If using the whole order span, choose only lines at the current storage; a missing/zero/invalid selection fails. Reject invalid types/None, zero amount, overflows, insufficient reserved or count and reserved>physical. Preserve source stack order, prune zero stacks without allocation; prevent throws between first and last logical writes. Use the existing checked Numeric API. For carpentry precompute reserved_slots successor and ensure post-withdrawal total_items+reserved_slots<=capacity before any quantity write; move commit/route/cursor only after success. No per-line mutating call before complete preflight. Failures observed by the owner must preserve last healthy publication. Avoid needless repeated lookup/allocations.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Prefer one simple domain function returning std::expected<void,typed quantity diagnostic>; exact type and header naming locally flexible. Application entry precondition is pickup-function entry: World::step may already advance walking position/route_cursor earlier in the tick. On pickup rejection, no additional stop, inventory, reserved slots/stock, route replacement or state transition; never publish partial transfer. Cover zero/foreign-only or out-of-range data; existing legitimate repeated material entries aggregate. Raw13/LAN11 layout stays byte exact and modern Current14 shape stays the same.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns merging this branch to milestone/integration and cross-branch checks. P5 future durable IDs and reservations will consume this operation. S04-01 and S19-02 are already present; S18 UI can proceed independently.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Data bounds as provided by old loader; max distinct types item_type_count, avoid allocating proportional to a user-provided count. Do not wrap at uint32 max on destination, source/slot arithmetic or sum. Source storage count/metadata may be inconsistent on direct test input; fail safely. No total mutable parallel ledger. Minimize impact on World::step hot path.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source/dest byte-equivalent on success for valid meal and multi-material/multistop/carpentry paths, tested from production code. 2. A two-item stop late failure plus cumulative duplicate and destination overflow leaves all stock/reserved/capacity/inventory unchanged. 3. Successful exact depletion removes zero stack, respects source order and reserve slot. 4. Replay serial/2/6/12 modern checks and both old byte corpora unchanged. 5. Document limits separately from future custody and link Void #8 replacement.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/quantity-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Use --tag quantity-transfer on new tests, CTest -V, git diff --check; /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin old golden outputs were checked by s04 (portable projection probe sources in same directory). Keep verification logs quantity-* in that temp root.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not fake output inventories for finish_production or weaken legacy validity, add unrelated changes or use unbounded copies. Alert root if actual code contradicts the contract. Root owns commit/push/MRs/upstream issues. After two failed same-cause repairs escalate; no children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Approved M01 item conservation and per-system development. F7 corrective terms are included above. Conditional batch issue Void/Library #8 already registered; parent owns external tracking.
|
||||
|
||||
## 14. Return format
|
||||
Return S06-02 READY or PARTIAL, owned files, exact tradeoffs/failure boundary, actual tests/golden output, any native and deferred full-custody limitations. No Git/remote operations.
|
||||
|
||||
F7 corrections are binding. Item indices are checked against 1..item_type_count before using type−1. Aggregate nonadjacent duplicate lines, handle an absent stack, and preserve the original first material's storage as the output source even when it is visited after another stop. No stale iterators may survive zero-stack removal. Include valid exact UINT32_MAX destination count, multiple erasures with unrelated surviving stacks, full storage freeing exactly one carpentry output slot, invalid slot/capacity state rejected before physical transfer, and direct storage→output production compatibility.
|
||||
@@ -0,0 +1,50 @@
|
||||
# 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 <that dir> --parallel 6, run ctest --test-dir <that 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
|
||||
|
||||
After local candidate `4f4c038`, S15 observed that a retained admission can be authenticated with repeated reservation IDs, even though the allocator always issues distinct increasing IDs. Inspect canonical emitters and reject repeated issued reservation IDs or demonstrably duplicate identical effect rows, including after the referenced actor/stack has retired. S15 adds authentic malformed fixtures in its own files. Verify genuine consumed-through-zero and valid split/merge results continue to pass. Use the same exclusive scope, tests, and Gitea restrictions.
|
||||
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.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Publish immutable save requests asynchronously on Windows
|
||||
|
||||
Task ID: S15-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s15 system/s15-persistence, baseline 8d2870a. Root and other authors use different checkouts. S15-W02, M01-P2/F3, Void pin 7b0fea6. Root created https://git.faumaray.com/Void/Library/issues/3 for unsupported Windows replace_file.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a bounded FIFO background Windows save service, with atomic same-volume publication of immutable request content and meaningful failure outcomes. Provide API/test surface for viewer and later checkpoint framing.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Own independent S15 file service only. No UI/World/serialization format change. Input is a snapshot-owning producer (or shared immutable bytes) with tick, epoch and request identity; synchronous existing save helper remains until owner integration.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/viewer_win32.cpp::save_world_file, current save codec, docs/plan/systems/S15.md. In exact pin inspect Void/System/Path.hpp (ReplaceFailure, unsupported Windows), Void/Async/{ThreadExecutor,FuturePool}.hpp for a single writer and bounded admission. Existing env and library checkout are in /tmp/stoneheart-verify.KoZwE4o8.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/save_service.hpp; engine/src/save_service_win32.cpp; tests/save_service_tests.cpp; CMakeLists.txt
|
||||
You are not alone. Use explicit workdir/absolute paths only in specified worktree; others own independent systems. Root handles CMake merges/Git. Do not edit main or change shared Serena project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Give each accepted save a monotonic request identity, captured tick and session UUID (reuse Void::Uuid::Uuid or consistent fixed bytes). Materialize from immutable producer on writer thread or allow shared immutable bytes, further integration must keep snapshot acquisition cheap. Bound queue including in-flight and return Busy/Closed before ownership side effects. One FIFO writer ensures older accepted saves cannot replace newer same-slot requests. Use pinned Void Async where suitable. Worker completes all accepted requests on shutdown. A failed producer/write must deliver completion and next FIFO task continues.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Publish to a unique same-directory staging file created exclusively, write all bytes incl embedded NUL, handle short/error or close failure, explicitly FlushFileBuffers, atomically rename with replacement on the same volume; preserve previous slot on any prepublication failure, remove only owned staging files and distinguish postpublication visible/durability-unknown. First create, Unicode paths, sharing errors. Keep application-crash observations separate from power-loss guarantees. Local adapter + replacement criterion and upstream #3 link. Deterministic fault injection at phases for test; do not broaden external access. Communicate API early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S01 runtime later captures immutable snapshot/manifests, S15 checkpoint codec constructs bytes, UI will enqueue this service and poll completion. No dependency on unfinished runtime/system branch. CMake public types require actual transitive includes for callers.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Serialize FIFO submission ordering even if concurrent callers; expose or check order via returned IDs. No blocking UI submission, no mutex held waiting for disk/producer or while joining. Same-directory sibling preserved on failures. Use isolated temporary directory for tests, never overwrite user files. Reject missing parent/closed service; documents should make overwrite/new behavior clear.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Unicode path succeeds on create/replace while readers see full contents. 2. Prepublication failures preserve old bytes, temp cleaned, postpublication failure truthful. 3. Slow earlier/newer order on a single slot, bounds, shutdown drain, producer exception followed by next success verified. 4. Tests establish immutable snapshot life & UI caller progress without sleep-only assertions; tag save-slot and run under Wine.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/save-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Tests use new empty temp dirs, Windows/Wine results labelled. Collect native limitations. Provide specific replacement test for Void #3.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if Windows primitive cannot meet claimed contract or tests prove a different outcome. After two failed repairs escalate with artifacts. No external writes, further agents, branch operations, admin actions or out-of-scope edits.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved entire roadmap and per-system development with commits/push from root. F3 accepted FIFO ordering and failure semantics. Upstream issue already exists.
|
||||
|
||||
## 14. Return format
|
||||
Return S15-01 status, exact API/files, failure/visibility semantics, commands/counts, native verification still needed and integration notes. No subagents.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Encode and validate versioned world checkpoints with frozen rules
|
||||
|
||||
Task ID: S15-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/checkpoint, detached de38aff (reviewed S19 rules + M01 replay). Parent integrates this into system/s15-persistence. Legacy World::write_save/read_save and their validations implement formats 1–13. default_rules_manifest resolves two real built-ins. Pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a bounded modern checkpoint codec admitting a stable world UUID, city identity and a verified rules manifest together with the existing canonical world state. Produce a complete validated candidate without touching live state.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Game-specific envelope, built-in installed-catalog API only if needed, tests. SaveService, asynchronous requests, session/epoch assignment, UI, new custody fields, scripting are independent packages. Existing default format13 encoding and LAN11 fixtures must still pass.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect engine/include/settlement/core/{world,rules_manifest}.hpp, engine/src/{world_save,rules_manifest}.cpp, tests/{rules,core,replay}_tests.cpp, CMakeLists.txt, docs/plan/systems/{S15,S19}.md. Inspect pinned Void/Binary, Crypto SHA256, Core Uuid public types/tests.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; tests/checkpoint_tests.cpp; CMakeLists.txt; engine/include/settlement/core/rules_manifest.hpp; engine/src/rules_manifest.cpp
|
||||
Use last two only for extracting the actual built-in catalog behind existing default_rules_manifest. Others own writers, S01/S16 and separate checkouts. You are not alone, do not revert others or change Serena/Git.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Define NEW encode_checkpoint(const World&, stable world UUID, nonzero city, const RulesManifest&) and decode_checkpoint(bytes, installed RulePackage catalog, workers/mode), or equivalent precisely typed API. Use distinct magic+schema, little endian Void Binary, SHA-256 integrity over all meaningful header+payload bytes. Persist complete selected closure with each sorted stable ID, exact version, content digest and compare recomputed manifest from installed catalog, naming missing/changed package. Serialize core once with existing World codec. Verify bounded lengths/counts and outer integrity before domain/world allocations. Reject extra bytes, unsupported version, nil identity/zero city, metadata mismatch incl tick if stored, missing/extra/conflicting rules. Candidate returns unique World, identity, matching immutable manifest. No on-disk active session/ledger. Report simple actionable diagnostics while preserving ownership; do not make persistence a signature/authentication.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Use Void::Uuid::Uuid for world, uint64 city, RulesManifest and RulePackage directly. Add public installed builtin_rule_packages() returning expected catalog if needed, reuse in default_rules_manifest. Keep compiled-in fixture contents identical. Frozen rules independent of current active world. Allow later versioned state for new custody data without breaking old fixture. Match preexisting 128 MiB body cap plus separately bounded metadata before buffering. Communicate actual API early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
No dependency on writer or runtime; immutable capture later calls encode in background, validated decoded world goes to runtime replacement. No new framework/dependency or external issue is needed for game framing using supported primitives; report a genuine missing generic capability to root.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Adversarial truncations, length overflow, malformed counts/input, duplicate packages, package digest/version/build mismatch, corrupted canonical body with recomputed outer checksum, lossless old bytes, world/identity/city survival. Decode allocates only from bounded data; respect existing output failure behaviors. Reading legacy file remains via World::read_save.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Round-trip a live and mid-carry world, compare full canonical world bytes and continued ticks. 2. Selecting alternate installed packages round-trips and validates against a catalog in different order. 3. Corruption, incompatible/uninstalled rules, bad UUID/city, lengths/trailing data fail with usable diagnostics while original world is untouched. 4. Old save13 & LAN11 and all existing suites pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/checkpoint-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <build>/settlement_core_tests.exe --tag checkpoint and git diff --check. Check commands from YOUR worktree.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No changes to shared checkouts or external services. Stop on ambiguous destructive format migration or incompatible real library semantics. Escalate after two failed repairs of the same defect.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Parent owns Git. User approved milestones/systems, commits/push; plans M01, M01-F3 cover independent validation before any owner replacement. Parent will review actual diff.
|
||||
|
||||
## 14. Return format
|
||||
Return S15-02 READY/BLOCKED, exact API, owned files, frame and limits, test results incl counts, residual limitations and later runtime integration. No subagents.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Prepare checkpoint files in the background for the interactive client
|
||||
|
||||
Task ID: S15-03
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive s15 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s15 system/s15-persistence fast-forwarded to 8c4c1fe. Includes verified runtime PublishedSnapshot, S15 checkpoint and SaveService + builtins. M01-F4 accepted bounded background file adapter; #3 is the linked Windows atomic-write contract.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Supply a usable persistence adapter for the real window: submit save of a held PublishedSnapshot, prepare a modern or legacy file asynchronously into a complete WorldCheckpoint; no disk or parsing on UI/owner thread.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S15 file API/implementation and test/docs/target integration. Viewer itself and its load-ticket/feedback lifecycle are owned separately. Existing SaveService handles writes; existing World/checkpoint codecs handle validation.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual simulation_runtime.hpp (PublishedSnapshot immutable), checkpoint.hpp/.cpp, save_service.hpp/.cpp, rules_manifest.hpp/.cpp, world_save.cpp signature/limits/validation, viewer current dialog/select and file handling. Review Void Async ThreadExecutor/FuturePool lifetime/admission tests and pinned Windows IO coverage. M01-V6 requires max_checkpoint_bytes.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/checkpoint_files.hpp; engine/src/checkpoint_files.cpp; tests/checkpoint_file_tests.cpp; CMakeLists.txt; docs/plan/systems/S15.md; engine/include/settlement/core/checkpoint.hpp and engine/src/checkpoint.cpp only if needed to expose canonical signature recognition
|
||||
No changes to other worktrees/Git/Serena/Win32 UI. You are not alone; other workers own runtime, LAN, UI, World/custody. Parent integrates CMake.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Introduce NEW CheckpointFiles owning one existing SaveService configured max_checkpoint_bytes and a bounded pinned Void reader executor/FuturePool. try_save(absolute path, shared_ptr<const PublishedSnapshot>) delegates to existing queue, producer owns const world/manifest and runs encode_checkpoint on writer. Caller acquired healthy snapshot already. try_load(absolute path,... immutable installed catalog, workers/mode) returns immediately with explicit admission and accepted future/typed diagnostic or complete candidate. Provide useful error for file access, limits, legacy decode, missing package etc. For modern signature call decode_checkpoint only, never downgrade after a modern failure. For legacy signature parse validated World::read_save and attach fresh stable nonnil UUID, city1, default supported manifest. Preserve exact prior old v1–13 paths; don't invent a mutable live session. Open each path once, enforce maximum read incl growth/EOF before consuming unbounded storage. Reader/writer can run independently; hold input/catalog through work, drain on shutdown.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Communicate exact header early. Constructor may own shared immutable installed catalog (default builtins) to simplify caller. Caller keeps this service for window lifetime across runtime resets; jobs never capture viewer/raw runtime or call GUI. Return SaveSubmission or precise adapter result preserving prior SaveService metadata. Reader producer can use an optional bounded observer/gate for deterministic tests following existing failure hooks if needed. No thread per file; explicit bounds & stable closed admission. Busy or invalid admission does not consume caller data. Viewer handles begin_load tickets/replacement policy, reporting and 32×32 restriction.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root wires UI later, receives filled result and verifies dimensions before SimulationRuntime::try_install; runtime itself rechecks epoch/ticket. Old valid file import gets a fresh stable ID on each explicit import. Default `.settlement` existing extension and title paths maintained. Store upstream #3 link where relevant; pinned Void supports asynchronous running and file codecs as documented. No external actions.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check Unicode filesystem path, open-one/read-one with changing files, oversized declared/actual data (bound including growth), corruption/trailing/truncation distinctly, catalog mismatch names missing package, nil UUID generator error, concurrent submit/shutdown/read queue/in-flight count, writer retains held snapshot after source advances. Avoid throwing from worker leaving pending futures. No double-opening for format detection, no fallback rewriting files. Track native/Wine differences.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Roundtrip actual immutable old snapshot through production save helper to file then load to independent candidate; live world progresses meanwhile. 2. Open true legacy fixtures and modern mismatches; invalid/oversized/trailing/frame corruption rejects. 3. Bounded and closed reader, deterministic held reader blocking test shows UI submit and writes/other work independent, shutdown drains, next read succeeds after bad file. 4. Normal cross build and old suites pass. 5. Frozen interface is usable for viewer async polls without lifetime hazards.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/file-adapter-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag checkpoint-file, full verbose CTest, git diff --check; files in new temporary Windows directories. Name logs file-adapter-*.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No editing viewer/custody, raw live World access from workers, remotely written actions or new external deps. If architecture requires a new generic capability report it to root. Two failed fixes for the same issue require escalation.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root owns all Git; user approved roadmap and asked maintain PR/cumulative/issue tracking. F3/F4 and V6 freeze acceptance; Windows physical tests follow separately.
|
||||
|
||||
## 14. Return format
|
||||
Return S15-03 READY/BLOCKED, early concrete signatures for viewer, owned paths, complete tests/observations and limitations. No children/commits/push.
|
||||
@@ -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 <that dir> --parallel 6, run ctest --test-dir <that 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.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Dispatch authenticated session commands with exact retry outcomes
|
||||
|
||||
Task ID: S16-01
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16 system/s16-authority, 8d2870a. Main checkout is a different task. F2/F3 and M01-P2 approve this scope; pinned Void 7b0fea6, upstream gap https://git.faumaray.com/Void/Library/issues/6.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement S16-W01 game command admission/dispatch in a single-owner component plus integration tests with two trusted client handles. Expose a frozen interface for S01 runtime and modern transport.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S16 dispatcher only, no sockets/UI/clock or save format. Preserve legacy World::apply_command behavior and LAN11 decoding for existing callers.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp World::next_command_sequence/apply_command and queue_cabin, app/lan_wire.cpp, tests/core_tests.cpp, docs/plan/systems/S16.md. Void/Core/Uuid.hpp at exact pin supplies nonnil identities/try_v4; source stubs/compile headers from known library checkout.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/command_dispatcher.hpp; engine/src/command_dispatcher.cpp; tests/session_tests.cpp; CMakeLists.txt
|
||||
You are not alone. All writes only to specified worktree with explicit absolute paths/workdir. Root integrates branches and CMake; no switching shared Serena, changing others' files, committing/pushing or spawning.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use one host dispatcher per world/session and one shared city for M01 (plus disallowed city test). Authenticate caller via trusted local connection slot passed separately, never trust payload player. Envelope includes version, nonnil world+session UUID, city, uint64 request id, game action fields. Per trusted client require contiguous monotonic numbers from 1. Session/identity/version and trusted slot validated before any cached response. For full payload and city equal to an existing key, replay original outcome; reject ID reuse with a changed payload (compare all fields) without mutation. Persist accepted and completed rejected results within session until replaced. Global or per-client configurable capacity: Busy before NEW requests at capacity; honor all previously admitted receipts, no eviction/reexecution. Stale/out-of-order/busy transient errors don't consume request; completed domain rejections do. Store or reserve result before applying effect. Do not silently drop prior receipts on exceptions; runtime will retire faulted owner and session before more commands.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW CommandEnvelope/CommandPayload, session identity (using Void::Uuid::Uuid or fixed byte-compatible game type), target city and explicit outcomes incl status, assigned tick and revision; trusted player is supplied to dispatcher, not a payload identity. Map payload to PlayerCommand using World::next_command_sequence after auth, with no change to legacy sequences on rejection. Provide bounded acceptance path for legacy queue_cabin when needed by viewer (new owner command, preserve checked prerequisite and return outcome) or report exact adaptation to root. New command and session types should be usable without event loop. Share exact API with root early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Consumers S01 runtime, S15 checkpoint and modern transport. Worker owns CMake additions in isolated branch; link Void::Core PUBLIC only if publicly required. Reference #6 in companion task + local source/milestone decision with replacement check. No extra generic ledger.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check nonnil IDs, invalid/unsupported action, sequence zero, overflow, two clients same request numbers, different payload/city, old world/session, accepted and failed duplicates even after later requests, capacity and exception-safe reservation. Old rejection corrected under a new envelope ID must still use correct World sequence. No hidden trust from bytes.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Two clients converge and repeat accepted/rejected commands without reapplication, including after newer requests. 2. Stale after rollback and wrong city/identity rejected with identical world bytes. 3. Changed payload, exhaustion, unsupported version/order bounded and tested. 4. Legacy and new tests build/run using actual World. Header communicates semantics to runtime.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/session-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Tag new tests session, including positive effects and exact repeat receipt tick/revision. Report performance bounds by inspection.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Escalate required cross-branch changes, genuine ambiguity or two failed repairs; use direct source in this worktree instead of querying the main graph as if it were the same checkout. No external actions.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized full roadmap and branches/commits/push; root owns remote actions. F3 READY for S16 dispatcher under above semantics.
|
||||
|
||||
## 14. Return format
|
||||
Return S16-01 status, actual files and public interface early, semantics/complexity, test and build counts, gaps, runtime integration notes. No subagents.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Serve compatible LAN clients from the immutable authoritative runtime
|
||||
|
||||
Task ID: S16-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16, system/s16-authority fast-forwarded to 8c4c1fe. Existing LanSession::poll(World&) protocol11 is tested (4 cases/baseline binary interop). Runtime and command dispatcher new headers exist. M01-F4 identified manifest and outstanding-command reconnect gates, included below.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Add production host polling that consumes immutable runtime views and submits authenticated guest actions to the owner asynchronously. Add guest-only polling usable by a view-only client, preserve current hardcoded two slots and old packet format.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Legacy LAN11 compatibility adapter and actual loopback tests. No public new protocol/version or remote rollout, no new internet exposure. Preserve existing poll(World&) entry/fixtures for old API clients. Viewer source is owned separately.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/lan_session.hpp, app/lan_session_win32.cpp, app/lan_wire.hpp/.cpp, tests/lan_tests.cpp, simulation_runtime.hpp, command_dispatcher.hpp, world.hpp, rules_manifest.hpp, docs/plan/systems/S16.md. Read /tmp/stoneheart-verify.KoZwE4o8/interop.cpp/.py for existing binary interop.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/lan_session.hpp; app/lan_session_win32.cpp; tests/lan_tests.cpp; docs/plan/systems/S16.md
|
||||
If an identified shared codec change is necessary, contact root first; no data layout redesign. Other workers own Win32 viewer/core. You are not alone, do not change Git/Serena/other worktrees.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
NEW poll_host(SimulationRuntime&) and poll_guest() (or equally explicit) for real viewer. Wire11 Hello carries no manifest/epoch, so allow ONLY default compatibility manifest (verified frozen identity); close incompatible connection before exposing a snapshot/command. Bind host session incarnation; detecting replacement drops peer & requires new hello before serving new world. Existing TCP framing/auth and slot validation retained. Read current immutable published World and prepare v13 snapshots with current bounds. No direct mutation in new host path. Screen sends one action at a time; bound hostile/pipelined volume, keep pings/timeouts/disconnect progress, never wait on a long owner while polling socket. Serialize one outstanding valid command per authenticated guest slot.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Wire request IDs are legacy World::next_command_sequence(guest), only accepted gameplay increments them. Modern envelope number from committed PublishedSnapshot::next_requests[guest] also advances on domain rejection. Precheck wire sequence without mutating state; old wrong-sequence -> expected number. Submit trusted guest=2, verified UUIDs/world/city/version, exact payload; report the correct legacy result and next wire sequence only from corresponding committed runtime result. Reject unsupported actions using existing authority. Track one outstanding admitted operation across TCP disconnect/rebind; suppress old-connection replies by connection generation, hold/reconcile its completion before next guest's sequence or authentication/publication is used, prevent reusing in-flight modern request number. On epoch change fence old future before new peer bind. No borrowed runtime pointer persisted. Expose status to viewer on incompatible rules/fault. Send early public signatures.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns actual Win32 viewer integration. Runtime consumers now available at baseline; old standalone overload remains tested. Add only in-process loopback tests using random port/loopback flag. Reuse existing socket implementation and avoid duplicate dispatch/snapshot logic. Legacy reader file/body remains format13 and lower limits; world with unsupported future schema must be rejected explicitly in later change.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
On Busy/Closed/Faulted/superseded/out-of-order preserve protocol-correct old next id and prevent lost reported effects. Guest can correct a rejected action using same old number. Do not retain retired peer's optimistic blueprint metadata. Check long owner tick does not block server pings/poll; settled work from old peer cannot reply to a new one. Enforce bounded admission and no logs of join codes. Test a publication at same tick.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Old-style genuine guest joins runtime-owned host and receives actual committed world; user action, domain rejection and corrected next command preserve legacy sequences. 2. Deliberately blocked/delayed command, disconnect/reconnect, no old receipt to new peer, sequential guest slot safely resumes. 3. New epoch and non-default manifest refuse or reauthenticate before any legacy snapshot. 4. Both existing LAN11 fixtures and old API work; deterministic cross-version loopback including old guest executable. 5. Real x64 tests and warning status.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_lan_tests.exe --tag lan (or registered runtime LAN tag plus full target), verbose CTest, git diff --check. Logs lan-owner-*. Root can stage external original-binary harness if needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No changes to socket reachability, authentication standards, new transport, UI or unrelated game state. Two failed fixes for the same defect -> send evidence and changed hypothesis to root. No children/Git/remote mutations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved milestone/system work, commits/PRs/accumulation. M01-F3/F4 require authenticated owner entry and preserved old-wire rules. Root handles final integration.
|
||||
|
||||
## 14. Return format
|
||||
Return S16-02 status, early exact caller entry points, peer/session tracking contracts, actual test evidence/counts/interop and any native limitations.
|
||||
|
||||
The client also needs positive acknowledgements to remove committed draft parts. The approved preferred guest interface exposes `take_result()` with the full accepted or rejected intent, including resident ID. Retain one completion until the preferred caller drains it, clear stale results across connection generations and preserve legacy `take_rejection()` behavior. The loopback cases cover accepted and rejected results.
|
||||
@@ -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 <that dir> --parallel 6, run ctest --test-dir <that 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.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Linearize legacy guest command admission with authoritative publication
|
||||
|
||||
Task ID: S16-04
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Independent review M01-V15 found a real race in S16-03 at c183de1 in s16 worktree. app/lan_session_win32.cpp current_runtime_snapshot takes a healthy compatible immutable snapshot, then handle_runtime_host later calls unconditional SimulationRuntime::try_submit. Runtime::enqueue under its mutex only checks closing/capacity; a host cancellation can publish an unrepresentable world in the same epoch between those operations. Work already queued before cutoff must still settle. Earlier old/current compatibility and partial buffered data tests unrelated to this gap passed.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Enforce atomic conditional admission against the exact compatible publication already inspected by protocol11; verify a deterministically forced check→concurrent publish→enqueue race using the real owner/host/socket. Keep old clients functional on compatible newer snapshots, and no secret fallback to the legacy path.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Limited change to S16 adapter, smallest general runtime admission seam and targeted regression/doc. No protocol layout change, global gameplay trust/authority changes, or duplicate compatibility logic under network ownership.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect engine/include/settlement/core/simulation_runtime.hpp, engine/src/simulation_runtime.cpp enqueue/publish/fault/try_submit, app/lan_session_win32.cpp + lan_session.hpp poll/handle_runtime_host/reply/drop, tests/lan_tests.cpp plus tests/runtime_tests.cpp existing gates, docs/plan/systems/{S01,S16}.md. Read M01-V15 and S16-03 and actual earlier logs in temp.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/simulation_runtime.hpp; engine/src/simulation_runtime.cpp; app/lan_session_win32.cpp; app/lan_session.hpp if essential for a small test seam; tests/lan_tests.cpp; docs/plan/systems/S16.md. S21 owns runtime_tests.cpp in a sibling; keep your specific regression in lan_tests. No shared changes/remote, Git writes, children or shared Serena switching.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Add narrowly named conditional admission to normal runtime queue (suggest try_submit_if_current, explicit checked snapshot). Under exactly the mutex serializing published/state and queue insertion, before effects, require RuntimeState::Running and match non-null expected retained shared publication (identity pointer or version+incarnation with equal semantics). Leave existing unconditional local API unchanged. Ensure lock contention/capacity Busy is distinct in outcome/handling from a changed publication, e.g. explicit mismatch result or documented guard outcome; no read outside mutex can certify admission. Do not recompute/copy the whole World in the lock. Never revalidate/revoke work already admitted before publication.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
LAN adapter passes checked published snapshot capability with outgoing command. On mismatch re-evaluate latest state: incompatible/faulted/session replacement clears peer/buffers and never enqueues stale envelope; healthy same-session changed revision must retain old protocol sequence/ack, e.g. legitimate Busy and old-client retry or bounded retry with current snapshot, not disconnect all guests every tick. Invalid/fault/capacity must not emit receipt for an unadmitted command as Accepted. Distinguish handshakes/queue flush; prior external bytes already sent cannot be recalled.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Real S04 cancel from host and custody S06/S15 already in s16. Root also integrating S21/S18 tests. Use test hook at narrow point after checking snapshot and before runtime enqueue, or equivalent genuine scheduling barrier. Avoid new permanent per-frame overhead unrelated to this path. If testing hook is needed, prefer existing configured seams or narrow optional sterile observer rather than global test-only code in normal library that changes semantics.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Protect repeated remote sessions/idempotency and stale same-epoch publication across canonical cancellation. Guards must not coerce nullptr into unconditional admission, ABA impossible with retained shared_ptr and immutable identity. Publication faults and shutdown must obey existing semantics. Do not busy-loop when current world is advancing. Old/queued command with exact accepted availability must complete on healthy owner even if the state changes afterwards.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Deterministic two-thread/real-loopback test holds remote operation after capturing representable S, publishes same-epoch unrepresentable S+1 via real typed cancellation, releases, proves zero new guest ledger entry/sequence/stock/command effect and correct peer drop (works on old code as counterexample). 2. Positive same-session compatible revision interleaving maintains coherent old-client progress/sequence and earlier admitted request still settles. 3. Existing 13 LAN and target viewer, actual compiled original/new host+guest both ways pass. 4. No change to PC11 bytes/ordinary local auth or installed snapshots.
|
||||
|
||||
## 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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run new focused LAN tests and full CTest -V, old/new interop harnesses from your S16-03 context, use logs s16-published-admission-*.log and git diff --check. Native Windows unavailable. Before fixed build, show exact reproducer outcome if feasible.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
If inability to atomically compare protected publication and enqueue, report actual contract and fail closed within scope. After two failed same-cause attempts root escalates; no other agents, external writes, retrying commands outside the appropriate session or full scans under runtime lock.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested end-to-end software and protocol compatibility. Fresh V15 correction belongs to S16; bounded change to existing owner seam is authorized. Root exclusively owns commits/remote operations and post-fix re-review.
|
||||
|
||||
## 14. Return format
|
||||
Return S16-04 READY or PARTIAL, frozen paths, observed pre-fix failure/post-fix controlled interleaving and old/new compatibility, actual logs and residual limits.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Prepare immutable client frames and present camera changes independently
|
||||
|
||||
Task ID: S17-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated system/s17-rendering at 66af7c5 includes reviewed S18-01 client. app/viewer_win32.cpp has a 60 ms session/network timer, parent+child paints retain an old pointer but still dereference changing globals and SceneView spans live blueprint vectors. D3DScene::render presently regenerates flat geometry even on camera-only paints. S18-02 alters title/host gates and bed text in another worktree. M01-P6/F9 advise independent dirty-only 16ms frame sampling and strict install boundary.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement S17-W01 normal Windows entry: scene and HUD consume one immutable prepared client packet including owned overlays, camera and pinned snapshot; camera frames can render while 20 Hz world step or file/load busy. Coalesce invalidation and reuse geometry on view-only changes.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Existing flat game map, hardware Direct3D/WARP and error HUD only. No M02 chunk meshes, new camera settings, render thread, input/protocol changes or 60fps hardware claim. Preserve current viewer/rooms/blueprints/colony UX and all baseline harnesses.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/viewer_win32.cpp scene_window and main WndProc, WM_TIMER/PAINT/DESTROY, camera wheel/drags, pump_session, draft/room render, title/minimize/resize, D3DScene in app/d3d_scene_win32.hpp/.cpp, map_camera, actual /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. CMake/tests WARP/capture availability, app/viewer_session member changing_world/poll_changes.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/viewer_win32.cpp (drawing, camera invalidation, timer/pump sequencing only); app/d3d_scene_win32.{hpp,cpp}; NEW app/viewer_frame.hpp/.cpp if useful; NEW tests/viewer_frame_smoke.cpp; CMakeLists.txt limited to registering frame test/owned sources; docs/plan/systems/S17.md
|
||||
Other branches own title/profile and stock; do not revert others' changes or switch Serena. Exclusive isolated s17 checkout. No Git/remote operations, further agents or unrelated app changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Prepare owned immutable presentation data on UI thread, derive HUD/selection/cursor/room validity and existing geometry from exactly one accepted world and copied relevant overlay state. Avoid borrowed spans into mutable UI across nested WM_PAINT or an overwritten single scratch buffer. Main and child paint each pin packet locally; no global world deref to render. Frame timer and camera/window invalidation independently drive dirty visible frames; keep existing 60ms LAN/control pump. While session->changing_world() keep prior presented world/frame including null, even if runtime.latest has already installed newer; release new world only after pump consumes Replaced, resets overlays/camera and updates identity. Guest/epoch transitions likewise cannot mix old work and new overlays. Sample ordinary healthy revisions with stable client identity.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Keep one current flat geometry version keyed by world identity/snapshot and all overlay/selected/cursor/BuildingView inputs. Camera-only or size-only change regenerates only camera/projection constants; account for resize/device/backend reset invalidating GPU upload. Explicit immutable geometry ownership shared by packets retained by readers; stale packets can render consistently even after newer packet then reuse correct upload. No work on hidden/title/minimized/zero sizes. On restoration or failed/recreated backend request fresh frame. No busy loop or full mesh rebuild/upload for unchanged view. Preserve existing D3DScene::render callers or update only within ownership. RAII for paint/DC and timers/shutdown.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Integration root will merge separately from S18 title+host. Avoid code dependencies on S06 custody changes, S21 hooks. Reuse Void owner snapshot (#5) and current D3D facilities; GPU resource ownership remains in renderer. Do not copy fixture include paths from other worktrees into repo. There is no GDI world renderer to invent in this scope.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check nested dialog/WM_PAINT while replacements happen, applied room/draft vector lifetime, same-world rollback or new UUID taking same tick, mouse cursor remains coherent re camera zoom and changes may legitimately affect preview geometry, no blocked owner/file calls on presentation thread. Render failure presents current HUD error and recoverable state. Graphics-test availability must be explicit, tests need bounded cleanup and skip/report only genuine backend unavailability.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Durable actual regression target (repo-relative source paths) observes fresh render and actual input camera/zoom/drag while owner worker and file writer blocked; original tick/canonical snapshot preserved. 2. Frame timer alone advances camera frame without event timer. 3. Held old packet remains renderable with old overlays across nested install; new packet resets correctly; exact saved snapshot content. 4. Geometry/upload reuse on pure camera/unchanged, title/hide/minimize/0-size/restore/destruct, device reset semantics; WARP/offscreen capture/real UI as available. 5. All original UI, core and LAN checks still pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s17-frame-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. CTest -V, git diff --check; source actual Wine GUI/D3D environment from env.sh. Add/verify focused new real frame smoke and existing UI regressions (three-process/temp harness with isolated LOCALAPPDATA, no user data). Use s17-frame-* logs and report observed device/driver.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if independent-frame scheduling would require replacing app/renderer architecture or mutating unrelated title/guest controls. Ask root on genuine scope change; after two failed same-cause fixes escalate with evidence. No M02 feature additions, Git/remote or children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap on system/milestone branches. Root approved independent dirty-only 16ms sampling, immutable packet, one flat geometry generation and no unsourced performance claims. F9 requires explicit pre-Replaced candidate fence.
|
||||
|
||||
## 14. Return format
|
||||
Return S17-01 READY or PARTIAL, actual owned changes/normal paths, packet/geometry lifetime, render/repaint file/worker evidence, exact logs/native limits. Send frozen smoke seam early.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Draw and pick the same sliced voxel terrain through Direct3D
|
||||
|
||||
Task ID: S17-02
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated detached staging worktree s17-voxel at 13dc673 contains both M01 immutable D3D frame changes and accepted S02 1ca481b (including MaterialId DoorClosed/DoorOpen). Later root integrates this work to the existing system/s17-rendering. M02-P1/F1 define shared z-up projection, frozen bounds/32³ S02 sampling/availability, finite edit scenario. Actual shader uses (x−y)*halfTile.x and (x+y)*halfTile.y−16*z, existing flat pick is z=0. Void pin 7b0fea6 Math::Vec/Numeric present, general bounded 3D grid-ray traversal absent under issue #12; mesh neighbor revision issue #13.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a usable terrain geometry and height-slice picking API, real D3D11 renderer entry point and offscreen WARP test proving projected visible surfaces agree with mouse hit cells/faces for edited signed voxel regions. Provide frozen interface early for normal S18+World frame hookup. Root/next worker wires actual authored game when its World factory exists.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
M02 terrain presentation/picking/CPU prepared geometry and actual D3D draw only; do not edit mutable World, simulation, new-game menu, viewer_win32.cpp, existing legacy protocol/codec or actor motion. Existing 2D rendering and immutable prepare/render interface are relied upon; cover regressions. Use game generated terrain and material colors, no borrowed graphics.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read real S02 voxel_region.hpp/cpp/test, S17-01 frame contract and S17 docs, M02 F1/P1, dependency matrix M02 and pin Math Vec/Numeric. Read app/{d3d_scene_win32,map_camera}.hpp, d3d_scene_win32.cpp Mesh/PreparedGeometry/shader/camera constant buffer/D3DScene::render, viewer_win32 map_cell/scene_view/camera/timers, tests/viewer_frame_smoke.cpp CMake graphics targets. Share public anchors with S18 owner; M02 normal World integration upcoming.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/d3d_scene_win32.hpp; app/d3d_scene_win32.cpp; app/voxel_scene.hpp; app/voxel_scene.cpp; tests/voxel_scene_tests.cpp; CMakeLists.txt; docs/plan/systems/S17.md
|
||||
New dedicated voxel_scene files plus tested D3D terrain overload; CMake only own source/test entries/libraries. Other agents own separate WTs. No external actions, Git writes/checkout changes, shared Serena activation, children or other source edits. Temporary controlled probes in your own /tmp build OK.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use actual existing shader isometric basis, z-up. Expose one view/projection/slice model for both rendering and hit query; support real camera origin/pan/scale/viewport and integer slice inclusive maximum visible z. Render material faces exposed to air/open door/slice/outside, avoid duplicate internal faces across adjacent loaded pages. Decide display for unavailable neighboring pages consistently; picking must return unresolved when an unloaded visible cell can precede a farther surface. Open doorway permits seeing and picking through its aperture, closed door blocks, rendering/picking same shape. Bound drawable cells/faces/time, support signed absolute/extreme coordinates via region-local origin and double checked ray/cell transforms, no huge implicit dense region allocation. Clip to actual bounds + slice and dynamic depth or comparable ordering so unusual signed positions are not clipped by the legacy flattened shader constants. Keep old renderer unchanged for old 2D. Use real immutable prepared CPU data and actual D3D upload/render, camera-pan reuse and retained meshes across mutation.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW public terrain APIs for building immutable surface mesh/packet (a shared pointer accepted by D3DScene::render over existing PreparedGeometry or equivalent) and constrained screen/world ray picking. Return region/epoch or caller-held snapshot plus stable voxel, signed face normal, adjacent placement/work cell when representable, consulted chunk stamps incl neighbor/missing for stale check. GPU resources owned by UI as existing; do not expose mutable resident pointers. NEW generic DDA local to receiver if no pin primitive: deterministic exact boundary negative coordinate convention, finite distance/step budget, zero components/no-hit/inside/start exactly on plane/edge/corner ties with declared single face, outside/unavailable distinct. Avoid epsilon that scales poorly across world; one documented voxel cell convention shared between meshing and picking. Bound face budget before/while preparing and refuse atomically without replacing old displayed geometry.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Committed S02 actual region ready. No new World getter needed in this package; S18 will call terrain prepare and pick on the exact held published region after M02 owner. Expose next-point integration callback/document only if needed. Root will sign off and ff/merge existing S17 branch after publication of M01. Preceding user branches/MRs preserved.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Negative floors/near int extrema/partial chunk boundaries, clipping slice (below/above whole region), camera pan/zoom/viewport, equal edge/corner traversal, unknown and unloaded neighbor occlusion, triangles orientation/cull/depth, overflows at INT_MIN/INT_MAX adjacency, WARP device reset/upload of older immutable packet. Respect real outcome with WARP, no physical 1080p60 claims. Keep CMake test registrations independent of running interactive controls, use offscreen captures where possible.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Build real signed two-page sample incl cutaway cave/passage, opendoor/closed, compare expected emitted faces and frozen old vs updated CPU buffers & distinct markers incl neighbor stamps. 2. Test/measure real offscreen WARP draws at controlled pixel samples and projected hit face/adjacent cell including slice and camera transforms, consistent crossing from both directions through x31/32 and negatives. 3. Ties/start-inside/zero direction/limits/unloaded/extremes explicit, refusal leaves displayed packet usable, camera-only no regeneration or upload when previous mesh valid. 4. Legacy viewer/frame tests pass, actual link and diagnostic output/issue links #12/#13 in docs. 5. Show bounded per world/page costs (prepared counts), no placeholder flat map geometry presented as voxel mode.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run new registered voxel scene target showing real offscreen WARP output and full ctest -V; coordinate interactive keyboard control tests with root before running. Write s17-voxel-*.log and git diff --check. Non-Windows host does not establish native hardware perf.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not silently fallback to flat map for unsupported 3D or ray through unloaded cells. If dependency/API or D3D transform must change beyond local scope, notify root with targeted counterexample. No new upstream ticket without pin/duplicate research; user mandated genuine gaps, #12/#13 already cover this. No remote, children or claims of normal S18 integration until actual world is wired.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized all milestones and system branches. Planner/F1 accepted 3D render/pick and actual shader basis. Reversible drawing/Face data layout choices delegated, root accepts final integration and posts remote work.
|
||||
|
||||
## 14. Return format
|
||||
Return S17-02 READY or PARTIAL, early stable public interface, verified real D3D pixel/pick behavior, touched paths, tests/limits/CPU-GPU retention and exact upcoming normal-viewer options.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Drive the Win32 client from committed world views and async results
|
||||
|
||||
Task ID: S18-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s18 system/s18-client at 512c9ef. Runtime reviewed at 7979fff and M01 8c4c1fe. S15-03 and S16-02 are in separate worktrees and root will supply reviewed commits to this checkout before final build. S18-W01 owns separating snapshot reads and command submission from window handlers. M01-F4 identified title/menu, lifetime, admission and rules gates.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Wire the actual Win32 viewer to the single-owner runtime for offline play and hosting, immutable guest view, bounded async command handling and real background checkpoint save/load. Keep title/new/continue, legacy scenario/cabin controls and LAN guest usable.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Normal Windows app entry points plus focused testable client-state handling. This first S18 slice does not include unrelated keyboard/scale/sound settings, new internet protocol or UI for metadata-only rule selections. Show only supported default-profile new games; S19 adds genuine selectable behavior separately.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read app/viewer_win32.cpp all session lifecycle/menu/paint/blueprint/command handlers, app/title_screen_win32.hpp, D3D const World entry, LAN and CheckpointFiles headers in sibling s16/s15, frozen simulation_runtime.hpp/impl, raw world factory/first_colony, and existing tests/smoke source /tmp/stoneheart-verify.KoZwE4o8/viewer_smoke.cpp. Watch S06-01 resident detail index access intentionally owned by another worktree.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/viewer_win32.cpp; app/viewer_session.hpp and app/viewer_session.cpp (NEW if needed for testable state); tests/viewer_session_tests.cpp (NEW); CMakeLists.txt (viewer_session target/tests only); docs/plan/systems/S18.md
|
||||
Do not edit other worktrees, shared Serena or Git, or overhaul unrelated UI. Keep resident-detail lookup changes minimal where S06 branch also edits one line; parent integrates. Native normal entry is mandatory.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
One window-lifetime owner runtime where possible. New/reset/load install prepared WorldCheckpoint with fresh incarnation; reuse the long-lived runtime or retire former owners off UI without joins, keeping retirement bounded. Guest reads latest received world immutably, never steps/applies; suspend local owner when guest, fence pending UI/authority. Preserve playable disconnected/leave behavior: keep last received guest World privately owned to import into a fresh local session on deliberate leave if prior behavior allows continuing that colony. Fresh first colony uses nonnil stable UUID+resolved default manifest. Gate viewer installs to exact supported compiled-rules profile/32x32 dimensions, preserve legacy imported world. Use consistent shared const world/view per frame and protect raw references across nested window messages/modal confirmations by pin or revalidate after dialogs. Render/HUD paths must stay safe on title with no world. WM_TIMER pumps file/network/runtime completions and reconciles desired ticking state BEFORE ANY title/offline/file-dialog/UI early return. Never step/serialize mutable World on UI. File picker is normal modal selection; picker open affects presentation pause without blocking owner polling or completion processing. Anchor title/hidden, pause-menu, file-dialog, guest/host and shared World::paused semantics to existing user-facing choices; no flood of set_ticking when unchanged or Busy. Fault visible, rendering last head and explicit load still usable.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Expected seam: S15 CheckpointFiles(options) with try_save(path,shared_ptr<const PublishedSnapshot>), try_load(path,workers,mode) → admission/request/future<expected<WorldCheckpoint,CheckpointFileDiagnostic>>, one process-level instance, survives reset across slots. Viewer obtains snapshot_for_save(), tracks completion by request+epoch, only reports latest relevant result. At selected load intent issue runtime begin_load even if ensuing file decode fails so stale older prepare cannot undo latest request; file result independent, filter UI ticket/generation+epoch, install checks again, preserve display on invalid/busy/superseded. S16 provides void poll_host(SimulationRuntime&) and unique_ptr<World> poll_guest(); guest presentation stores owned snapshot only, legacy standalone poll(World&) is for old consumers. Attach local controls/host and legacy cabin to modern CommandEnvelope, trusted host slot, via ONE bounded per-client intent queue and at most one runtime submission awaiting reply; allocate number from latest committed next_requests, never consume on Busy; retries do not duplicate. Pending blueprint/room IDs or exact generation-marked metadata ensure only an actually accepted part is cleared, rejected/busy remains editable, repeated click cannot resubmit pending. Other accepted-only statuses after commit. On reset/join/load, disconnect or retired epoch fence stale results and preserve unrelated current edits. Explicit local effects and connection authority; no GTK/web UI.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root merges reviewed S15/S16 deps into s18 checkout before final build; send dependency requests early. Development may start on public seam/logical model; verify actual source before final compile. F4 corrections per exact contract. Existing tests and external Wine UI smoke must still run. Current UI actions should remain meaningful. No fake alternate rules advertising. Preserve old compatible file extension/recent saves and existing no-guest-save host policy.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
UI must remain responsive during deliberately long tick/file write, complete results on title/modal loops, avoid dereferencing stale selected_agent pointer, actively fence prior session commands/loads, avoid starving owner and don't freeze on reset/new/join. No stateful dangling callbacks on WM_DESTROY; orderly shutdown can drain on app exit. Queue memory and ongoing operations bounded by documented capacity. No unchecked exceptions escaping Win32 callbacks or stale feedback after generation change. Use deterministic gates for tests; actual end-to-end app path observable.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Launch actual viewer, start and advance local colony; deferred owner command incl cabin, pause/unpause while at same tick; no WM_TIMER direct world->step/World::apply_command. 2. Open modern and old saves from title, save during progress, update status only on newest completion; malformed/superseded/unsupported rule loads preserve current session. 3. UI reader can repaint/pan while owner/writer blocked; no synchronous join resetting/joining. 4. Host and guest continue through correct polling and domain-rejection/blueprint sequencing; stale queued intent/load cannot affect new session. 5. All Windows x64 tests and real viewer smoke, including title load if possible, with recorded native gaps.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe or viewer suite as actually registered, CTest -V, git diff --check. Reuse local isolated Win32 smoke harness for real viewer title/new/close and extend temporary harness for title/save/load as feasible; no disk writes to real user saves. Keep logs client-*.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits to S06, raw game rules, runtime, file service or LAN wire. Stop if exact external API differs or a product decision is needed, continue independent work. After two failed repairs of the same issue escalate. No children/Git/remote mutations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, per-system branches, commits/push and merge requests. F3/F4 and subsequent corrective recheck apply; parent owns branch merges/remote publication, no release.
|
||||
|
||||
## 14. Return format
|
||||
Return S18-01 status, actual changed behavior/lifetime/queue and gates, owned files, exact tests and Win32 smoke evidence, pending native validation. Communicate frozen helper/normal UI entry paths early.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Select supported rules when starting a colony in the Win32 client
|
||||
|
||||
Task ID: S18-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated s18 worktree after root fast-forwards to db0a872 or a descendant containing the reviewed b7f18c0 client and 2759563 compiled profiles. S18-01 uses a long-lived runtime, exact default-only constructor/load, healthy views, transactional guest admission and fresh session identity. S19 core factory and validator already run the two real cost chains. M01-F6/F7 require validating initial, asynchronous and legacy hosts.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Make the actual Russian title screen offer staged beds (default) or one-plank beds for a new colony, apply the selected compiled rules to the new world, reload either supported profile exactly, and restrict LAN protocol 11 to default rules before any network side effect.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S18 profile selection/validation and accurate colony presentation. Preserve general S19 resolver, format1–14, LAN bridge/wire, legacy guest leave and unrelated keyboard/settings. Initial factory default stays staged, UI title selection is local to this process and only affects New.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root/s18 actual app/title_screen_win32.hpp, viewer_win32.cpp, viewer_session.hpp/.cpp, tests/viewer_session_tests.cpp, colony_profile.hpp/.cpp (colony_rules, compile_colony_rules, make_colony_checkpoint, validate_colony_checkpoint), S19 profile_tests and S18/S19 docs. Inspect LAN direct and deferred host event paths BEFORE making changes, current supported_rules_ also supplies legacy guest import. Actual smoke sources client_{ui,handlers,regression}_smoke.cpp in temp.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/title_screen_win32.hpp; app/viewer_win32.cpp (title/new/host/bed labels only); app/viewer_session.hpp and .cpp (factory/validator/host readiness); tests/viewer_session_tests.cpp; docs/plan/systems/S18.md
|
||||
Isolated s18 only. Other workers edit separate branches. Do not revert others' changes or modify CMake/other components. Root owns all Git/remote operations. Distinct test build directory.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use one accessible native control for a clearly labeled New-only choice, ensure keyboard (focus/Tab/arrows/Space/Enter as appropriate) and mouse operate at supported dimensions. Preserve title layout/order and new/continue/save list. Factory creates a new UUID and selected actual world; Continue/Open ignore current selector. Run candidate validation for both supplied initial and replacement/latest prepared loads before owner install and preserve current 32×32 restriction. Preserve default simple/inactive historical modes. Display correct cost including Miner house in simple profile; hide staged foundation material controls when simple.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Host immediate path must reject if changing_world or the current authoritative publication does not have exact default rules. Recheck after returning from modal menu before opening a listener; deferred path revalidate the newly installed publication immediately before network start. Error preserves active world/local file operation/peer. Existing default simple legacy world can host if other established gates pass. Legacy guest import still uses exact frozen default. Do not expose optional rules via old wire. Keep S18-01 fresh ticket/epoch gating and bounded queues.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns fast-forward to integrated base before starting. Backend S19 and first viewer are independently accepted. New choice has real compiled behavior. Future S17 render-timer changes are separately owned; avoid edits to WM_TIMER or D3D unless a real unexpected dependency is reported.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reject unknown/forged/extra manifests, optional+staged, unusable dimensions/identity before any effect. Restore valid default raw simple, active optional simple and authentic old saves. A superseded valid load followed by failing newest must keep current world. Titles with small width/DPI should retain usable label/control. No external files in real saves, never open real network beyond loopback.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Real title New creates both variants (including exact selected manifest in saved checkpoint and visible costs). 2. Continue/Open preserve saved choice despite different selection, exact default old inactive/simple accepted. 3. Bad initial/load gate leaves session/world untouched. 4. Immediate/deferred legacy Host refusal before listener or peer change, including held optional load over old default. 5. Existing ten viewer tests, integration CTest and prior three-process/handler regressions still pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-profiles-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V, viewer suite selectors as actually registered and git diff --check. Run an actual GUI smoke with isolated LOCALAPPDATA, exercise both choices with mouse/key, New, save/open with opposite selector, confirm actual stored manifest/bed mode. Extend /tmp smoke only as appropriate and record client-profile-* source/logs. Named current published checks are baselines.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not change staged vs simple game costs or default digest, add fake settings, change wire or unrelated app controls. No lowering exact-default admission. If title input cannot be exercised with available Windows/Wine tooling, describe specific gap and continue core meaningful checks. No children/commits/push; two failed same-cause fixes escalate.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User asked for complete milestones/system branches and actual compatible module selection. M01-F7 recorded corrective host gate and accurate simple Miner description. Root owns external side effects. Existing upstream #4 tracks generic resolution.
|
||||
|
||||
## 14. Return format
|
||||
Return S18-02 READY/PARTIAL, actual chosen title control + normal flow, exception/load/LAN boundaries, paths, commands/logs and any native UI caveats.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Resolve a frozen set of game rule packages from actual manifests
|
||||
|
||||
Task ID: S19-01
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 8d2870a. Main working directory belongs to another task. Exact Void pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. M01-P2/R2 and preflight F2 confirm the implementation seam.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement S19-W01 typed game rule manifest loading, validation and reproducible identity, with real JSON inputs and CTest coverage. Supply the public interface S15/S01 will freeze into worlds.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S19/M01 core support and its tests/build wiring; no Lua, UI, save codec or network yet. Plan requires diagnostics usable by a caller and frozen identity for explicit world selection.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/systems/S19.md, M01, CMakeLists.txt, exact upstream Void/Data/StrictJson.hpp, Void/Text/Semver.hpp, Void/Algorithms/Graph.hpp, Void/Crypto/Crypto.hpp and respective tests. Source root for pin is /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/rules_manifest.hpp; engine/src/rules_manifest.cpp; tests/rules_tests.cpp; CMakeLists.txt
|
||||
You are not alone. Use ONLY your specified worktree with explicit workdir/absolute paths, verify root/HEAD before edits. Other systems have separate checkouts. Do not edit the main checkout, change shared Serena project, stage, commit, push or spawn. Root integrates CMake.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Bound byte count and node/dependency/depth limits before/while using Void::Json::Strict. Manifest schema v1 includes namespaced package ID, exact strict SemVer, named dependencies and version constraints, exclusive providers, definitions with stable qualified IDs and references. For M01 definitions live in the JSON file (no external untrusted file paths/scripts). Resolve transitive deps from installed packages (one installed version per ID), detect duplicates/missing/range incompatibility/cycles/exclusive-provider clashes/unresolved definition refs. Use Void::Semver, Algorithms, Crypto and StrictJson. Sort sets, include definition content in SHA256, recompute digests; preserve semantically ordered data. Write diagnostics containing package/source and field. Provide usable base game package(s) for later startup via an explicit built-in loader or factory in owned code. Avoid implementing generic library alternatives.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW public RulePackage source + immutable RulesManifest (sorted frozen package ID/exact version/SHA256 and manifest fingerprint), loading/resolution via settlement/core/rules_manifest.hpp. Expose a base default and real catalog/selection input. Keep public types independent of upstream internals where practical. Define schema, duplicate/unknown semantics and source error handling in a short header comment. Send final signatures to root ASAP for S15/runtime.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
No upstream dependency update. Validate SHA-256 pure C++ fallback on Windows; use modules Data, Text, Algorithms, Crypto and transitive deps only. Matching generic candidate issue draft for reusable resolver is root-owned; game-specific capability names and decisions use published primitives. Root handles cross-system consumers and remote tracker outcome.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reject unknown schema/invalid UTF-8/duplicate fields, malformed IDs/versions, digest spoofing, large files and excessive fan-out. Range semantics need explicit prerelease policy. SemVer == ignores build metadata, so frozen exact identities compare normalized full string and 32-byte digest. Stable diagnostic path relevant to user-provided files. No third-party game content.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Load and select from at least two meaningful original package documents with deps; reversing input/definition sets produces identical frozen identity. 2. Content, exact version or build change alters fingerprint. 3. Missing dependency, bad range, duplicate, cycle, exclusive conflict, dangling references and malformed/oversize JSON give actionable diagnostics. 4. Windows target/test suites pass and API ready to persist/compare a manifest.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/rules-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Add a discoverable Void suite with tag rules. Check actual diff and log timings.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Escalate any required new generic mechanism or library incompatibility. No network writes, no Git mutations, no competing branch/source edits. Stop after two unsuccessful repairs of one issue and send original failures.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized full plan, milestone/system branches and pushes. The root handles those; preflight READY for S19 under these limits.
|
||||
|
||||
## 14. Return format
|
||||
Return S19-01 status, actual files and API, schema/canonicalization decisions, failure coverage, commands/results, unverified limits, integration notes for runtime/save. Do not spawn.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Compile a selectable plank-bed package into actual colony behavior
|
||||
|
||||
Task ID: S19-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive s19 worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 60154bd. Prior S19 catalog/manifest reviewed, M01-P4 and F6 preflight approved both existing bed production paths. Current World::start_scenario sets staged_beds_=true unconditionally; legacy/restored worlds already execute nonstaged SawPlank + BuildBed. S18 initial UI work/other World changes in distinct checkouts.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Allow real selection between the existing default staged bed assembly and optional one-plank bed assembly at colony creation. Freeze compatible manifest/engine configuration and provide supported-profile validation at the application boundary for creation and loading.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S19 core package, game-profile compiler/factory, narrow World scenario initialization and runtime-neutral validation tests. No UI/transport changes in this slice. No change to generic resolver/decoder acceptance or Lua VM. Preserve all original package contents, default game output and original call signatures/behavior.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect rules_manifest.{hpp,cpp}, first_colony.cpp, world.hpp/.cpp start_scenario/PlaceBed/PlaceRoom/recipes, world_save.cpp staged flag/state validation, checkpoint.hpp, actual tests/rules_tests, core_tests, legacy fixtures, prime S18 viewer_session.cpp constructor/load/host gates via sibling and plans S19/F6. Pin has resolver primitives used earlier, existing issue #4. Current default SawPlank executes 12 ticks; the old manifest's sample work_ticks=8 is not activated by this feature.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/colony_profile.hpp and engine/src/colony_profile.cpp (NEW); engine/src/rules_manifest.cpp; engine/include/settlement/core/world.hpp; engine/src/world.cpp (scenario initialization only); engine/src/first_colony.cpp; tests/rules_tests.cpp; tests/profile_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S19.md
|
||||
Skip all UI and unrelated caller edits. S04 changes production identity in separate worktree. You are not alone; root integrates and handles simultaneous CMake/World edits. Never revert another worker, change Git or shared Serena.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Add additive optional built-in exact package settlement.plankbeds with an allowed recipe definition in its own namespace, stable dependency on settlement.colony and no conflicting exclusive construction capability. Interpret explicit typed data describing one plank/simple assembly to select the actually existing engine bed mode. Use resolver/checkpoint typed APIs, validate supported exact closure/digests and content before building a supported colony. Compute prechange default manifest canonical bytes/fingerprint using the verified baseline first, hardcode golden from it into regression (old two-package closure/content unchanged); do not recompute expected with candidate. New default=false option meaning must be clear by names. Expose concise NEW profile enum/options and a game-specific factory producing validated WorldCheckpoint (owned World, fresh stable nonnil UUID, city1, correct manifest), plus supported-profile validation taking World/manifest or candidate. Name signatures early so S18 follow-up can wire title.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Keep existing World::start_scenario(sawmill), make_first_colony(workers) staged by default; add explicit creation-only mode/profile parameter or overload, no mutable post-creation toggle. When active optional package selected, actual simple path: SawPlank + one BuildBed, one plank consumed; default already uses foundation wood/stone plus cloth twice. Furnished rooms must respect same rule. Existing schemas saved real mode; loaded exact default is allowed with EITHER persisted mode, inactive legacy worlds included (historical v1 or raw-format import). Do not alter their rules/mode at load. Optional exact profile requires active scenario staged=false where applicable; reject exact simple-manifest with active staged world. Unknown package/digest/config rejected by supported-profile gate; generic decode/runtime continue to handle caller-supplied catalogs independently. Reuse shared immutable definitions/lookup as suitable; avoid catalog-size assumptions and requiring every installed unrelated package.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Viewer later calls this public factory and canonical compatibility gate on BOTH initial and prepared worlds, and keeps immediate/deferred old LAN11 exact-default-only. Do not mix S18 UI edits on s19; communicate the trusted support check and whether a profile may host to root. New catalog optional must not automatically activate or alter existing default hashes.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Exercise active/inactive imported historical worlds, current resaves, no silent toggle or package rewriting. Avoid claiming all base/ACE systems implemented. Use an actual complete bed production run under both options with relevant materials/outputs (incl furnished room), mature/paused snapshots persisted and continued. Preserve wire13/old baseline normal path. An altered content package using same ID/version must not pass compiled-profile support.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Old default known fingerprint/bytes and baseline gameplay preserved; selecting optional package changes material chain and completes bed with actual initial supply. 2. Compare modern canonical per tick across serial/2/6/12 for representative events; held view does not change; mid-carry save/load continues identically. 3. Exact optional mismatch, default historical raw/v1 active simple and inactive accepted without rewriting; catalog reordering and missing/changed/extra activated packages handled. 4. Correct real startup factory and no mutable rules switch. 5. All cross suites pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/profile-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag profile and tagged rules, full verbose CTest, git diff --check; source actual old baseline digest from already built branch or separate helper, log its hash. Provide exact logs profile-*.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No editing S18 UI, no broad changing existing recipes to fit sample data and no rewriting old manifests, formats or resources. Stop/escalate after two failed repairs of same issue or if actual optional mode cannot complete the scenario. No children/Git/remote mutations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Plan explicitly requires new-world module selection. Existing bed behaviors were chosen as first reversible demonstration, preserving old defaults and P4/F6 restoration policy. User authorized commits, issues and PRs through root.
|
||||
|
||||
## 14. Return format
|
||||
Return S19-02 status, early exact creation/validation API, source derived default golden, observed actual bed/room/canonical and legacy compatibility, counts and residual native/UI risks.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Prove deterministic arbitration under opposing worker completion orders
|
||||
|
||||
Task ID: S21-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated system/s21-verification at 66af7c5. World assign_idle_agents calculates independent candidates for idle residents then assigns competing jobs in stable order. Meal claim is serial before parallel movement. Existing replay compares Current14 state for 1/2/6/12, last meal and mid-delivery plus capacity1; scheduler hooks currently before_submit/before_execute only. M01-P6/F9 request an observer of actual returns and readable divergence reports.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a minimal optional success observer in the real WorkerPool adapter, prove opposite actual calculation completions and deterministic arbitration, and report first divergence through domain facts tied to canonical bytes. Verify runtime install waits for outstanding work and fresh session fences stale results.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
WorkerPool instrumentation, tests and S21 verification docs only. No World scheduling/codec/receipt semantic changes, no synthetic exploit inputs or unrelated rendering/milestone changes. Native Windows hardware separate.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read engine/include/settlement/core/worker_pool.hpp, engine/src/worker_pool.cpp/world.cpp (actual partitions and meal selection), runtime source, tests/{executor,replay,runtime}_tests.cpp, M01-P6/F9 and S21. Void FuturePool/Testing at pinned clone and issue #15.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/worker_pool.hpp; tests/executor_tests.cpp; tests/replay_tests.cpp; tests/runtime_tests.cpp; NEW tests/replay_diagnostics.hpp only if useful; docs/plan/systems/S21.md
|
||||
Isolated s21 only. Other agents own sibling source. No CMake mutations, shared project switch, children/Git/remote changes. Root integrates.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
NEW optional WorkerPoolOptions::after_execute(index), success-only after callable returns before result future ready. Account for optional observer alone in submission indexing. Preserve original no-hook path and hook/call behavior for void, values, lvalue refs, move-only closures/results and exceptions on worker + inline fallback. Observer exceptions reach corresponding future; no throwing destructor. Test using separate driver and bounded CV gate for two known submissions; release on all exit paths. Only block task B until A has actually returned (post hook), then reverse. Never wait for all tasks/lanes or rely on sleeps/scheduling chance.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Fresh two-resident/one real reachable WorkJob scenario, opposite completion traces must be observed even with max_admitted1 on a separate driver, 2/6/12. Verify deterministic winner and each future state equal serial canonical Current14. Last berry serial claim test/cargo/movement preserve independent one-winner evidence, do not claim parallel meal arbitration. Add old worker held, queue same-world earlier load, verify old view remains readable/install pending until drained, replacement identity fresh, old request rejected, current state intact after further fence.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Test-local semantic reporting only when canonical byte comparison differs (existing Current14 encoder remains oracle). Include seed/scenario, attempt/tick, concurrency/schedule, load, stable first differing entity/property and expected/actual, command/receipt player/number/status/revision or byte-offset fallback. Actor/job/storage stack as owner plus type for current14; support absent/extra records. Test at least stock/job/command divergences individually and equal-case. Later body15 will extend this; don't introduce alternate persistence schema. Reuse existing helpers/tests.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound waits even on CI; each branch releases gates before destroying/joining pool; no assertion library calls from worker threads. Keep hook captures alive; no mutex while running user callbacks. When no selector installed, no new allocations/counters per job. Tested genuine Submit paths including inline. No simulated full native performance claim.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Tests fail when completion acknowledgement incorrectly moves to start, schedules traces must be opposite and canonical states match. 2. Observer sees returned value/reference/void, exceptions incl hook and overload, callable ownership preserved. 3. Reload barrier stale work/commands and snapshot fencing checked. 4. Domain diagnostics exercised with expected entity ID/field/receipt context. 5. All CTest, corpus, focused tags and docs checks pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V and --tag executor, --tag replay and --tag runtime under Wine; record s21-replay-* logs and commands. Old normal corpus should remain unchanged, use available trajectory probes as appropriate. Actual checks rather than latency claims.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if index pair cannot be tied to real first job-choice partition: identify actual code and adjust fixture, no pretend success. No global installation or unrelated changes. Two failed same-cause fixes escalate. No children/Git/remote writes.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete M01 and separate S21 system branch; root approved test-only success observer and strict canonical oracle. [Void/Library completion test facility](https://git.faumaray.com/Void/Library/issues/15) documents the replacement test. Root publishes.
|
||||
|
||||
## 14. Return format
|
||||
Return S21-01 READY/PARTIAL, bounded integration/worker semantics, branch files, tests with actual opposing traces/diagnostic cases/corpus, native limits.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Compare authoritative custody state in journal and runtime replay
|
||||
|
||||
Task ID: S21-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S21 sibling at 3c7cc3c merges approved replay ef980af with provisional live World/codec 539cea0, later partner fixes will be included. tests/replay_diagnostics.hpp canonical and tests/replay_tests.cpp saved_state still choose Current14, tests/runtime_tests.cpp bytes currently defaults to Legacy13. Both projections drop custody15. S15 owns tests/snapshot_tests.cpp. Released S21 real opposite-order tests and prior hashes must still pass.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Use current complete raw15 state for replay/owner snapshots and identify divergent item owner, stack/reservation/transfer/receipt/balance when those facts change. Exercise retained cancel/retry and continuation on 1/2/6/12. Keep intentional legacy13/14 compatibility fixtures and golden outputs as separate existing coverage.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only test replay/diagnostics and their S21 explanation. No changes to application World, protocol/codec, CMake unless unavoidable for existing registered suites, generator/M02 or unrelated tests. This is a contracted validation extension of S21-01 (M01-F8/F9).
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect tests/replay_tests.cpp, replay_diagnostics.hpp, runtime_tests.cpp, tests/custody_tests.cpp and custody_migration_tests.cpp, engine/include/settlement/core/{world,custody,simulation_runtime}.hpp, custody.cpp, world_save.cpp, S06-03/S15-04/docs/plan/custody.md and S21. Read surrounding domain projections and fallback.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: tests/replay_tests.cpp; tests/replay_diagnostics.hpp; tests/runtime_tests.cpp; docs/plan/systems/S21.md
|
||||
Isolated s21 only. You share checkout state with others in separate working directories; do not revert others or change other WTs/branches, shared Serena or any Git/Gitea state. Parent handles schema source seals.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Centralize canonical save selection in the test helper to Current15 and apply it to current replay & runtime owner world equality paths, preserving any explicit legacy compatibility expectations. Extend first-difference report from real public immutable facts with stable entity/owner IDs: resident/storage/order input stack quantities/IDs, execution and active claims, admission/operation receipt keys and result outcome, material balance. Compare canonical bytes first and retain unknown/opaque byte fallback. Organize human-readable distinctions so stock change still reports stock, before a secondary balance if relevant. Do not construct huge diagnostic maps on equality.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Consume Inventory::stack_id, Agent.execution and next_admission, ProductionOrder.input and suspended, World::item_balances(), custody_receipts() and public receipt/request/result. A public vector is a ring backing store; use key and true order only when authoritative, avoid exposing physical ring layout as game identity. No modifying private counters nor pointers into mutable shared data for assertions. Use a valid game action/migrated world with same historical projection but differing modern owner/receipts if possible (old projected world loaded vs originating modern).
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Real source base includes custody and codec; parent will furnish final stricter validation and zero-count terminal semantics as local commits. S06 owns normal domain fixtures S15 authenticated raw15/history; S21 owns comparison and divergent-entity diagnostics, runtime stale/reload, not another codec test. External library support references existing issue #15 real execution, #7 ids/#8 transfer only if relevant. No request creation.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Only derive proof from real accepted actions with invariant-valid states. Catch first divergence when original legacy projection matches despite changed durable facts; do not falsely flag a different ring backing index as a logical change. Preserve old positive-negative receipt/stale owner and reproducible opposing completion trace. Keep replay test runtime bounded (first compare bytes and build facts on mismatch only). Notify root early of genuine production defects.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Current canonical captures include all custody state on real replay and after load; regression makes prior projection blind yet new one finds named entity/step. 2. Existing identity/stock/job/context and byte fallback still work. 3. Continue canceled in-flight durable cargo through checkpoint on serial/2/6/12, retained replay/conflict without physical duplicate. 4. Root can integrate while all registered tests, 24 actual completion traces and historical golden checks remain intact.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Focus --tag replay and --tag runtime after build, full CTest -V, named /tmp/stoneheart-milestones.xprJ2SVp/s21-custody-*.log and git diff --check. Authentic raw13 corpora old-trajectory.bin + identity-compat-old.bin independently validated by S06; compare if behavior or underlying partner revisions change.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No application edits, publishing, shared source checkout switch, new helper API into World or script internals just for diagnostics. If blocked by partner fix, obtain it through root while implementing independent diagnostics; report exact evidence. Review independent via root.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Approved milestone/system work plus explicit exact-state replay and ID diagnostics from M01. Root keeps transient cross-branch commits local pending package acceptance.
|
||||
|
||||
## 14. Return format
|
||||
Return S21-02 READY or PARTIAL with real base, owned diff, command results, source domain/id and regression observations, test runtime and external dependencies.
|
||||
|
||||
Worktree now at `e26b9c2` includes the stricter S06 validator and S15 zero-count terminal effects, count budgets and authentic migration/ring tests from `ccd50ec`. Begin on this combined source.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Владение грузом во время работ M01
|
||||
|
||||
Формат 14 уже различает заказы по постоянным ID. Следующий срез [S06](systems/S06.md) и [S04](systems/S04.md) вводит имущество, требования к нему и результат передачи. Это контракт реализации для текущих игровых действий. [План этапа](milestones/M01.md) · [Проверка действующего кода](../agent-workflow/tasks/M01-P5.md)
|
||||
|
||||
## Имущество и резервы
|
||||
|
||||
Каждый непустой стек имеет ID мира и одного владельца — склад, жителя или входной запас конкретного производственного заказа. Количество хранится у владельца. Резерв ссылается на него и задаёт удерживаемое количество. Отдельные резервы удерживают рабочее место, источник добычи и место для результата. Счётчики доступности склада и источника можно восстановить из действующих резервов. Требование рецепта описывает затраты отдельно от имущества.
|
||||
|
||||
Целый стек, переходящий в пустой слот, сохраняет ID. При разделении ID остаётся у исходного остатка, а новая часть получает отдельный ID. При объединении сохраняется ID стека получателя. Ссылки резервов на перемещённое количество обновляются той же операцией. Для каждого вида ID свой восстанавливаемый счётчик. Ноль означает отсутствие ссылки, а `UINT64_MAX` у следующего ID — исчерпание. Выделение всей группы проверяется до изменения мира. [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7)
|
||||
|
||||
Назначение работника закрепляет все материалы, рабочее место и вместимость вместе. Для плотника место под результат может обеспечивать зарезервированный входной материал в том же складе. Резерв места ссылается на конкретный резерв материала. Одна единица обеспечивает только одно место. При получении этого материала на освободившееся место устанавливается обычный резерв. До окончания работы запоминается и исходный склад, чтобы прежние команды перемещения и разбора выдавали согласованный отказ после получения груза.
|
||||
|
||||
| Событие | Изменение владения |
|
||||
|---|---|
|
||||
| Стартовые запасы и добыча | Начисление создаёт количество у склада либо жителя. Для добычи в тот же момент уменьшается исчерпаемый запас источника. |
|
||||
| Получение материалов | Все позиции текущей остановки переходят со склада к жителю. При отказе любой позиции весь груз остаётся на месте. |
|
||||
| Прибытие на стройку | Материалы переходят к заказу. Пока идёт работа, у площадки есть собственный входной запас. |
|
||||
| Завершение рецепта, монтаж, еда | На одном шаге списываются входы, учитывается причина и при необходимости создаётся результат. |
|
||||
| Отмена до получения | Освобождаются требования к складу, рабочему месту и исполнителю. |
|
||||
| Отмена в пути или на площадке | Груз остаётся у жителя либо возвращается ему со стройки. Уже установленные части здания сохраняются. Житель возвращает все виды груза, ожидая место при заполнении складов. |
|
||||
| Разбор свободного склада | Оставшиеся запасы списываются с причиной разбора и точным количеством каждого вида. |
|
||||
|
||||
Когда время работы истекло, а завершение временно невозможно, исполнение сохраняет состояние ожидания завершения и нулевой остаток времени. Новый шаг повторяет проверку с очередным номером операции. Так при исчерпании ID или переполнении не происходит повторного уменьшения нулевого таймера и частичной выдачи результата.
|
||||
|
||||
Для каждого вида предмета проверяется баланс. Начальный остаток, начисление, добыча и производство равны сумме имущества у всех текущих владельцев и списаний на сырьё, монтаж, питание и разбор. Счётчики источников и расходов используют проверяемую арифметику. Эта проверка выполняется при загрузке и в тестах. [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8)
|
||||
|
||||
## Исполнение и повтор
|
||||
|
||||
У создания исполнения заранее известен ключ из ID жителя и его следующего номера назначения. Нумерация начинается с 1. При успешном принятии мир одной операцией выдаёт `TransferId`, сохраняет данные запроса и его результат и увеличивает номер назначения. Потеря ответа не может назначить ту же работу повторно. Нехватка ID, места или материалов до принятия оставляет оба счётчика прежними. Последующие шаги используют пару из `TransferId` и очередного номера операции. Отказ принятого шага меняет только журнал повтора. Повтор с исходными данными возвращает прежний результат, с изменёнными — конфликт.
|
||||
|
||||
Хранятся последние 4096 результатов в порядке применения. Для каждого результата закодированные запрос и ответ ограничены 1024 байтами каждый. После вытеснения прежний номер распознаётся по следующему номеру шага действующего исполнения или по границе выданных ID завершённых исполнений. Устаревший запрос не может повторно переместить имущество. У жителя не более одного действующего исполнения. Резервы одинакового предмета могут относиться к разным складам; размер набора проверяется по фактическим ограничениям игры. Полные проверки и измерения размера снимка входят в приёмку.
|
||||
|
||||
Действующие ссылки должны разрешаться к существующим объектам. Историческая квитанция может содержать уже израсходованный стек или удалённый заказ. Загрузчик проверяет её вид, согласованность полей и диапазоны выданных ID. Пары схемы и тела проверяются по отдельности для всех трёх поколений сохранений.
|
||||
|
||||
Явная отмена относится к современному приказу по `ProductionId`, с проверками города, инкарнации и номера запроса. Житель с возвращаемым грузом сохраняет своё исполнение до сдачи последней единицы. Если у кровати уже установлено основание или существует действующий ткацкий станок, отмена сохраняет площадку под прежним ID и приостанавливает следующие работы. Явное возобновление продолжает с сохранённой стадии. Завершённая кровать сохраняет назначение владельцу. Для старых `DemolishObject` и `MoveObject` продолжают действовать прежние отказы при занятом источнике, складе или кровати. [Контракт команд](systems/S16.md)
|
||||
|
||||
## Сохранение и миграция
|
||||
|
||||
Планируемая контрольная точка схемы 3 использует тело версии 15. В нём сохраняются реальные ID, владельцы, незавершённые исполнения, резервы, результаты повторов и баланс. Повтор ID, лишний владелец, пропавший источник или несовпадающий баланс отклоняют кандидата до смены текущей партии.
|
||||
|
||||
| Вход | Восстановление |
|
||||
|---|---|
|
||||
| Тела 1–13 и контрольная точка схемы 1 | Проверить исторические поля и контрольную сумму. Сопоставить позиционные ссылки постоянным ID. |
|
||||
| Тело 14 и схема 2 | Сохранить имеющиеся ID заказов и следующий ID, восстановить остальное имущество из действительных старых данных. |
|
||||
| Материалы в пути | Уже посещённые остановки соответствуют грузу жителя. Оставшиеся материалы удерживаются у склада. |
|
||||
| Начатая работа с доставленным материалом | В старом формате прибытие убирало материалы из инвентаря жителя. Восстановить вход площадки по проверенному действующему рецепту, затем посчитать начальный баланс. |
|
||||
| Добытчик, перевозчик, голодный житель | Восстановить фактический груз, удержание места, резерв источника или еды в соответствии с сохранённой стадией. |
|
||||
|
||||
При переносе старого активного задания ему назначается первое поколение, а следующий номер назначения жителя устанавливается в 2. Для свободного жителя следующее назначение начинается с 1. Запрос от уже перенесённого поколения без исторической квитанции получает ответ об устаревшем номере.
|
||||
|
||||
Обычная партия сохраняет побайтовый экспорт 13 и протокол LAN 11. Для отменённой стройки житель может нести несколько видов материалов без доступного склада. Даже одна доска без связанного с ней заказа может не иметь представления в старом состоянии перевозки. Кодек сообщает `UnsupportedLegacyState` до записи первого байта. Это относится также к приостановленной площадке и другим несовместимым сочетаниям состояния. Современная контрольная точка сохраняет партию полностью. Хост проверяет представимость до допуска гостя, разбора приказа и выдачи снимка. При отказе совместимый гость получает отказ в подключении или отключается, а хост продолжает игру.
|
||||
|
||||
Приёмка охватывает остановки до получения, между складами, на площадке, при отмене и при ожидании свободного места; исчерпание ID и числовые границы; точный повтор до и после загрузки; старые двоичные наборы; сравнение каждого такта на последовательном исполнителе и 2/6/12 потоках. В контрольном сценарии с 500 жителями дополнительно измеряются снимок, размер сохранения и операции при 10 000 стеках и 2 000 заказах.
|
||||
@@ -13,8 +13,30 @@
|
||||
5. Ввести выбор совместимых модулей при создании мира и сохранить их версии и контрольные суммы. Определить контракт явного состояния скрипта и атомарного применения его предложений в [S19](../systems/S19.md). Внутренний сценарий с двумя клиентами проверяет общую поверхность команд до публичного кооператива M09.
|
||||
6. Для механизмов потоков, бинарной записи и тестов проверить существующие возможности VoidLibrary по [матрице](../void-library.md). Для отсутствующей возможности найти или создать issue в Void/Library и привязать к локальной реализации. Конкретный API выбирать по проверенной версии библиотеки.
|
||||
|
||||
## Приёмка реализации M01
|
||||
|
||||
В Windows x64 Release `4bac17d` под Wine 11 прошли все пять исполняемых наборов. Они охватили 182 теста ядра, 17 LAN, 15 клиентского сеанса, 6 проверок управления заказами и отдельный тест окна Direct3D. В последовательном режиме и на 2, 6 и 12 исполнителях два контрольных файла прежнего прототипа совпали побайтово. Потактный тест современной партии также сравнивает владельцев стеков, резервы, идентификаторы передач, квитанции и балансы. В 24 запусках с перестановкой завершений результат совпал с эталоном. [Испытания воспроизведения](../../../tests/replay_tests.cpp) · [Независимая проверка](../../agent-workflow/tasks/M01-V15.md)
|
||||
|
||||
Сохранение в пути, отмена заказа и возврат части груза прошли через рабочее меню и авторитетный диспетчер. Формат контрольной точки 3 восстанавливает имущество и незавершённые работы. Для 13 подлинных сохранений формата 2 проверены следующие 80 тактов на каждой из четырёх конфигураций исполнения. В отдельном опыте остановили гостевой приказ между чтением снимка и постановкой в очередь. После несовместимой отмены на хосте номер приказа гостя и состояние мира сохранились. При обратном порядке ранее принятый приказ завершился. Первоначальная и новая сборки сыграли по протоколу 11 в обеих ролях. [Фикстуры прежних сохранений](../../../tests/fixtures/custody_v14/README.md) · [Проверка имущества и кодека](../../agent-workflow/tasks/M01-V14.md) · [Условный допуск в VoidLibrary](https://git.faumaray.com/Void/Library/issues/16)
|
||||
|
||||
Два профиля рецепта кровати проверены через настоящие элементы управления в отдельных процессах. Камера работала во время задержанной записи и незаконченного такта. Воспроизведены загрузка предыдущего состояния и отказ при повреждённом файле. Эти результаты подтверждают программные условия выхода в M02. Нативный прогон Windows, физическая сеть и измерение частоты кадров на целевом ПК ещё предстоят. [Кадр и пользовательский интерфейс](../../agent-workflow/tasks/M01-V13.md) · [Ветка этапа](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/6)
|
||||
|
||||
## Первый переход с текущего клиента
|
||||
|
||||
### Потактный эталон прототипа
|
||||
|
||||
Для контрольного прогона мир создаётся с одним логическим исполнителем и `settlement::ExecutionMode::SerialReference`. Этот режим выполняет расчёт выбора работ, поиск пути и движение в вызывающем потоке. Сначала все свободные жители выбирают задание по одному состоянию, затем мир разбирает совпадающие заявки в порядке жителей. Обычный конструктор и загрузчик по умолчанию используют пул с 2–64 рабочими потоками. Конфигурацию исполнения выбирает клиент при создании или чтении мира. Один файл сохранения подходит для обоих вариантов. [Интерфейс мира](../../../engine/include/settlement/core/world.hpp)
|
||||
|
||||
Из корня репозитория после сборки Windows запустить `build\settlement_core_tests.exe --tag replay`. Журнал теста задаёт номера команд и попытки шага, поэтому может снять паузу даже тогда, когда номер такта остановился. Проверка сравнивает квитанции команд и полные байты сохранения по мере продвижения мира. Непрерывная партия задаёт ожидаемый результат для загруженной копии. [Исполняемые сценарии](../../../tests/replay_tests.cpp)
|
||||
|
||||
Этот срез открывает разработку M01. Фиксированный такт вне окна, неизменяемые снимки для клиентов, инкарнация после загрузки и идемпотентный результат повтора требуют отдельных изменений. Для замены пула остаются проверки переполнения, частичного запуска, времени жизни захваченных данных при отказе и стоимости работы на малом и нагруженном мире. [Проверка VoidLibrary](../void-library.md)
|
||||
|
||||
### Переход к авторитетному такту
|
||||
|
||||
Ядро выполняет такты по 50 мс в отдельном потоке. На каждой завершённой границе `SimulationRuntime` публикует независимый снимок и квитанции приказов. Пока идёт новый такт, читатели могут продолжать работу с прежней версией. Остановка игрового времени сохраняет возможность отдать приказ. Результат загрузки заменяет мир после повторной проверки номера запроса и инкарнации, в том числе при откате того же сохранения. [Интерфейс владельца](../../../engine/include/settlement/core/simulation_runtime.hpp) · [Тесты такта и отказов](../../../tests/runtime_tests.cpp)
|
||||
|
||||
Селектор `--tag runtime` под Wine выполнил десять проверок. Среди них — 20 тактов за секунду ручных часов, чтение предыдущего снимка при задержанном рабочем задании и возврат к управляемой партии после отказа публикации. Независимая проверка и общая сборка охватили 92 случая ядра и 4 LAN. Дальнейшая приёмка M01 проверяет действия игрока через окно, обмен со старым LAN-клиентом и постоянные ссылки при удалении объектов. [Техническая проверка](../../agent-workflow/tasks/M01-V7.md)
|
||||
|
||||
Выделить одну воспроизводимую партию прототипа и записать последовательность приказов. Сначала пропустить её через очередь авторитетного мира и дать окну читать последний завершённый снимок. Далее заменить один участок независимого расчёта, сверить результат каждого такта, затем подключить следующий. Так первое расхождение привязано к конкретной стадии. Для суммы запасов, состояния задания и номера команды выводить в отчёт также идентификатор первого отличающегося объекта.
|
||||
|
||||
Проверить для нынешнего `WorkerPool` исполнителя `Void::Async::ThreadExecutor` с `FuturePool`. На частичном отказе запуска уже созданные потоки должны штатно завершиться. При заполненной очереди логическая работа остаётся в такте до исполнения. При одновременных заявках на предмет ожидаемый победитель определяется правилами арбитража. Доступность API и управляемое воспроизведение отказов записать до удаления прежнего пути. Эталонный последовательный исполнитель — новый тестовый режим. Исторический тест, отклоняющий конфигурацию с одним рабочим потоком, остаётся свидетельством поведения прототипа.
|
||||
|
||||
@@ -22,9 +22,28 @@
|
||||
|
||||
## Проверки и выход
|
||||
|
||||
### Контракты первой реализации
|
||||
|
||||
Воксели имеют знаковые 32-битные координаты, высота растёт по оси `z`. Границы конечного региона задаются полуинтервалами с 64-битными концами, чтобы в них можно было включить последний положительный воксель. Чанк содержит 32³ ячеек; быстрее всего меняется индекс `x`. Отдельные результаты чтения обозначают воздух, недоступный чанк и координату за пределами региона. Генератор получает версию, seed и абсолютные координаты. Порядок подготовки страниц не влияет на материал.
|
||||
|
||||
Снимок региона разделяет неизменяемые страницы. Операция проверяет все ожидаемые ревизии, размер и бюджет до публикации. Пустая операция или запись прежнего материала сохраняет ревизию после проверки ожиданий. Дублированная координата отклоняет весь запрос. Изменение на грани оповещает соседний чанк, сохраняя его собственную ревизию материала. Реализация и проверки замены библиотечным API связаны с задачами о [знаковых координатах](https://git.faumaray.com/Void/Library/issues/11), [транзакциях страниц](https://git.faumaray.com/Void/Library/issues/14) и [зависимостях по ревизиям](https://git.faumaray.com/Void/Library/issues/13).
|
||||
|
||||
Житель занимает одну клетку в плане и две по высоте, поднимается на одну ступень. Поиск учитывает опору, свободное место для головы, дверь и соседние чанки, включая чтения, из-за которых путь не найден. Перед очередным перемещением житель перепроверяет переход. Удаление следующей ступени сохраняет его собственную позицию, груз и цель. Поиск через ещё не подготовленный чанк либо за пределами бюджета имеет отдельный результат.
|
||||
|
||||
Добыча создаёт авторитетный заказ с доступной соседней рабочей позицией. При завершении мир заранее проверяет правку и возможность зачислить материал по правилам S06. Удаление грунта и передача добычи выполняются одной операцией. Если для добычи нет места, заказ ждёт с указанием причины. Повтор принятой команды находит исходный заказ. Режим тестовой колонии имеет собственный манифест с версией генератора и определениями материалов.
|
||||
|
||||
Координатор принимает подготовленные чанки на назначенной границе такта в порядке координат. Во время ожидания он обслуживает загрузку и завершение программы. В сохранение попадают требуемые чанки, назначения работ и безопасная позиция после правки. Прежние колонии сохраняют прежнюю геометрию на высоте ноль. Форматы нового региона согласуются с подтверждённой версией сохранений M01. Текущий шейдер уже проецирует высоту `z`; луч выбора и видимый срез должны пользоваться той же проекцией. [Проектирование](../../agent-workflow/tasks/M02-P1.md) · [Проверка контрактов](../../agent-workflow/tasks/M02-F1.md)
|
||||
|
||||
- Житель проходит через вход, поднимается и работает на верхнем этаже. Закрытая стена не считается проходом. После перекрытия маршрута он строит обход либо показывает недоступность.
|
||||
- Игрок выкапывает тоннель и изменяет опору у края чанка. Геометрия, выбор мышью и проход согласованы с обеих сторон границы после сохранения и загрузки.
|
||||
- При перестановке порядка чтения и генерации журнал команд создаёт одинаковое состояние на каждом такте. Повреждённые данные не публикуются как загруженный чанк.
|
||||
- Сценарий работает на Windows x64, а его составляющие доступны для строительства и снабжения в [M03](M03.md).
|
||||
|
||||
[Мастер-план](../../../PLAN.md) · [Паритет](../parity.md) · [VoidLibrary](../void-library.md)
|
||||
|
||||
## Проверенный каталог и навигация
|
||||
|
||||
В `1ca481b` каталог S02 публикует только целые правки. Из 256 исходных страниц при изменении одной клетки переиспользуются 255. Отдельная программа по очереди внесла 18 отказов выделения памяти и сравнила исходные данные после каждого отказа. В `2017e56` поиск S03 фиксирует также прочитанные недоступные страницы. При поиске рабочей позиции он различает замкнутую стеной область, недостающий проход и выход за край исследованного окна. Узкое окно в контрольном примере исчерпывает границу; расширение на две клетки находит доступ к материалу. [Каталог S02](../systems/S02.md) · [Маршруты S03](../systems/S03.md)
|
||||
|
||||
Обе системы с окончательной версией M01 проверены в `14987b2`. Сборка Windows x64 GCC 16.2 под Wine 11 прошла все пять наборов CTest, в том числе 14 проверок каталога и 14 навигации. В следующих изменениях M02 реальный житель получает задание на добычу, владеет извлечённым камнем до доставки, а игрок выбирает высоту и клетку в окне. Состояние рельефа и незаконченной работы получает версионное представление в сохранении. [Проверка исходного кода](../../agent-workflow/tasks/M02-V1.md) · [Контракты интеграции](../../agent-workflow/tasks/M02-F2.md)
|
||||
В совместной сборке `129d7f2` видимая поверхность и выбор лучом используют одну проекцию с высотой `z`. При открытой двери пиксель соответствует более далёкому блоку, а недоступная страница перекрывает выбор. На 16 страницах генератора из 6 528 проверенных ячеек получились 1 998 граней. Запись старого кадра осталась доступной после отказа по бюджету. Проверены 15 случаев слоя и все шесть наборов CTest под Wine, включая чтение реальных пикселей WARP. [Визуализация S17](../systems/S17.md) · [Независимая проверка](../../agent-workflow/tasks/M02-V2.md)
|
||||
@@ -57,8 +57,30 @@
|
||||
|
||||
Первый пакет имеет одного владельца контрактов времени, ID и публикации. После закрепления интерфейсов отдельные исполнители берут адаптацию навигации, экономики и клиента с раздельными файлами. Интеграционный тест проверяет целый такт.
|
||||
|
||||
## Неизменяемый снимок M01
|
||||
|
||||
`World::capture() const` возвращает `std::shared_ptr<const World>`. Владелец вызывает его после завершения всех заданий стадии. Логические поля мира и доступные читателю счётчики находятся в едином копируемом `detail::WorldState`. Снимок владеет отдельными контейнерами жителей, запасов, маршрутов, работ и резервов. Конфигурация числа исполнителей остаётся доступной читателю. Пул, обратные вызовы исполнителя и восстанавливаемый кэш маршрутов принадлежат рабочему миру. Ошибка выделения памяти передаётся владельцу. [Интерфейс и данные](../../../engine/include/settlement/core/world.hpp) · [Копирование](../../../engine/src/world.cpp)
|
||||
|
||||
Четыре проверки `settlement_core_tests.exe --tag snapshot` прошли в Windows x64 Release под Wine. Они проверяют копии в эталоне и на 2/6 потоках, удержание данных при дальнейшем развитии и уничтожении исходного мира, паузу с материалом в руках, вложенные маршруты и резервы, чтение из второго потока и освобождение обратных вызовов вместе с рабочим миром. Полный прогон дал 46 случаев ядра и 4 LAN, включая формат сохранения 13 и протокол 11. [Проверки снимков](../../../tests/snapshot_tests.cpp)
|
||||
|
||||
Для сцены из существующего `benchmarks/colony.cpp` на карте 80 × 80 с шестью потоками выполнены три прогона для 50 и 500 жителей. После 32 тактов прогрева снимок создавался после каждого из 240 тактов. Измерение охватывает выделение и копирование в `capture()`. Чтение снимка и освобождение ссылки выполнялись за пределами интервала. Медианы трёх p50/p95 составили 2/4 мкс для 50 жителей и 23/68 мкс для 500. Отдельные p95 составили 4, 7 и 4 мкс, затем 68, 81 и 67 мкс. Это измерение кросс-сборки GCC 16.2.0 под Wine 11.
|
||||
|
||||
Общая библиотечная публикация неизменяемого состояния отслеживается в Void/Library. Переход на неё требует проверок удержания старой версии, независимости от изменяемого источника, согласованной версии и освобождения читателей при остановке. Игровое копирование выполняет `World::capture()`. [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5)
|
||||
|
||||
## Приёмка
|
||||
|
||||
В срезе S01-04 `SimulationRuntime` владеет изменяемым миром в отдельном потоке Void. Шаг соответствует 50 мс монотонных часов. Очередь допускает по умолчанию 256 операций вместе с исполняемой, а перегрузка возвращает `Busy`. После каждой операции владелец может выполнить один просроченный такт, сохраняя обслуживание команд. Пауза мира и остановка тактов из-за меню имеют отдельные состояния. При продолжении отсчёт начинается заново. [Интерфейс владельца](../../../engine/include/settlement/core/simulation_runtime.hpp)
|
||||
|
||||
Публикация содержит UUID мира и инкарнации, ревизию, неизменяемые мир и правила, следующие номера запросов двух клиентов. `latest()` возвращает последний завершённый снимок, а `snapshot_for_save()` дополнительно проверяет рабочее состояние владельца. Читатель может удерживать предыдущие поколения, поэтому потребление памяти зависит от числа таких ссылок. Новая команда подготавливает копию журнала квитанций. Потактное продвижение и точные повторы используют уже опубликованный журнал.
|
||||
|
||||
Исключение при такте, команде или подготовке публикации переводит владельца в `Faulted`. Предыдущий снимок и завершённые квитанции доступны для чтения, новые изменения получают ошибку. Восстановление требует подходящего кандидата загрузки. `begin_load()` фиксирует текущую инкарнацию и номер запроса, который проверяется повторно непосредственно при переключении мира. Более новый запрос отменяет публикацию старого кандидата. Каждая успешная загрузка создаёт новую инкарнацию, в том числе при откате того же мира.
|
||||
|
||||
Регрессии `--tag runtime` проверяют 20 тактов в секунду с управляемыми часами и эталон на 1/2/6/12 исполнителях, команды на паузе, чтение во время заблокированной задачи, отказы и восстановление, порядок загрузок, переполнение очереди и завершение принятых операций при выходе. Подключение окна к этому интерфейсу выполняется отдельным срезом. [Проверки владельца](../../../tests/runtime_tests.cpp)
|
||||
|
||||
На ветке `system/s01-simulation` три параллельные стадии мира используют закреплённые `Void::Async::ThreadExecutor` и `FuturePool`. При заполнении лимита координатор выполняет задание сам. Стадия дожидается ранее принятых заданий и при исключении. Последовательный эталон вызывает те же игровые операции. На журнале из 750 тактов канонические сохранения после каждого такта совпали у эталона и вариантов с 2, 6 и 12 потоками, в том числе при лимите одного задания и после загрузки в процессе переноски. [Исполнитель](../../../engine/include/settlement/core/worker_pool.hpp) · [Проверки отказов](../../../tests/executor_tests.cpp) · [Воспроизведение](../../../tests/replay_tests.cpp)
|
||||
|
||||
В Windows x64-сборках под Wine при шести потоках медиана измерений p95 такта при переходе на Void изменилась с 86 до 96 мкс для 50 жителей и с 407 до 333 мкс для 500. Нативные замеры Windows, неизменяемая публикация завершённого такта и восстановление после ошибки остаются отдельными проверками.
|
||||
|
||||
- Сравнить хеш каждого такта на последовательном эталоне и 2/6/12 потоках, включая одинаковые команды и сохранение внутри стройки.
|
||||
- Задержать выбранные задачи, завершить их в обратном порядке, отменить мир во время расчёта. Новое поколение принимает только свои результаты.
|
||||
- Инъецировать ошибку в середину стадии. Опубликованное состояние остаётся последним завершённым тактом, предметы и резервы согласованы.
|
||||
|
||||
@@ -10,6 +10,34 @@
|
||||
|
||||
## Данные и ответственность
|
||||
|
||||
### Исполняемая основа ограниченного региона
|
||||
|
||||
`VoxelRegion` хранит ненулевой ID, seed, версию генератора и границы. Ячейки имеют знаковые координаты `int32`, а концы полуинтервалов используют `int64`, включая верхнюю границу `INT32_MAX + 1`. Деление на размер чанка округляет вниз, поэтому координата −1 попадает в чанк −1 и локальную ячейку 31. Индекс внутри страницы вычисляется как `x + 32 * (y + 32 * z)`. Результат `sample()` различает загруженный воздух, недоступную страницу и выход за границы. [Публичный контракт](../../../engine/include/settlement/core/voxel_region.hpp) · [Реализация](../../../engine/src/voxel_region.cpp)
|
||||
|
||||
Копия региона разделяет каталог и страницы через неизменяемые объекты. `directory()` возвращает владеющую ссылку на прежний каталог. Изменение создаёт новый каталог и копирует затронутые страницы. Срок жизни снимка охватывает все его материалы. Номер региона и `ChunkStamp` связывают чтение с состоянием доступности и ревизией страницы. Владелец мира дополнительно проверяет инкарнацию сеанса при загрузке партии.
|
||||
|
||||
`prepare_generated()` независимо готовит страницу генератора 1. Он кодирует seed, версию и координаты опорных столбцов в little-endian через `Void::Binary::Writer`, затем использует FNV-1a из `Void::Hash`. Интерполяция сетки с шагом 16 даёт высоты от −8 до 8. Верхние три слоя состоят из почвы, нижние — из камня. Соседние столбцы по горизонтальной оси отличаются по высоте максимум на одну ячейку. Область вне частичного чанка заполнена воздухом. Для seed 42 чанк (−1, −1, −1) имеет FNV-1a `13302332479434111011`; этот результат отдельно воспроизведён по закодированным полям. Подготовка не меняет каталог региона.
|
||||
|
||||
`prepare_restored()` проверяет полный размер страницы, ненулевую ревизию, материалы и воздух за границами, затем копирует данные вызывающего кода. `activate()` принимает весь набор подготовленных страниц одной операцией. Она проверяет точный дескриптор региона, дубликаты, бюджет и отсутствие уже опубликованной страницы. `edit()` проверяет ожидаемую ревизию каждой ячейки, даже если материал уже совпадает. Повтор координаты отклоняет весь запрос. Пустая и тождественная запись сохраняют ревизии. Исчерпанная ревизия запрещает изменение страницы. Все новые страницы, каталог и результат готовятся до публикации. При отказе прежние указатели, материалы и ревизии сохраняются.
|
||||
|
||||
Список изменённых чанков упорядочен по координатам `x,y,z`; список ячеек — по мировым координатам. Правка на грани добавляет пересекающего регион соседа в `dirty_chunks`. Это касается и недоступных соседей. Диагонали не включаются. Неизменившийся сосед сохраняет свою ревизию материала. Активация страницы оповещает все её соседние грани. Выгрузка страниц появится с отдельным контрактом сохранения их ревизий.
|
||||
|
||||
| Материал | Значение | Проход | Опора |
|
||||
| --- | --- | --- | --- |
|
||||
| Воздух | 0 | Свободен | Нет |
|
||||
| Почва | 1 | Занят | Есть |
|
||||
| Камень | 2 | Занят | Есть |
|
||||
| Закрытая дверь | 3 | Занят | Нет |
|
||||
| Открытая дверь | 4 | Свободен | Нет |
|
||||
|
||||
Навигация и изображение используют общие `voxel_blocks_passage()` и `voxel_provides_support()`. Генератор создаёт природные материалы. Игровая команда определяет право изменить дверь и обновляет обе её ячейки одной операцией, в том числе через границу страниц.
|
||||
|
||||
По умолчанию разрешены 256 страниц и 4096 ячеек в запросе. Лимиты полезных данных резидентного региона и одной транзакции равны 16 МиБ каждый. Проверяемая арифметика учитывает объекты страниц, каталог, сортируемый запрос, временную страницу и массивы результата до их выделения. На проверенной Windows x64-сборке страница занимает 32 776 байтов, запись каталога — 32 байта, каталог с 256 страницами — 8 398 872 байта. Служебные данные распределителя, подготовленные страницы и старые снимки, удерживаемые потребителями, имеют отдельный расход памяти. Будущий владелец ограничивает число таких потребителей.
|
||||
|
||||
Проверки `--tag voxel-region` покрывают отрицательные и предельные координаты, частичные страницы, порядок завершения настоящих задач на 2/6/12 исполнителях, границы двери, загрузку, точный отказ целого набора и неизменяемые снимки. На заполненном каталоге правка одной ячейки сохранила прежние 255 страниц. Отдельная программа по очереди вызвала отказ каждого выделения памяти при генерации, восстановлении, активации и правке двух страниц; все отказы сохранили прежний каталог. Переход на библиотечную реализацию должен повторить эти проверки. [Тесты региона](../../../tests/voxel_region_tests.cpp) · [Знаковая арифметика в VoidLibrary](https://git.faumaray.com/Void/Library/issues/11) · [Атомарные страницы в VoidLibrary](https://git.faumaray.com/Void/Library/issues/14)
|
||||
|
||||
Windows x64 Release с GCC 16.2 под Wine 11 прошла 14 проверок региона и весь CTest — 155 тестов ядра, 9 LAN, 14 клиента и испытание кадра с видимым D3D11 и WARP. В одном прогоне подготовка и активация 256 страниц заняли 57 917 мкс, правка одной ячейки — 11 мкс. Это измерение относится к данному прогону под Wine. Нативная Windows и аппаратная частота кадров ещё не проверены.
|
||||
|
||||
| Новый контракт | Содержимое и владелец |
|
||||
| --- | --- |
|
||||
| Позиция мира | Постоянный ID региона и знаковые целочисленные координаты вокселя. Вертикальная ось — `z`, горизонтальная плоскость — `x,y`. |
|
||||
|
||||
@@ -8,6 +8,34 @@
|
||||
|
||||
В прототипе есть A*, фиксированный порядок соседей и кэш запросов. Изменение проходимости инвалидирует маршруты. Тесты проверяют проход через отверстие в стене и открытие ранее недоступной шахты. Карта использует двумерную позицию, а маршрут хранится последовательностью клеток внутри жителя. [Мир](../../../engine/src/world.cpp) · [Типы](../../../engine/include/settlement/core/world.hpp) · [Тесты маршрутов](../../../tests/core_tests.cpp)
|
||||
|
||||
## Первый исполняемый срез M02
|
||||
|
||||
Модуль `voxel_navigation` работает с неизменяемым `VoxelRegion`. `voxel_standing` проверяет опору, клетку ног и клетку головы. `voxel_transition` использует те же проверки для одного горизонтального перехода с подъёмом или спуском на одну клетку. При изменении высоты дополнительно проверяется объём, через который проходит голова. Закрытая дверь препятствует движению, открытая дверь допускает проход. Земля и камень предоставляют опору. [Интерфейс](../../../engine/include/settlement/core/voxel_navigation.hpp) · [Реализация](../../../engine/src/voxel_navigation.cpp)
|
||||
|
||||
`find_voxel_path` получает ID региона, UUID текущей инкарнации, старт, множество целей и явное окно поиска. Путь содержит очередные позиции после старта. Его стоимость равна числу переходов. При равной стоимости выбирается первая цель в порядке координат, соседи каждой позиции перечисляются в том же порядке. Поиск использует `Void::Algorithms::bfs` из закреплённой версии библиотеки. Множество вершин относится к заданному окну, список соседей вычисляется по запросу. До выделения массивов проверяется полный размер окна. Разреженный регион с большой протяжённостью требует меньшего окна для конкретной задачи.
|
||||
|
||||
`find_voxel_interaction_path` строит доступные позиции контакта с указанной клеткой. К ней должна примыкать грань тела жителя. Цель может находиться у ног, у головы, под ногами или непосредственно над головой. Цель должна быть загружена. Право добывать материал, менять дверь и удалять опору проверяет владелец работы. Выбранная позиция взаимодействия и следующий переход доступны для повторной проверки перед действием.
|
||||
|
||||
Позиции контакта за пределами окна поиска сохраняются для проверки отрицательного ответа. Если такой контакт допускает размещение жителя, достигнутый допустимый выход из окна даёт `SearchBoundary`, а достигнутый неопределённый переход требует загрузки данных. При известном отсутствии выхода результат остаётся `Unreachable`. Заблокированные контакты внутри окна не доказывают недоступность всех внешних позиций. Общий предел целей учитывает и пропущенные контакты.
|
||||
|
||||
Каждый ответ содержит `VoxelReadSet` с ID региона, инкарнацией и упорядоченными уникальными ревизиями прочитанных чанков. В набор входят опора, свободное место над головой, заблокированные соседи и недоступные страницы. `current` проверяет тот же сеанс и все эти ревизии. Загрузка недоступной страницы делает прежний отрицательный ответ устаревшим. Правка непрочитанного чанка сохраняет ответ пригодным. Сам ответ и его маршрут удерживают собственные данные. Для замены локального набора библиотечным повторить проверки опоры через границу чанка, открытия прохода, загрузки страницы и смены инкарнации. [Void/Library #13](https://git.faumaray.com/Void/Library/issues/13)
|
||||
|
||||
Найденный путь является кратчайшим среди известных переходов в заданном окне. Отрицательный ответ различает доказанную недоступность, недостающие данные и возможность выхода за границу окна. Отдельные результаты обозначают исчерпание бюджета, отмену, неверный запрос и отказ выделения памяти. До быстрого случая совпавших старта и цели проверяется геометрия тела. Применяющий результат код должен проверять и его статус, и актуальность набора чтений.
|
||||
|
||||
Недостающие данные требуют ожидания, когда они могут продолжить путь из уже достигнутой позиции. Известная сплошная стена или занятая клетка ног окончательно запрещает переход, даже если его проверка прочитала недоступную опору. Прочитанные ревизии сохраняются в ответе. Недоступная цель за доказанно непроходимой стеной сама по себе не создаёт достижимый проход. Выход за окно учитывается после проверки допустимого перехода через его границу.
|
||||
|
||||
Пределы по умолчанию составляют 65 536 вершин, 1 000 000 шагов алгоритма, 4 000 000 чтений клеток, 64 цели, 4096 ревизий и 8 МиБ рабочих данных. Бюджет учитывает четыре массива `size_t` и посещённость из Void BFS, собираемый маршрут и зарезервированный набор ревизий. Список соседей из 12 элементов находится в стеке. Владелец сохраняет входные данные запроса и страницы мира отдельно. Измерение памяти распределителя и принудительный отказ системного распределителя остаются отдельными проверками.
|
||||
|
||||
Ёмкости проверяются также против `vector::max_size()`. Непредставимая ёмкость возвращает `LimitExceeded` через каждую из четырёх публичных операций. Проверка с `max_dependencies = max_size() + 1` и максимальным байтовым бюджетом воспроизводит этот отказ без выделения указанной памяти.
|
||||
|
||||
Селектор `--tag voxel-navigation` проверяет двухклеточную дверь, ступени на границе `x=31/32` и работу наверху, удаление следующей опоры, прежний неизменяемый снимок, место для головы, недоступную опору через отрицательную границу по высоте, постороннюю правку, смену сеанса и предельные координаты. Стоимости сравниваются с независимым полным обходом 16 малых плоских карт. Запросы в настоящем пуле с 2, 6 и 12 потоками дают те же маршруты и ревизии. [Проверки](../../../tests/voxel_navigation_tests.cpp)
|
||||
|
||||
На совместной базе S02 `e7046a9` сборка Windows x64 GCC 16.2 и все десять проверок навигации прошли под Wine 11. Полный `ctest -V` прошёл четыре набора с 165 случаями ядра, 9 LAN, 14 клиента и испытанием кадра с видимой цепочкой D3D11 и WARP. Проверка заняла 4,66 с. Нативная Windows и связь навигации с исполнением работ в `World` проверяются при последующей интеграции M02.
|
||||
|
||||
Проверка замечаний к `7a7ff32` воспроизвела ожидание отсутствующей страницы под сплошным полом и исключение `vector::reserve` при непредставимой ёмкости. После исправления прошли 13 проверок навигации и четыре полных набора с 168 случаями ядра, 9 LAN, 14 клиента и испытанием кадра за 4,61 с. Отдельно проверены недоступная цель за известной стеной, загруженная цель взаимодействия за ней, запрещённый переход за границу окна и настоящий ожидающий загрузки проход. Один предыдущий полный прогон встретил прежнюю проверку немедленного допуска при восстановлении клиента после сбоя, `viewer_session_tests.cpp:363`. Повтор этого набора и итоговый полный прогон прошли. Проверяемый файл клиента в этом срезе не изменялся.
|
||||
|
||||
Проверка замечания к `17389b2` воспроизвела ложную недоступность при единственном пригодном контакте за границей окна. После исправления узкое окно возвращает `SearchBoundary`, расширенное достигает той же позиции контакта. Изолированный старт и незагруженный проход проверены отдельно. Под Wine прошли 14 проверок навигации и полный `ctest -V` с блокировкой общего интерактивного окружения. Все четыре набора прошли, включая 169 случаев ядра, 9 LAN, 14 клиента и испытание кадра за 4,74 с.
|
||||
|
||||
## Пространственная модель
|
||||
|
||||
Позицию и материал предоставляет [S02](S02.md). Профиль движения определяет объём тела, высоту шага и разрешённые переходы. Для M02 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками.
|
||||
|
||||
@@ -6,7 +6,33 @@
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. В ссылках на материалы и остановки используются индексы контейнеров. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
|
||||
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. Материалы и остановки хранят `StorageId`, источники — `ResourceNodeId`, назначения производства — `ProductionId`. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
|
||||
|
||||
## Реализованный срез S04-01: идентичность производства
|
||||
|
||||
У `ProductionOrder` появился постоянный `ProductionId`, а житель хранит `production_id` (`0` означает отсутствие назначения). Единственный счётчик `next_production_id_` входит в копируемое состояние мира. Заказы остаются отсортированными по ID, поиск выполняется через `lower_bound`; удаление нижнего заказа не требует исправлять ссылки жителей. Присвоенный ID не меняется в течение жизни заказа.
|
||||
|
||||
Все вставки, включая обстановку и клетки комнаты, проходят общий метод. До первого изменения проверяются ID и вместимость вектора для всей группы: кровать, ткацкий станок, комната с мебелью, дом и замещающие столярные заказы при сносе склада. Снос вычисляет нехватку каждого затронутого изделия по запасам **после** предполагаемого удаления, учитывая другие склады и уже существующие заказы, затем резервирует всю группу. Недостаток ID возвращает `Busy` без потери запасов, изменения заказов или номера команды. Последний выдаваемый ID — `UINT64_MAX - 1`; `UINT64_MAX` остаётся допустимым исчерпанным счётчиком. Прямой `queue_cabin` сообщает такую проверенную до изменений нехватку через `ProductionCapacityError`; диспетчер сохраняет повторяемый результат `Completed/Busy`, а runtime продолжает принимать команды.
|
||||
|
||||
`World::write_save(stream)` сохраняет прежний формат 13 и позиционные ссылки для совместимости, включая LAN 11. Явный `WorldSaveFormat::Current14` записывает настоящие ID производства, складов и источников, а также следующий ID производства. Новые checkpoint используют внешнюю схему 2 и тело 14. Схема 1 принимает тела 1–13; несовместимые пары отклоняются даже при корректных контрольных суммах. Импорт старого тела назначает производству ID по порядку записей; современные сохранения сохраняют историю выдачи после удаления последнего, максимального или всех заказов. Чтение проверяет ненулевые упорядоченные ID, следующий ID и ссылки до разыменования; новые проверки не добавляют квадратичный поиск.
|
||||
|
||||
Используются закреплённые `Void::Numeric::checked_add`, Binary и Crypto из `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. Отдельного библиотечного восстанавливаемого генератора ID пока нет: [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Локальную проверку и продвижение счётчика в `World::reserve_production` / `append_production` можно заменить после подтверждения того же поведения на Windows x64, включая групповую проверку и исчерпание.
|
||||
|
||||
Проверки: [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 и причину ожидания возвращающегося жителя. Каждый запуск окна использует отдельный временный каталог пользовательских данных.
|
||||
|
||||
Полный `ctest -V` для Windows x64 GCC 16.2 под Wine 11 выполнил 160 тестов ядра, 9 LAN, 14 клиентских сеансов и 6 проверок управления в настоящем окне. В одном предыдущем прогоне тест восстановления после сбоя получил временный отказ при попытке синхронизации. Ветка S18 добавила ограниченное ожидание допуска. После этой правки клиентский набор прошёл 24 раза подряд. На физической Windows и под MSVC эти проверки ещё предстоят.
|
||||
|
||||
## Данные и владение
|
||||
|
||||
|
||||
@@ -60,6 +60,22 @@ S06 владеет фактическими количествами, содер
|
||||
|
||||
## VoidLibrary и приёмка
|
||||
|
||||
[Контракт имущества M01](../custody.md) описывает владение при подборе и сдаче, возврат материалов, повтор операции и перенос старых сохранений.
|
||||
|
||||
Первый срез M01 хранит в жителях, требованиях материалов и остановках доставки постоянные `ResourceNodeId` и `StorageId`. Ноль означает отсутствие ссылки. Удаление более раннего склада или узла сохраняет цель активной работы. Списки объектов упорядочены по ID, чтение использует двоичный поиск. Формат 13 продолжает хранить прежние позиции. Загрузчик удерживает их во временном буфере, проверяет порядок ID и переводит в постоянные ссылки до проверки состояния мира. [Модель](../../../engine/include/settlement/core/world.hpp) · [Кодек](../../../engine/src/world_save.cpp)
|
||||
|
||||
Счётчик со значением `UINT64_MAX` обозначает исчерпание. Последний выдаваемый ID равен `UINT64_MAX - 1`. Фабрики и команды проверяют следующий ID через закреплённый `Void::Numeric::checked_add` до изменения объектов и геометрии. Фабрика сообщает `overflow_error`, команда возвращает `Busy` и сохраняет номер следующей команды. Общая возможность восстанавливаемого счётчика предложена в [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Переход на неё проверяется независимыми мирами, сохранением после удаления объектов и отказом у верхней границы.
|
||||
|
||||
Семь проверок `--tag identity` под Wine покрывают удаление более ранних объектов при переноске, доставку с двух складов, кладовую, засев без склада, готовую продукцию плотника, границы счётчиков и недопустимые старые ссылки. Загруженные копии продолжают совпадать потактно в последовательном режиме и на 2/6/12 потоках, включая контрольную точку с правилами и удерживаемый снимок. Постоянные ID производственных заказов, стеков, резервов и передач входят в последующие срезы. Для общего резервирования и переноса количеств зарегистрирован [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). [Исполняемые проверки](../../../tests/identity_tests.cpp)
|
||||
|
||||
Срез S06-02 переводит физическое получение еды и материалов одной остановки на `withdraw_reserved_materials`. Операция объединяет все строки текущего склада по типу, включая несмежные повторы; строки остальных остановок не участвуют. До первого изменения проверяются ненулевой ID склада, выбранные типы и положительные количества, существование отсортированных уникальных стеков, `reserved <= count`, достаточность резерва, вместимость и проверяемые суммы источника и личного инвентаря. Счётчик назначения может достичь ровно `UINT32_MAX`. Фиксированные массивы ограничены числом типов; получение не выделяет память, удаление нескольких опустевших стеков сохраняет порядок остальных. [Контракт операции](../../../engine/include/settlement/core/inventory_transaction.hpp) · [Реализация](../../../engine/src/inventory_transaction.cpp)
|
||||
|
||||
Плотник в той же операции резервирует место для результата на складе **первого ингредиента**, даже если этот склад посещается позже другой остановки. Проверка учитывает освобождающееся место; полный склад может обменять последнюю единицу сырья на одно зарезервированное место. При отказе не меняются количества, резерв места, остановка, маршрут и состояние жителя относительно входа в получение. Перед ним `World::step` уже мог продвинуть движение или потребности. Ошибка нарушенного предусловия поднимается владельцу симуляции; runtime сохраняет последнюю здоровую публикацию и блокирует сохранение повреждённого кандидата. Прямое преобразование сырья в продукт в `finish_production` остаётся отдельной операцией и не получает гарантию атомарного преобразования рецепта. Форматы 13, LAN 11 и Current14 не меняются. [Вызовы получения](../../../engine/src/world.cpp) · [Проверки `quantity-transfer`](../../../tests/quantity_transaction_tests.cpp)
|
||||
|
||||
В закреплённом Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` используется платформенно независимая `Void::Numeric::checked_add/checked_sub`; `Storage::Batch` относится к ключам движка хранения и не меняет игровые структуры в памяти. Локальный перенос связан с [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки позднего отказа всего набора, несмежных повторов, пределов арифметики, полного склада плотника и реальных еды/доставки/публикации на Windows x64, затем сравнить продолжения и старые байтовые эталоны. Этот срез не вводит ID стеков, резервов и передач, журнал или идемпотентность: повторное получение отсеивает существующий курсор остановки, а долговременный учёт владельца груза остаётся будущей работой S06-A/S04.
|
||||
|
||||
Проверка S06-02: сборка GCC 16.2 Windows x64 Release и запуск под Wine; 14/14 проверок `quantity-transfer`, полный CTest — 136/136 core и 9/9 LAN, включая современные сохранения и повтор на 1/2/6/12 исполнителях. Оба старых байтовых корпуса (`old-trajectory.bin`, `identity-compat-old.bin`) совпали с проекцией формата 13 на всех четырёх режимах. Нативный запуск Windows и MSVC отдельно не проверялись.
|
||||
|
||||
Применять существующие подходящие средства контейнеров, проверяемой арифметики, сериализации и результатов из [VoidLibrary](../void-library.md). Для отсутствующей возможности перед локальной реализацией найти либо создать issue в `Void/Library` и указать ссылку в задаче и коде.
|
||||
|
||||
- Два заказа запрашивают последнюю единицу ресурса. Только один получает резерв, свободный запас остаётся неотрицательным.
|
||||
@@ -68,3 +84,26 @@ 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`.
|
||||
|
||||
Дополнительная проверка кандидата Current15 требует уникальных ID резервов в порядке выдачи, в том числе в квитанциях уже завершённых исполнений. Результат завершения сначала объединяет строки материалов, которые относятся к одному окончательному `(владелец, StackId, ItemType)`: два склада с древесиной могут образовать один входной стек плотника. Одна итоговая запись сохраняет нулевой остаток расхода, отдельная — реальный результат у жителя. Повтор такой итоговой записи отклоняется независимо от указанного количества; одинаковый вид предмета у разных владельцев или разных стеков сам по себе не является повтором. Проверка ограничена восемью выданными резервами и одиннадцатью итоговыми записями.
|
||||
|
||||
Терминальная квитанция не может относиться к действующему исполнению, получению со склада или доставке на рабочую площадку. Задания с получением материалов переходят через `FetchingMaterials` и `Hauling`, затем в `Working`; обычный `Travelling` для них отклоняется, поскольку обходил бы получение. Дополнительные проверки используют реальные два склада плотника и пять источников хижины, точный повтор после загрузки и подписанные повреждённые контрольные точки S15. Сборка и полный CTest после этой коррекции: 167/167 core, 9/9 LAN, 10/10 viewer; отдельный `custody` — 17/17. Журналы этой проверки — `s06-custody-uniqueness-{build,focused,ctest}.log` в том же временном каталоге. Схема 15 остаётся неопубликованным кандидатом; старые опубликованные форматы не меняются.
|
||||
@@ -25,10 +25,38 @@
|
||||
|
||||
## Границы интерфейсов
|
||||
|
||||
`CheckpointFiles` обслуживает файлы вне потока окна. `try_save` удерживает опубликованный снимок и передаёт формирование контрольной точки единственному писателю с лимитом `max_checkpoint_bytes`. `try_load` возвращает номер запроса и future отдельного кандидата. Один ограниченный исполнитель чтения открывает файл один раз, проверяет размер и читает до конца под общим лимитом, включая рост файла после открытия. Ошибка современного формата сохраняет диагностику кодека. Импорт прежнего сохранения получает новый постоянный UUID и точный поддерживаемый набор правил из установленного каталога. [Интерфейс файлов](../../../engine/include/settlement/core/checkpoint_files.hpp) · [Проверки адаптера](../../../tests/checkpoint_file_tests.cpp)
|
||||
|
||||
Служба живёт до закрытия окна и завершает принятые чтения и записи при остановке. Окно связывает подготовку с `LoadTicket`, проверяет размеры карты и передаёт кандидат владельцу симуляции. Этот же владелец сверяет инкарнацию и последний запрос перед публикацией. Сценарии `--tag checkpoint-file` проверяют удерживаемый снимок при продвижении партии, прежние версии 1/8/9/13, диагностику несовместимых правил, рост файла, переполнение очереди, независимость писателя от задержанного чтения и завершение очереди при выходе.
|
||||
|
||||
Windows-адаптер чтения связан с [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). Условие перехода на библиотечную операцию — проверки чтения одним дескриптором до конца файла, путей Unicode, исходного размера и роста сверх лимита. Служба продолжает задавать ограничение приёма и владение запросом.
|
||||
|
||||
Контрольная точка версии 1 содержит постоянный UUID мира, город, такт, полный выбранный набор пакетов с точными версиями и SHA-256, а также состояние мира в формате 13. Декодер проверяет внешнюю контрольную сумму, заново разрешает набор правил по установленному каталогу и создаёт кандидат мира существующим проверенным загрузчиком. Клиенту доступны имя несовместимого пакета и поле ошибки. Восемь проверок под Wine охватывают переноску материалов, продолжение расчёта, перестановку каталога, обрезанные файлы, недопустимое состояние и тело размером более 16 МиБ. [Кодек контрольной точки](../../../engine/include/settlement/core/checkpoint.hpp) · [Проверки](../../../tests/checkpoint_tests.cpp)
|
||||
|
||||
`SaveRequest`, `SaveSnapshot`, `SaveManifest` и `LoadCandidate` — предлагаемые новые интерфейсы. Запрос содержит слот и желаемую операцию. Снимок привязан к одному завершённому такту. Манифест описывает все необходимые блоки и контрольные суммы. Кандидат загрузки предоставляет результат проверки до замены мира. Завершение операции возвращает идентификатор запроса, состояние и диагностическую причину ошибки.
|
||||
|
||||
При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md)
|
||||
|
||||
## Владение имуществом в версии 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 последующих тактов. Объединённый прогон `e348a42` на Windows x64 GCC 16.2 под Wine 11 подтвердил все такты на последовательном исполнителе и 2/6/12 потоках, точный экспорт 14, канонический цикл схемы 3 и продолжение после загрузки. Отдельно проверены отменённая одиночная доска и каменный блок, смешанный груз без места, частичный возврат, приостановленные кровать и станок, нулевой таймер, старые ссылки квитанций и отказ после аутентифицированного повреждения. [Проверки миграции](../../../tests/custody_migration_tests.cpp) · [Снимки с полной версией 15](../../../tests/snapshot_tests.cpp)
|
||||
|
||||
Итоговая проверка S15-04: 14/14 тестов миграции и аутентифицированных изменений прошли за 4,92 с; полный CTest — 3/3 цели, 169 основных, 9 сетевых и 10 клиентских проверок, за 9,57 с. Реальные 2050 заказов заполнили кольцо до 4096 результатов; проверены точный повтор, конфликт, вытеснение, устаревшие номера и каноническая перезапись кольца после загрузки. Дополнительные отрицательные случаи меняют терминальность действующего исполнения, фазу доставки, источник добычи, вместимость отменённого возврата и уникальность ID/эффектов квитанции, сохраняя согласованные вторичные счётчики и внешний SHA-256. Допустимые исторические ссылки на израсходованный стек, нулевой остаток и разные виды владельцев проходят тот же кодек. Полный протокол проверки находится в `s15-custody-final-build.log`, `s15-custody-final-migration.log` и `s15-custody-final-ctest.log` во внешнем каталоге верификации.
|
||||
|
||||
Универсальные части продолжают использовать закреплённые 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 и сохранность после отключения питания остаются отдельными проверками.
|
||||
|
||||
## Ошибки и восстановление
|
||||
|
||||
| Ситуация | Требуемое поведение |
|
||||
@@ -46,6 +74,10 @@
|
||||
|
||||
## Приёмка
|
||||
|
||||
Первый Windows-срез службы сохранений ставит в ограниченную очередь запись с удерживаемым снимком, тактом и инкарнацией. Единственный исполнитель формирует байты, создаёт временный файл рядом со слотом, записывает и сбрасывает данные, закрывает дескриптор и публикует замену. Результат отдельно сообщает о видимости нового файла и об ошибке очистки. Принятые записи завершаются в порядке приёма, включая несколько запросов в один слот. [Интерфейс](../../../engine/include/settlement/core/save_service.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/3)
|
||||
|
||||
Девять проверок `--tag save-slot` прошли в Windows x64 под Wine. Если во время замены читатель удерживал дескриптор с разрешением удаления, Wine вернул ошибку доступа 5. Служба сохранила прежние байты и удалила временный файл. Следующая запись после закрытия читателя успешно заменила слот. Нативная Windows и сохранность после потери питания требуют отдельной проверки. [Исполняемые проверки](../../../tests/save_service_tests.cpp)
|
||||
|
||||
- **S15-A01.** Сохранить демо при доставке на второй этаж. После загрузки сравнить сумки, склад, резервы и детали стройки, затем завершить дом без повторной оплаты материала.
|
||||
- **S15-A02.** Прервать запись после каждого блока и перед публикацией. Каждый запуск открывает целую предыдущую либо целую новую генерацию.
|
||||
- **S15-A03.** Воспроизвести один журнал в последовательном режиме и на 2, 6 и 12 потоках с задержанным чтением чанков. Канонические хеши совпадают на каждом такте.
|
||||
|
||||
@@ -47,6 +47,32 @@
|
||||
|
||||
## Приёмка
|
||||
|
||||
Клиент Windows может обслуживать хост через `LanSession::poll_host(SimulationRuntime&)`, а гостя — через `poll_guest()`. Хост читает опубликованный снимок и отправляет команду доверенного слота 2 владельцу мира. Сетевой опрос продолжает работу, пока симуляция завершает приказ. `take_result()` возвращает гостю результат вместе с исходными параметрами намерения. До чтения результата следующая команда гостя остаётся в ограниченной очереди. [Сетевой интерфейс](../../../app/lan_session.hpp)
|
||||
|
||||
Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается.
|
||||
|
||||
Проверка представимости фактического имущества выполняется до приёма соединения, перед каждым разобранным сообщением и перед отправкой, включая продолжение ранее поставленного снимка или квитанции. `World::legacy_representable()` проверяет игровой контракт без пробной сериализации. Если отменённый груз или приостановленная площадка не имеют точного представления в формате 13, адаптер закрывает гостя и очищает его буферы. Слушатель, современный владелец и принятая им работа сохраняются; готовая квитанция прежнего подключения не отправляется следующему гостю. При работе с фоновым владельцем каждое сообщение и отправка сверяют свежую публикацию и инкарнацию. Прежний `poll(World&)` применяет ту же проверку представимости.
|
||||
|
||||
Общий `ViewerSession::can_host_legacy()` разрешает создание слушателя только для опубликованной представимой активной колонии 32×32 с точными встроенными правилами, вне гостевого режима и смены партии. Это ограничение совместимости не блокирует современные команды и контрольные точки. Историческая активная колония с простым рецептом кровати и встроенным манифестом остаётся допустимой. [Контракт S16-03](../../agent-workflow/tasks/S16-03.md)
|
||||
|
||||
Проверка представимости снимка сама по себе не разрешает позднейший допуск команды. `SimulationRuntime::try_submit_if_current` сравнивает удержанную проверенную публикацию с текущей и проверяет рабочее состояние под тем же mutex, который защищает публикацию и постановку в очередь. Пустая ссылка получает `InvalidRequest`, нерабочий владелец — `Closed`, сменившаяся публикация — `StaleSnapshot`; конкуренция за mutex и заполненная очередь возвращают `Busy`. Сравнение публикаций предшествует проверке вместимости очереди. Внутри блокировки нет сканирования мира или сериализации. Обычный `try_submit` сохраняет прежний контракт. Уже допущенные операции не отзываются последующей публикацией.
|
||||
|
||||
Адаптер передаёт точную проверенную ссылку. При `StaleSnapshot` или `Busy` он заново проверяет текущую публикацию: несовместимое имущество, отказ владельца или другая инкарнация закрывают гостя и очищают буферы. Совместимое новое состояние возвращает честный `Busy` с актуальным прежним номером команды, чтобы гость мог повторить намерение. Цикла повторных допусков в сетевом опросе нет. Необязательный диагностический `LanSessionOptions::before_command_admission` позволяет остановить поток опроса ровно между проверкой и допуском, не удерживая блокировку владельца. [Контракт S16-04](../../agent-workflow/tasks/S16-04.md)
|
||||
|
||||
Общий контракт условного допуска отслеживается отдельно от публикации и журнала результатов в [Void/Library #16](https://git.faumaray.com/Void/Library/issues/16). Закреплённый `FuturePool::try_submit` проверяет лимит и остановку исполнителя, но не игровую публикацию. Условие замены локального допуска — сохранить точное сравнение удержанного снимка и постановку в ограниченную очередь одной критической секцией и повторить управляемую гонку: после проверки представимого S реальный владелец публикует несовместимое S+1 в той же инкарнации, затем гость пытается войти в очередь. До исправления регрессия реально продвинула номер запроса гостя с 1 до 2. Она также проверяет совместимую новую публикацию с повтором прежнего сетевого номера, отсутствие эффектов отказа, завершение ранее допущенной работы и отказ после сбоя владельца.
|
||||
|
||||
Проверка S16-04 на базе `c183de1`: Windows x64 Release GCC 16.2 под Wine 11, 4/4 новых `lan-admission`; полный CTest — 168/168 core, 17/17 LAN, 15/15 клиента и 6/6 управления заказами. После исправления управляемая гонка сохраняет точную публикацию отмены, прежние сетевой номер и номер запроса гостя, профессию жителя и отсутствие квитанции в журнале. Старый скомпилированный клиент и заново собранный адаптер успешно обменялись приказами в обеих ролях. `git diff --check` прошёл. Нативная Windows, MSVC и физические машины этим прогоном не проверялись.
|
||||
|
||||
Для этого адаптера повторно проверены публичный `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)
|
||||
|
||||
Селектор `--tag session` под Wine выполнил десять проверок, включая двух клиентов, конфликт данных повтора, откат с новой инкарнацией и отказ до/после изменения. Сценарий из 700 тактов сверяет эталон и 2/6/12 потоков. Подключение окна и сетевого транспорта к владельцу мира входит в следующий срез M01. [Сценарии](../../../tests/session_tests.cpp)
|
||||
|
||||
- **S16-A01.** Два клиента общего города одновременно заказывают последний доступный предмет. Выполняется один расход, второй запрос получает объяснимый результат.
|
||||
- **S16-A02.** Передать чужой `player`, чужой город, просроченный экземпляр сессии и повтор команды. Проверить авторизацию и устойчивые квитанции.
|
||||
- **S16-A03.** Разорвать соединение между принятием сделки и получением квитанции. После возврата предметы и деньги совпадают со снимком хозяина.
|
||||
|
||||
@@ -1,10 +1,57 @@
|
||||
# S17. D3D11-рендеринг, камера и визуальное состояние
|
||||
|
||||
Статус — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
Статус — S17-W01 и ограниченный объёмный API S17-02 реализованы и проверены в Windows x64/Wine, ожидают независимой приёмки. Подключение объёмного API к обычному игровому кадру выполняется отдельной задачей S18/World. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
`D3DScene::render` принимает `const World&`, заново собирает геометрию карты, ресурсов, построек и жителей, загружает её и вызывает D3D11. `SceneView` хранит положение камеры, выбор и предпросмотр. Вызов происходит из `WM_PAINT`, а симуляция — из `WM_TIMER` того же окна. Основой нового клиента остаётся имеющийся Win32/D3D11-путь. [Интерфейс сцены](../../../app/d3d_scene_win32.hpp) · [Текущий рендер](../../../app/d3d_scene_win32.cpp)
|
||||
S17-W01 сохраняет существующую плоскую карту и Win32/D3D11. `PreparedFrame` удерживает один принятый `World`, параметры камеры и области, копии чертежей/комнат, выбор и предпросмотр, готовую CPU-геометрию, строки HUD и собственный шрифт. Главная и дочерняя `WM_PAINT` сначала удерживают весь пакет, затем рисуют без обращения к живому миру или векторам редактирования. [Подготовка кадров](../../../app/viewer_win32.cpp) · [Интерфейс сцены](../../../app/d3d_scene_win32.hpp)
|
||||
|
||||
Отдельный таймер 16 мс выбирает актуальный кадр только для видимой ненулевой игровой области и при изменениях. Таймер управления/LAN остаётся 60 мс, владелец симуляции — 50 мс. Это частоты обслуживания, а не утверждение о физической частоте экрана. Камера и размеры не пересобирают плоскую CPU-геометрию; неизменённая геометрия повторно не загружается на GPU. Размер render target, пересоздание устройства или возврат к удержанному старому пакету требуют соответствующей загрузки.
|
||||
|
||||
Ключ геометрии учитывает удержанный снимок мира, курсор и его допустимость, переносимый объект, жителя, все поля чертежей/комнат и предпросмотра, режим крыши/стен и переносимую комнату. Сравнение удерживаемых объектов снимков различает новые публикации даже при одинаковом такте. Пакеты владеют CPU-геометрией совместно; у renderer остаётся только текущая GPU-загрузка. Старый пакет можно отрисовать после нового или после сброса backend.
|
||||
|
||||
Пока `ViewerSession::changing_world()` истинно, прежнее представление сохраняется, включая отсутствие мира. Фоновая публикация между проверкой future и чтением мира не выпускает кандидата в UI. Только обработанный `Replaced` сбрасывает чертежи, выбор и камеру перед подготовкой замены. Подготовка приостанавливается внутри обработки событий и отрисовки; вложенная инвалидизация остаётся запросом следующего кадра. `BeginPaint` и временные DC/bitmap имеют RAII, backend удерживается до возврата из `Present`. При отказе остаётся HUD ошибки с восстановлением через повторный вход из меню; резервного GDI-рендера карты нет.
|
||||
|
||||
### Проверка S17-W01
|
||||
|
||||
Постоянная CMake/CTest-цель `settlement_viewer_frame_smoke` использует относительный include реального обработчика и настоящие главное/дочернее окна. [Тест](../../../tests/viewer_frame_smoke.cpp) проверяет:
|
||||
|
||||
- колесо и оба перетаскивания с изменением кадра/пикселей, когда настоящий рабочий `World` и запись файла `WriteStage` удерживаются барьерами; таймер событий в этой части не вызывается;
|
||||
- неизменность полного канонического снимка и такта, повторное использование CPU/GPU-геометрии, побайтовое равенство сохранённого checkpoint исходному `World` и метаданным;
|
||||
- отдельный удержанный файловый reader, старые комнаты/чертежи после редактирования, вложенные paint и незатерянную инвалидизацию;
|
||||
- публикацию установки после `poll()` до чтения мира, вложенные paint в этом промежутке, сохранение прежнего/нулевого представления до `Replaced`;
|
||||
- скрытие, минимизацию, меню, восстановление последней публикации, изменение размера, нулевую область, ошибку и повторный запуск renderer, отрисовку старого пакета после сброса backend;
|
||||
- разрушение окна внутри paint и игнорирование оставшихся таймерных сообщений.
|
||||
|
||||
Сборка: GCC 16.2 MinGW, Release, закреплённая VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, `BUILD_TESTING=ON`. Проверка: `cmake --build <build> --parallel 6`, `ctest --test-dir <build> -V`, `git diff --check`. В Wine 11 с доступным DISPLAY работают видимый swap chain и offscreen WARP; проба DXGI сообщает «ATI Radeon HD 5600 Series» для обоих типов устройств. Это имя адаптера Wine, а не подтверждение физического GPU. Если устройства отсутствуют, smoke возвращает CTest skip 77; отказ renderer при доступном устройстве считается ошибкой.
|
||||
|
||||
Дополнительно прошли прежние UI-прогоны: blueprint/room handlers, отказ команд и сохранность чертежей, загрузка/выход из гостя, rollback LAN-диалогов, три настоящих процесса viewer с изолированным `LOCALAPPDATA`, меню, реальный file picker, современное и прежнее сохранение. Нативная Windows, физическая потеря устройства, 1080p60/p95 и будущая воксельная геометрия здесь не проверялись. Тест отказа renderer намеренно подаёт неподходящий viewport и проверяет штатный HUD/повторный вход.
|
||||
|
||||
Общий примитив публикации остаётся связан с [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5). При его появлении заменить локальное владение только после тех же проверок старого пакета, вложенной установки и срока жизни геометрии. `PreparedFrame` и игровые правила формирования HUD остаются клиентскими данными.
|
||||
|
||||
## Объёмная сцена S17-02
|
||||
|
||||
[`prepare_voxel_scene`](../../../app/voxel_scene.hpp) принимает настоящий `VoxelRegion` S02, UUID экземпляра сессии, конечный объём показа внутри региона и включительный верхний слой `slice`. Результат совместно владеет неизменяемым снимком страниц, открытыми гранями и отсортированными `ChunkStamp` всех прочитанных страниц, включая отсутствующие и соседние. `current(region, session)` проверяет описание региона, экземпляр сессии и прочитанные ревизии. Изменение непрочитанной страницы оставляет геометрию пригодной. При замене мира вызывающая сторона меняет UUID.
|
||||
|
||||
Клетка занимает `[x,x+1) × [y,y+1) × [z,z+1)`. Почва, камень и закрытая дверь образуют непрозрачный куб. Воздух и открытая дверь дают видимый проход. Внутренние грани смежных занятых клеток не выпускаются, в том числе через границы страниц −32, 0 и 32. Отсечение объёмом показа и слоем открывает соответствующие граничные поверхности. Отсутствующие страницы показываются непрозрачными серыми гранями, а выбор останавливается с `Unavailable`, поэтому загруженный объект за неизвестной областью нельзя выбрать насквозь.
|
||||
|
||||
`D3DScene::prepare_voxels(scene)` создаёт настоящий CPU-пакет `PreparedGeometry`. `render(packet, VoxelCamera, capture)` загружает его в D3D11 и рисует треугольники. Координаты вершин отсчитываются от нижнего угла объёма показа, что сохраняет точность клеток рядом с `INT32_MIN` и `INT32_MAX`. Позиция этого угла на экране задаётся `origin_x/y`. Проекция сохраняет базис `(x-y)*halfTile.x, (x+y)*halfTile.y-z*16`, масштаб и смещение камеры. Глубина нормируется по объёму сцены. Прежний плоский пакет сохраняет прежние коэффициенты глубины `.96/.009`.
|
||||
|
||||
`pick_voxel_screen` использует тот же удержанный `VoxelScene` и ту же `VoxelCamera`, что и показанный пакет. Результат содержит регион, UUID сессии, клетку, одну нормаль грани, материал, расстояние и прочитанные ревизии. Соседняя клетка возвращается только при представимых координатах и может оказаться за границами региона, поэтому её допустимость для действия проверяет симуляция. `trace_voxels` также принимает произвольный конечный луч. Нулевое направление и нечисловые входы отвергаются. Начало внутри занятой клетки даёт `Inside` без грани. На точной плоскости знак направления выбирает следующую клетку, нулевой компонент оставляет луч в клетке, владеющей полуоткрытой границей. При одновременном переходе по нескольким осям меняются все эти координаты, а нормаль выбирается в порядке X, Y, Z. Клетки, которых луч касается только ребром, пропускаются. Масштабирование направления степенью двойки сохраняет точные отношения компонентов, включая проверенный случай 1:3.
|
||||
|
||||
По умолчанию подготовка ограничена 2 097 152 просматриваемыми клетками, 262 144 гранями, 1 024 прочитанными страницами, 4 096 клетками по каждой оси и 64 МиБ для граней, ёмкости каталога ревизий и развёрнутых CPU-вершин. Независимый предел оси 65 536 сохраняет представимость локальных координат даже при повышении бюджета. Грани сначала подсчитываются и проверяются, затем заполняется выделенный массив. Луч ограничен 16 384 посещёнными клетками и 1 024 страницами. Ошибка лимита или выделения памяти возвращается до публикации замены. Источник страниц, старые удержанные пакеты, накладные расходы аллокатора и GPU-память учитываются вызывающей стороной отдельно. Один квадрат разворачивается в шесть вершин по 24 байта.
|
||||
|
||||
Камера не входит в CPU-геометрию. Сдвиг и масштаб используют тот же пакет без повторной загрузки. Возврат к удержанному старому пакету и восстановление устройства загружают его вновь. Рост GPU-буфера сначала создаёт и заполняет замену, сохраняя прежний буфер при отказе. Пустой срез рисует только фон. Асинхронный диспетчер перестроения отдельных чанков, вращение камеры, обычное управление срезом через S18 и физический профиль производительности остаются последующими работами.
|
||||
|
||||
### Проверка S17-02
|
||||
|
||||
[`settlement_voxel_scene_tests`](../../../tests/voxel_scene_tests.cpp) содержит 15 проверок CPU-контрактов и настоящего offscreen D3D11/WARP. Пиксели известных верхних и боковых граней сверяются с результатом выбора, включая масштаб, сдвиг, срез крыши, открытый дверной проём, пропуск, лимит, неизвестную страницу и крайние знаковые координаты. Отдельная сцена использует генератор S02 на 16 страницах и 6 528 клетках, выдаёт 1 998 граней и 11 988 вершин. Отказ меньшего бюджета сохраняет отображаемый пакет и счётчик GPU-загрузок. Проверки удерживают старую геометрию после изменения материалов и пересоздания устройства.
|
||||
|
||||
Проверка из изолированного `s17-voxel` на базе `13dc673`, GCC 16.2.0, Windows x64/Wine 11.0, Release и закреплённой VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792` выполняется командами `cmake --build /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build --parallel 6`, `flock /tmp/stoneheart-milestones.xprJ2SVp/interactive-test.lock ctest --test-dir /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build -V` и `git diff --check`. Конфигурация использует согласованные `env.sh` и cross-toolchain из `/tmp/stoneheart-verify.KoZwE4o8`, `BUILD_TESTING=ON`. Журналы находятся в `/tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-*.log`. Этот прогон не устанавливает физическую производительность 1080p60 или поведение драйвера на нативной Windows.
|
||||
|
||||
Наблюдаемый итог 2026-12-03 — сборка без предупреждений, 6/6 CTest за 17,60 с. Прошли 196 core, 17 LAN, 15 viewer session, 6 production controls, 15 voxel scene и отдельный настоящий frame smoke. Полный журнал — `s17-voxel-final-ctest.log`, сборка — `s17-voxel-final-build.log`. Native Windows, физическая GPU и искусственное исчерпание памяти драйвера не проверялись.
|
||||
|
||||
Публичные `Void::Math::Vec3` и `Void::Numeric::checked_*` используются из закреплённой версии. Локальный ограниченный 3D-обход связан с [Void/Library #12](https://git.faumaray.com/Void/Library/issues/12), каталог прочитанных ревизий — с [#13](https://git.faumaray.com/Void/Library/issues/13). Замена библиотечным API требует сохранить проверенные правила границ, неопределённости, лимитов, UUID сессии и инвалидирования соседних страниц. Форма клеток, материалы, дверной проём и включительный срез остаются игровыми правилами.
|
||||
|
||||
## Границы данных и потоков
|
||||
|
||||
@@ -16,7 +63,7 @@
|
||||
|
||||
## Последовательность реализации
|
||||
|
||||
1. **S17-W01, M01.** Ввести публикацию снимков и самостоятельный цикл кадров. Перенести обращения к миру из обработчиков отрисовки в подготовку снимка. Проверить работу камеры при искусственно долгом такте.
|
||||
1. **S17-W01, M01 — реализовано, ожидает приёмки.** Неизменяемый пакет, отдельный таймер кадра и проверки камеры при удержанном рабочем/файловом вводе-выводе описаны выше.
|
||||
2. **S17-W02, M02.** Построить геометрию изменившихся чанков и обработку общих граней. Добавить отсечение невидимых областей и приоритет ближних участков. В тесте редактировать грань между двумя чанками и проверять отсутствие щели и дублирующей поверхности.
|
||||
3. **S17-W03, M02–M03.** Добавить вращение, масштабирование вокруг указателя, выбор по лучу и срез высоты. Выбор возвращает регион, клетку, грань и ревизию, по которым интерфейс формирует намерение. При подтверждении симуляция проверяет действие на актуальной геометрии.
|
||||
4. **S17-W04, M03–M07.** Разделить статическую геометрию, жителей, предметы и эффекты. Интерполировать визуальные позы между подтверждёнными тактами. Подключить оригинальные модели, анимацию, освещение, время суток и читаемую индикацию работы.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# S18. Интерфейс, управление и обратная связь
|
||||
|
||||
Статус — план реализации. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
Статус — первый срез S18-W01 и выбор двух встроенных правил S18-02 реализованы: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
@@ -16,6 +16,20 @@
|
||||
|
||||
## Последовательность реализации
|
||||
|
||||
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное, непосредственно заменяемое и последнее подготовленное состояние проходят `validate_colony_checkpoint` из [S19](S19.md) до установки и дополнительно ограничены картой 32×32. Допускаются только точные встроенные составы стандартной колонии и `settlement.plankbeds`; неизвестный, лишний или изменённый пакет, пустой мир, нулевой идентификатор либо поэтапная кровать с простыми правилами отклоняются с сохранением текущего мира.
|
||||
|
||||
На настоящем главном экране нативный список «Правила только новой колонии» выбирает поэтапную кровать с опорой и тканью (исходный выбор) либо простую кровать из одной доски. Выбор живёт в процессе и применяется только кнопкой «Новая колония»: `make_colony_checkpoint` создаёт соответствующий мир, новый UUID и точный манифест. «Продолжить», список сохранений и выбор файла восстанавливают правила самого сохранения. Исторический стандартный мир с простыми кроватями, поэтапными кроватями или без активного сценария принимается без смены режима. В простом режиме описания всех готовых домов, включая дом шахтёра, показывают одну доску; выбор деревянной/каменной опоры скрыт.
|
||||
|
||||
Старый LAN-протокол 11 допускает только точный стандартный манифест из текущей авторитетной публикации. Проверка выполняется при выборе Host после возврата из модального меню, а для отложенного создания — повторно перед запуском сети после установки мира. Пока ожидается любая смена мира, Host отклоняется без замены мира, отмены загрузки или изменения сетевого объекта. Даже если опубликованный старый мир стандартный, ожидающая загрузка простых правил не открывает слушатель. Выход старого гостя по-прежнему присваивает полученному миру замороженные стандартные правила; формат LAN не расширен.
|
||||
|
||||
Локальная очередь ограничена 64 намерениями и одной отправленной командой. Номер запроса берётся из подтверждённого снимка; занятая очередь владельца оставляет намерение для повтора. Чертёж комнаты, мебели или старого домика удаляется только после принятого результата. Отказ сохраняет возможность редактирования, повторное нажатие не дублирует ожидающую операцию. Гостевые квитанции сопоставляются с ограниченной очередью отправок и поколением сессии. Таймер обслуживает завершения также на главном экране и внутри модальных меню. Одиночная пауза и выбор файла приостанавливают игровое время; меню хозяина сохраняет существующее сетевое поведение.
|
||||
|
||||
Сохранение удерживает здоровый опубликованный снимок, а общий файловый сервис сохраняет порядок записей через смену мира. Только последняя актуальная операция обновляет сообщение. Любая новая попытка загрузки сначала отменяет актуальность предыдущего билета, включая попытку открыть повреждённый или отсутствующий файл. Сбой симуляции оставляет последний подтверждённый вид и возможность явной загрузки. [Файлы и восстановление](S15.md) · [Сетевой адаптер](S16.md) · [Проверки состояния клиента](../../../tests/viewer_session_tests.cpp)
|
||||
|
||||
Проверка среза: сборка Windows x64 GCC 16.2; Wine 11, verbose CTest — 99 проверок ядра, 9 LAN и 10 состояния клиента. Отдельный прогон настоящего `settlement_viewer.exe` прошёл создание колонии, движение времени, подтверждённую смену приоритета, модальную паузу, выбор файла сохранения, продолжение партии, загрузку нового формата через главное меню в новом процессе, отказ повреждённого файла, загрузку старого формата из списка и штатное закрытие трёх процессов. Сохранения размещались в отдельном временном `LOCALAPPDATA`. Дополнительный Win32-прогон настоящих обработчиков проверил отказ и повтор чертежа, принятую комнату при переносе другой комнаты, старый домик через общий журнал, отрисовку и сохранение при заблокированном тике, смену мира и гостя без ожидания тика. Регрессионный прогон проверил отказ ошибочного повторного подключения с сохранением полученной колонии, откат при отказе владельца после подготовки соединения и запрет подтверждения сноса во время ожидающей загрузки. Отдельная проверка состояния клиента покрывает остановку после сбоя, успешную загрузку и возобновление тиков. Нативная Windows, доступность и визуальная проверка масштабирования остаются отдельной приёмкой; настройки масштаба, клавиш и звука за пределами этого среза.
|
||||
|
||||
Проверка S18-02: повторная Windows x64 GCC 16.2 сборка и verbose CTest под Wine 11 — 122 проверки ядра, 9 LAN и 14 состояния клиента. Четыре новые проверки покрывают оба профиля при создании/сохранении/повторной загрузке, начальные и асинхронные отказы манифестов и идентификаторов, отмену актуальности старой правильной загрузки последующей несовместимой, исторические режимы и стандартный импорт гостя. Отдельный прогон настоящего приложения в изолированном `LOCALAPPDATA` проверяет окно 775×640, Tab/стрелки и мышь в нативном списке, мышь/Space на «Новая колония», точные манифесты и режимы в реальных сохранениях, продолжение, список и диалог открытия при противоположном выборе новых правил. Новый процесс возвращает стандартный выбор новой колонии и открывает последнее сохранение с простыми правилами. Прогон настоящих обработчиков удерживает загрузку простого мира поверх стандартного при прямом Host и Host из модального меню, проверяет сохранение мира/билета/сетевого объекта/кода/порта и отсутствие слушателя; отложенный Host повторно отклоняет несовместимую установленную публикацию. Проверены скрытие опор и описание дома шахтёра. Нативная Windows, экранный диктор и повышенный DPI остаются отдельной приёмкой.
|
||||
|
||||
1. **S18-W01, M01–M02.** Отделить чтение снимков и отправку команд от Win32-обработчиков. Определить модель состояния инструмента, выделения и отмены. Добавить настройку масштаба, клавиш и звука с проверкой конфликтов назначений.
|
||||
2. **S18-W02, M02–M03.** Собрать путь демо. Игрок размечает склон, ставит склад, выбирает этаж, редактирует дом, видит материалы и подтверждает строительство. Затем назначает мебель, проверяет потребности жителей и сохраняет незавершённую работу.
|
||||
3. **S18-W03, M04–M06.** Добавить панели рабочих очередей, профессий, запасов и торговых сделок. Фильтры и сортировки устойчиво сохраняют выбранный объект при обновлении снимка. Список населения ведёт к жителю или объясняет его нахождение в другом регионе.
|
||||
@@ -42,7 +56,7 @@
|
||||
|
||||
## VoidLibrary
|
||||
|
||||
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
|
||||
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Выбор S18-02 использует готовые фабрику и проверку профилей S19; общий пробел разрешения пакетов связан с [Void/Library #4](https://git.faumaray.com/Void/Library/issues/4). Схема игровых правил и нативные контролы остаются у игры. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
|
||||
|
||||
## Приёмка
|
||||
|
||||
|
||||
@@ -4,6 +4,24 @@
|
||||
|
||||
Статус — план реализации. Игрок выбирает совместимый набор механик при создании мира. Собственные материалы и моды подключаются через документированный формат, а состояние этой конфигурации сохраняется вместе с колонией. Основа вводится в [M01](../milestones/M01.md), используется игровыми системами и публикуется для авторов в [M10](../milestones/M10.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Первый исполняемый срез M01
|
||||
|
||||
`load_rule_package` читает ограниченный по размеру JSON с версией схемы, определениями, ссылками и зависимостями. `resolve_rules` для выбранных модулей вычисляет транзитивный состав, проверяет конфликты и возвращает точные версии с SHA-256. Порядок обхода файлов не меняет идентичность. Для проверки запустить `settlement_core_tests.exe --tag rules`. [Публичный интерфейс](../../../engine/include/settlement/core/rules_manifest.hpp) · [Реализация](../../../engine/src/rules_manifest.cpp) · [Проверки](../../../tests/rules_tests.cpp)
|
||||
|
||||
На Windows x64 под Wine прошли 9 сценариев для манифестов. Разбор JSON, версии, граф и хеш использованы из закреплённой VoidLibrary. Для замены локального разрешения наборов библиотечным сервисом повторить проверки транзитивных зависимостей, перестановок, конфликтов и идентичности. [Запрос в Void/Library](https://git.faumaray.com/Void/Library/issues/4)
|
||||
|
||||
## Выбор исполняемого профиля колонии
|
||||
|
||||
Первый выбор механики использует два существующих способа постройки кровати. Профиль по умолчанию собирает основание из дерева или камня, затем отдельно доставляет ткань для постели и подушки. Дополнительный пакет `settlement.plankbeds@1.0.0` задаёт простую кровать из одной доски. Для неё жители сначала выполняют распил за 12 рабочих тактов, затем собирают кровать за 14. Команды отдельной кровати и меблированной комнаты используют выбранный способ. [Профиль и создание колонии](../../../engine/include/settlement/core/colony_profile.hpp) · [Игровые проверки](../../../tests/profile_tests.cpp)
|
||||
|
||||
Компилятор профиля проверяет точный состав, версии и SHA-256 реализованных пакетов, затем связывает проверенные поля определения рецепта с начальной конфигурацией мира. Фабрика возвращает мир вместе с его манифестом и постоянным UUID. Настройка выполняется при запуске сценария. Поля демонстрационного определения доски в исходном пакете сохраняют прежнее содержимое. Общее исполнение произвольных данных рецепта относится к S19-W02.
|
||||
|
||||
Два исходных пакета и их канонический манифест закреплены проверкой с отпечатком `06d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1`, полученным из ядра до добавления профилей. Выбор по умолчанию включает эти два пакета. Дополнительный профиль разрешает их вместе с пакетом простых кроватей.
|
||||
|
||||
Старое сохранение с исходным манифестом может содержать любой из двух способов постройки, включая неактивный сценарий. Проверка загрузки сохраняет этот способ и манифест. Для дополнительного пакета требуется сохранённый способ простых кроватей. Изменённый пакет, неизвестная комбинация или сочетание дополнительного пакета с поэтапной сборкой получает диагностический отказ до замены партии. Общие кодеки остаются доступными для каталогов вызывающего приложения. Прежний LAN11 допускает точный исходный манифест. Интерфейс выбора профиля подключается через S18.
|
||||
|
||||
Семь случаев `--tag profile` прошли в Windows x64 под Wine. Оба профиля завершили цель с тремя кроватями и едой, проверены меблированная комната, материал в переноске, продолжение после загрузки и одинаковые контрольные точки на последовательном эталоне и 2/6/12 потоках. Сохранён подлинный файл схемы 1 с исходным манифестом и простой сборкой. Общая сборка прошла 113 тестов ядра и 4 LAN. Все 738 386 байтов прежней траектории совпали с исходной сборкой во всех четырёх режимах. Нативная Windows и подключение выбора в окно проверяются отдельно.
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
Предметы, профессии, рецепты и команды прототипа определяются C++-типами, а стартовая партия создаётся кодом. В проверенной CMake-конфигурации подключены `Void::Binary`, `Void::Core` и `Void::Testing`. Скриптовый runtime в этот перечень не входит. План вводит новые определения контента и границу расширения. [Текущая конфигурация сборки](../../../CMakeLists.txt)
|
||||
@@ -22,6 +40,8 @@
|
||||
|
||||
Долговременное состояние обработчика представляет собой проверяемые сериализуемые значения с явной схемой. Продолжение события хранит идентификатор шага, данные и запланированный такт. Персистентные coroutine-стеки, нативные замыкания и произвольная память интерпретатора в формат сохранения не входят. Сам обработчик выполняется с фиксированным входом и возвращает предлагаемые изменения.
|
||||
|
||||
Состояние обработчика получает ключ пакета, обработчика и версии схемы. Продолжение имеет постоянный идентификатор, детерминированные данные и назначенный такт. Предложения связываются с исходной ревизией снимка и инкарнацией. Владелец проверяет их в устойчивом порядке и одной операцией применяет новое состояние, продвижение генератора случайности, расписание и игровые изменения. Отказ либо устаревшая инкарнация отбрасывают весь этот результат. Исполнение Lua вводится в S19-W03.
|
||||
|
||||
Игровой API задаёт детерминированный порядок коллекций, отдельные потоки случайных чисел и правила числовых значений. Авторитетные решения используют разрешённые целочисленные либо явно квантованные величины. Прикладное API запрещает неупорядоченную итерацию для последовательности игровых изменений. Время берётся из номера такта. Вызовы системы, сети, произвольных файлов и нативных расширений недоступны исполняемому игровому скрипту.
|
||||
|
||||
Каждый обработчик ограничен по инструкциям, памяти, размеру результата и стоимости вызванных функций хоста. Счётчик Lua-инструкций дополняется ограничением работы C++-функций, поскольку эта работа выполняется вне счётчика интерпретатора. Состояние обработчика и предложения применяются атомарно. Ошибка отбрасывает его незавершённый результат и ставит авторитетное продвижение на безопасную границу с диагностикой. Состав правил мира сохраняется. [Стадии симуляции](S01.md)
|
||||
|
||||
@@ -73,3 +73,116 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
|
||||
Текущие тесты используют `Void::Testing`. Перед собственным runner, профилировщиком, таймером, журналом и форматом отчёта проверить существующие возможности VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности найти или создать issue в `Void/Library`, приложить воспроизводимый пример нужного поведения и связать локальную реализацию с issue. [Матрица VoidLibrary](../void-library.md)
|
||||
|
||||
Система принята, когда каждый обязательный сценарий имеет команду запуска либо точную ручную процедуру, исходный мир, фактический результат и границы среды. Финальный отчёт различает кросс-сборку, Wine, нативную Windows, физические ПК и измерения GPU. Готовность пакета подтверждается запуском из поставки с её библиотеками и материалами. [Сохранения](S15.md) · [Сеть](S16.md) · [Происхождение материалов](S20.md)
|
||||
|
||||
## M01: наблюдаемый порядок завершения (S21-01)
|
||||
|
||||
Проверка подготовлена поверх `66af7c5` в `system/s21-verification`. Закреплённый
|
||||
Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `FuturePool::try_submit`
|
||||
с сохранением отклонённого callable и доставкой исключений через future. Его
|
||||
`Testing::DeterministicRun` управляет тестовыми действиями; он не наблюдает возврат
|
||||
реального `World` callable. Поэтому локальный `WorkerPoolOptions::after_execute(index)`
|
||||
вызывается после успешного возврата callable, перед готовностью future. Исключение
|
||||
наблюдателя попадает в тот же future; ошибка до исполнения или внутри callable
|
||||
не вызывает наблюдателя. Без хуков остаётся прежняя ветка без счётчика отправок.
|
||||
[Реализация](../../../engine/include/settlement/core/worker_pool.hpp) ·
|
||||
[Контракт замены Void/Library#15](https://git.faumaray.com/Void/Library/issues/15).
|
||||
|
||||
Условие замены локального наблюдателя библиотечным — сохранить проверяемые возврат
|
||||
`void`, значения, lvalue-ссылки, move-only результата и callable, ровно одно
|
||||
успешное уведомление, исключения и исполнение при переполнении на координаторе.
|
||||
[ExecutorTests](../../../tests/executor_tests.cpp) дополнительно удерживает сам
|
||||
наблюдатель и проверяет, что future ещё не готов. Перенос уведомления к началу
|
||||
вызова нарушает проверку завершённого действия.
|
||||
|
||||
[ReplayTests](../../../tests/replay_tests.cpp) использует два отдельных сценария:
|
||||
|
||||
- Seed 101, два жителя в `(5,1)`, одно достижимое общее задание в `(1,1)`.
|
||||
При 2/6/12 потоках первые отправки 0 и 1 — реальные независимые вычисления
|
||||
`choose_jobs` для жителей 0 и 1. Контроллер разрешает первый расчёт, ждёт его
|
||||
`after_execute`, затем разрешает второй. Получены обе последовательности
|
||||
`A->B` и `B->A`; владельцем задания остаётся житель с меньшим стабильным ID.
|
||||
- Seed 97, два голодных жителя и одна ягода. Здесь общих заданий нет, поэтому
|
||||
отправки 0 и 1 — стадии продвижения жителей. Захват еды выполняется
|
||||
последовательно в `assign_meals` до этих стадий. Проверяются противоположные
|
||||
завершения продвижения, один владелец, сохранность ягоды и ровно одно потребление;
|
||||
параллельный арбитраж еды этим сценарием не заявляется.
|
||||
|
||||
Оба сценария проверены с `max_admitted=4096` и `1`. Контроллер находится вне
|
||||
координатора, который при переполнении сам может ждать в inline callable.
|
||||
Ожидания ограничены пятью секундами; scope guard всегда открывает ворота до
|
||||
ожидания координатора или разрушения пула. Каждая из 24 конфигураций сравнивает
|
||||
все 40 тактов с последовательным эталоном через настоящий `Current15` writer.
|
||||
Лог содержит фактическую последовательность завершений каждой конфигурации.
|
||||
|
||||
[RuntimeTests](../../../tests/runtime_tests.cpp) удерживает старую задачу во время
|
||||
постановки загрузки того же сохранения в очередь. Пока задача удержана, доступны
|
||||
старый неизменяемый снимок и захват сохранения, а установка и старая команда ещё
|
||||
не завершены. Перед захватом кандидата проверяется равенство числа начатых и
|
||||
вернувшихся задач. После установки меняется session, старая команда получает
|
||||
`StaleSession`; дополнительный барьер и следующий такт подтверждают неизменность
|
||||
старого снимка и соответствие нового мира эталону.
|
||||
|
||||
[Test-local диагностика](../../../tests/replay_diagnostics.hpp) сначала сравнивает
|
||||
канонические байты. Только при несовпадении она показывает первый различающийся
|
||||
публичный факт с ID жителя, задания или производства, именем поля и значениями
|
||||
expected/actual. Для запасов указываются владелец, тип предмета и ID стека,
|
||||
для команд — игрок и следующий номер.
|
||||
Сравнение квитанций содержит игрока, номер команды, статус, tick и revision.
|
||||
Контекст включает первый обнаруженный tick/attempt, seed мира, число потоков,
|
||||
расписание, состояние загрузки и предел допуска. Непокрытое публичной проекцией
|
||||
поле получает смещение и значения байта. Это диагностическая проекция, а не
|
||||
второй кодек или альтернативный критерий равенства. Отдельно проверены равенство,
|
||||
ошибки запаса/задания/команды/квитанции, лишний ID и байтовый fallback.
|
||||
|
||||
Проверка 2 декабря 2026 года: Windows x64 Release кросс-сборка GCC 16.2.0,
|
||||
выполнение Wine 11.0. CTest `-V`: 3/3 цели, 141 core + 9 LAN + 10 viewer тестов.
|
||||
Отдельные теги: executor 10/10, replay 8/8, runtime 11/11. Логи:
|
||||
`/tmp/stoneheart-milestones.xprJ2SVp/s21-replay-{configure,build,ctest,executor,replay,runtime}.log`.
|
||||
Повторная окончательная сборка/CTest: `s21-replay-final-build.log`, `s21-replay-final-ctest.log` (3/3, 18,35 с).
|
||||
Два внешних probe собраны заново против этой библиотеки; при 1/2/6/12 потоках
|
||||
`cmp` подтвердил совпадение обоих исторических корпусов:
|
||||
|
||||
- `trajectory.cpp`: 361 такт, 5 приёмов пищи; SHA-256
|
||||
`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`.
|
||||
- `identity-compat.cpp`: доставка и строительство после удаления других объектов;
|
||||
SHA-256 `05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`.
|
||||
|
||||
Логи probe: `s21-replay-probe-build.log`, `s21-replay-golden.log` в том же каталоге.
|
||||
Физическая Windows, длительная нагрузка и производительность GPU здесь не проверялись.
|
||||
Serena/граф были связаны с основным checkout; для изолированного worktree использована
|
||||
прямая проверка исходников без переключения общего проекта и без заявления о покрытии графом.
|
||||
|
||||
## Полное состояние владения грузом
|
||||
|
||||
Потактный эталон и сравнение публикаций владельца используют `Current15`.
|
||||
Сравнение включает имущество у производства, приостановку заказа, следующий
|
||||
номер назначения, действующее исполнение и его резервы, результаты передач
|
||||
и баланс каждого предмета. При расхождении диагностика показывает сначала
|
||||
видимое изменение запасов или задания, затем постоянные ID и шаги исполнения,
|
||||
сохранённые результаты и счётчики баланса. Ключ квитанции состоит из вида,
|
||||
ID и номера операции. Положение квитанции в кольцевом буфере не служит её ID.
|
||||
Если публичные факты совпали, сравнение сообщает первое различие байтов.
|
||||
|
||||
Проверка загрузки прежнего формата создаёт корректные миры с одинаковыми
|
||||
байтами `Current14` и разными данными `Current15`. Она выявляет восстановленный
|
||||
ID стека, различие начального остатка и начисления и отсутствие квитанции
|
||||
назначения в историческом сохранении. Диагностический пример сообщает
|
||||
`stock owner=storage:1 item=3 field=stack_id expected=2 actual=1`.
|
||||
|
||||
Отдельный сценарий отменяет настоящую стройку после доставки, заполняет
|
||||
исходный склад и возвращает одну доску в склад вместимостью один предмет.
|
||||
Оставшиеся две доски и два каменных блока ждут места у того же исполнителя
|
||||
с тем же ID передачи. Контрольная точка восстанавливается на 1/2/6/12
|
||||
исполнителях. После появления свободного склада каждый такт совпадает
|
||||
с непрерывной партией. Точные и конфликтующие повторы квитанций назначения
|
||||
и отмены проверяются до и после загрузки и после возврата груза.
|
||||
|
||||
Windows x64 Release GCC 16.2 под Wine 11 выполнил 10 проверок `replay` за 2,71 с
|
||||
и 11 проверок `runtime` за 30 мс на рабочем срезе `e26b9c2` с этой проверкой.
|
||||
Все 24 расписания завершения настоящих задач сохранились. Сценарий частичного
|
||||
возврата занял 19,1 мс. Логи находятся в
|
||||
`/tmp/stoneheart-milestones.xprJ2SVp/s21-custody-{configure,build-final,replay,runtime}.log`.
|
||||
После объединения с исправлением проверки времени и ссылок S06 в `8522f91`
|
||||
повторная сборка и CTest завершились с кодом 0. Все три цели прошли за 26,91 с,
|
||||
включая 169 проверок ядра, 9 LAN и 10 клиента. Журналы этой сборки и запуска —
|
||||
`s21-custody-build-validated.log` и `s21-custody-ctest-validated.log`.
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
## Срез на 2 декабря 2026 года
|
||||
|
||||
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. CMake игры явно выбирает `Binary` и `Core`, а при включённых тестах ещё `Testing`. Для следующих модулей проверены исходники закреплённой версии. Их включение и измерения в итоговой Windows-сборке входят в соответствующие этапы.
|
||||
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. Windows-сборка M01 выбирает `Algorithms`, `Async`, `Binary`, `Core`, `Crypto`, `Data`, `Math`, `Text` и `Time`. При сборке тестов добавляется `Testing`. [Настройки зависимости](../../CMakeLists.txt)
|
||||
|
||||
| Задача игры | Что есть в VoidLibrary | Решение и граница применимости |
|
||||
|---|---|---|
|
||||
@@ -33,10 +33,40 @@
|
||||
|
||||
## Первое применение правила в M01
|
||||
|
||||
| Пробел в проверенном pin | Локальная задача и условие перехода на Void |
|
||||
|---|---|
|
||||
| [Атомарная замена файлов на Windows, #3](https://git.faumaray.com/Void/Library/issues/3) | S15, `save_service_win32.cpp`. Заменить адаптер после проверок первой записи, замены слота и отказов до и после публикации, включая пути Unicode. |
|
||||
| [Ограниченное чтение одного файла на Windows, #9](https://git.faumaray.com/Void/Library/issues/9) | S15, `checkpoint_files.cpp`. Закреплённая `FileSystem::read_file_bounded` возвращает `unsupported` в Windows. Проверки замены охватывают Unicode, точную границу размера, увеличение уже открытого файла сверх лимита и отказ без возврата частичных данных. [API](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/System/Path.hpp) |
|
||||
| [Разрешение набора пакетов, #4](https://git.faumaray.com/Void/Library/issues/4) | S19, `rules_manifest.cpp`. Проверить транзитивный набор, конфликты, циклы, диагностику и одинаковый отпечаток при перестановке входа. Игровая схема остаётся у S19. |
|
||||
| [Публикация неизменяемого состояния с ревизией, #5](https://git.faumaray.com/Void/Library/issues/5) | S01, `simulation_runtime.cpp`. Читатели удерживают старую ревизию, пока владелец публикует следующую. При замене мира проверяются инкарнация и сохранность снимка после отказа. |
|
||||
| [Идемпотентные результаты и конфликт повторов, #6](https://git.faumaray.com/Void/Library/issues/6) | S16, `command_dispatcher.cpp`. Готовый примитив должен вернуть первоначальные принятые и отклонённые результаты, распознать другой запрос под тем же номером и отсечь старую инкарнацию. |
|
||||
| [Восстанавливаемый счётчик ID с проверкой исчерпания, #7](https://git.faumaray.com/Void/Library/issues/7) | [S06](systems/S06.md) и [S04](systems/S04.md), счётчики в `WorldState` и операции выделения в `world.cpp`. Переход проверяется на двух независимых мирах, сохранении после удаления наибольшего ID и атомарном отказе у верхней границы. В проверенном pin `SeqId<Tag>` использует общий счётчик для тега. [API](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Core/Counted.hpp) |
|
||||
| [Условное резервирование и перенос количеств в памяти, #8](https://git.faumaray.com/Void/Library/issues/8) | Для реестра резервов [S04](systems/S04.md) и передачи между владельцами [S06](systems/S06.md). Проверка замены должна покрыть конкуренцию за последнюю единицу, полный откат отказа, отмену с грузом и однократное применение повторной доставки после загрузки. Закреплённая `Storage::Batch` применяет условия к ключам и значениям движка хранения. Правила собственности и рецепты определяет игра. [API пакетных операций](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Storage/Batch.hpp) |
|
||||
|
||||
При подготовке последовательного эталона 2 декабря 2026 года публичный `main` указывал на закреплённый `7b0fea6`. Для сравнения прототипа доступны `World::write_save` поверх Void Binary/Core и проверки Void Testing. Игровая ветка эталона может прямо вызвать тот же расчёт назначения, маршрута и движения без создания исполнителя. Она сохраняет тот же порядок применения результатов. Журнал приказов и сравнение состояния конкретной колонии принадлежат тесту игры. Новый универсальный исполнитель для этого не требуется. [Кодек игры](../../engine/src/world_save.cpp) · [Набор проверок игры](../../tests/core_tests.cpp)
|
||||
|
||||
Для будущей замены пула `FuturePool::try_submit` принимает работу через `ThreadExecutor` и возвращает future. Занятые исполнением задачи входят в предел допуска. При отказе вызываемая функция остаётся у отправителя. Остановка закрывает допуск и завершает принятые задачи. Режим после `join()` не обслуживает новые отправки в `FuturePool`. При замене игрового пула проверить повтор или исполнение каждой отклонённой работы, завершение уже принятых задач до разрушения их данных, исключения и частичный запуск на Windows. [Публичный FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/FuturePool.hpp) · [Контракт ThreadExecutor](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/ThreadExecutor.hpp)
|
||||
|
||||
У текущего `settlement::WorkerPool` есть отправка функции, получение future, число потоков и ожидание принятых работ при завершении. Сверить эти четыре операции с `ThreadExecutor + FuturePool`. Начать перенос с эталонной партии, затем испытать переполнение, частичный запуск и остановку. При переполнении симуляция должна выполнить тот же набор логических работ с тем же результатом. Выбранный вариант измерить на малой партии и на нагруженном городе. Существующие тесты Void проверяют поведение утилит, игровые тесты должны дополнительно сравнить хеши мира. [Текущий пул](../../engine/src/worker_pool.cpp) · [Проверки FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/FuturePool.cpp) · [Проверки запуска потоков](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/ThreadExecutor.cpp)
|
||||
|
||||
## Публикация мира и приём команд
|
||||
|
||||
Клиент протокола 11 проверяет, можно ли передать ему текущее состояние. Пока он готовит приказ, владелец может опубликовать несовместимое состояние в той же партии. Проверка актуальности снимка и помещение приказа в очередь должны выполняться под одной блокировкой владельца. Тест задерживает клиента после получения старого снимка, отменяет заказ на хосте и проверяет, что номер гостевого приказа и состояние колонии сохранились. При обратном порядке уже принятый приказ должен завершиться. Публичный `FuturePool::try_submit` проверяет ёмкость своего исполнителя. Предложение связать допуск с публикацией передано сопровождающим. [Void/Library #16](https://git.faumaray.com/Void/Library/issues/16) · [Владелец симуляции](../../engine/src/simulation_runtime.cpp) · [Сетевой адаптер](../../app/lan_session_win32.cpp)
|
||||
|
||||
## Подготовка воксельного мира M02
|
||||
|
||||
Для проверки порядка завершения реальных вычислений [S21](systems/S21.md) использует работающий `FuturePool`. У `Testing::DeterministicRun` есть очередь управляемых тестовых действий. Для потактного теста игры требуется отдельно зарегистрировать возврат конкретной функции исполнителя, переставить две такие операции и проверить тот же результат мира на 2/6/12 потоках и при заполненной очереди. Предложение относится к тестовому адаптеру реальных задач. [Void/Library #15](https://git.faumaray.com/Void/Library/issues/15) · [Адаптер исполнения игры](../../engine/include/settlement/core/worker_pool.hpp)
|
||||
|
||||
Для будущей генерации и навигации проверены публичные заголовки и тесты того же pin. Отдельная программа, собранная для Windows x64 GCC 16.2, прошла под Wine 11. Проверены граничная арифметика, побайтовый FNV-1a, начальное значение Xoshiro256 для seed 42, очередность обхода графа и ограничение объёма поиска. Координаты и seed можно кодировать фиксированными полями через `Binary::Writer::writeLittle` и хешировать средствами `Void::Hash`. Для равных приоритетов поиска порядок задаёт клиент. [Задание исследования](../agent-workflow/tasks/M02-R1.md) · [Числовые операции](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Math/Numeric.hpp)
|
||||
|
||||
| Запрос в Void/Library | Локальный потребитель и проверка замены |
|
||||
|---|---|
|
||||
| [Восстановление потока RNG и воспроизводимый выбор целого, #10](https://git.faumaray.com/Void/Library/issues/10) | [Генератор прототипа](../../engine/include/settlement/core/deterministic_rng.hpp) и [S02](systems/S02.md). Сохранять алгоритм и версию генератора. Сверить фиксированные значения последовательности, продолжение после смешанных вызовов и независимость двух потоков. Исторический SplitMix64 должен воспроизводить старый ландшафт. |
|
||||
| [Частное и остаток для знаковых координат, #11](https://git.faumaray.com/Void/Library/issues/11) | [S02](systems/S02.md). У `checked_div(-1,32)` результат 0. Для чанка требуются чанк −1 и локальная координата 31. Проверить обе стороны каждой границы и предельные значения знакового типа. |
|
||||
| [Обход вокселей лучом, #12](https://git.faumaray.com/Void/Library/issues/12) | [S17](systems/S17.md). Проверить выбранную ячейку и грань при попадании в угол 32³ с обеих сторон, на отрицательных координатах и при ограничении длины. Камера и отсечение высоты принадлежат клиенту. |
|
||||
| [Набор прочитанных ревизий, #13](https://git.faumaray.com/Void/Library/issues/13) | [Маршруты S03](systems/S03.md) и [геометрия S17](systems/S17.md). Смена опоры в соседнем чанке сбрасывает маршрут, открытие границы делает прежний отрицательный ответ устаревшим, а правка непрочитанного чанка сохраняет результат. При смене инкарнации результат устаревает целиком. |
|
||||
| [Ограниченные разреженные объёмы и атомарные правки страниц, #14](https://git.faumaray.com/Void/Library/issues/14) | [Каталог чанков S02](systems/S02.md). Проверить изменение двух чанков одной командой, точный отказ при устаревшей ревизии либо исчерпанном бюджете и воспроизводимый порядок дельт. Генератор, материалы и такт активации остаются в игре. |
|
||||
|
||||
[Мастер-план](../../PLAN.md)
|
||||
|
||||
В M02 вызов `Void::Async::FuturePool::try_submit` допускает ограниченное число работ и оставляет вызывающей стороне функцию при отказе. Закреплённая версия позволяет готовить независимые страницы и сверять результат по сохранённому идентификатору запроса. Для общего такта игра собирает все необходимые страницы и публикует каталог один раз. Готовые и устаревшие результаты также входят в бюджет игры. В существующих задачах описаны чтение ограниченного файла Windows, замена публикации и восстановление набора прочитанных ревизий. [Исследование M02](../agent-workflow/tasks/M02-R2.md) · [Исходники FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/FuturePool.hpp) · [Windows-файл](https://git.faumaray.com/Void/Library/issues/9) · [Публикации](https://git.faumaray.com/Void/Library/issues/5) · [Ревизии](https://git.faumaray.com/Void/Library/issues/13)
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/rules_manifest.hpp"
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t checkpoint_version = 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;
|
||||
inline constexpr std::size_t max_checkpoint_bytes =
|
||||
24 + max_checkpoint_metadata_bytes + max_checkpoint_body_bytes + 32;
|
||||
|
||||
enum class CheckpointError : std::uint8_t {
|
||||
InvalidFrame,
|
||||
UnsupportedVersion,
|
||||
LimitExceeded,
|
||||
IntegrityMismatch,
|
||||
InvalidIdentity,
|
||||
RulesMismatch,
|
||||
InvalidWorld,
|
||||
ResourceFailure
|
||||
};
|
||||
|
||||
struct CheckpointDiagnostic {
|
||||
CheckpointError code;
|
||||
std::string field;
|
||||
std::string package;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct WorldCheckpoint {
|
||||
std::unique_ptr<World> world;
|
||||
Void::Uuid::Uuid world_id;
|
||||
std::uint64_t city;
|
||||
RulesManifest rules;
|
||||
};
|
||||
|
||||
// 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 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<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city,
|
||||
const RulesManifest& rules);
|
||||
|
||||
// Input is bounded and integrity checked before package or World decoding.
|
||||
// Rules are resolved from the installed catalog and must match the complete
|
||||
// saved closure exactly. The returned candidate is independent of any live world.
|
||||
[[nodiscard]] std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
std::string_view bytes, std::span<const RulePackage> installed,
|
||||
std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel);
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/save_service.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class CheckpointFileError {
|
||||
Io, TooLarge, UnsupportedFormat, InvalidCheckpoint, InvalidLegacy,
|
||||
IdentityGeneration, ResourceFailure, ReaderFailure,
|
||||
};
|
||||
|
||||
struct CheckpointFileDiagnostic {
|
||||
CheckpointFileError code;
|
||||
std::string message;
|
||||
std::uint32_t native_error = 0;
|
||||
// Present for a modern codec failure, including the exact incompatible package.
|
||||
std::optional<CheckpointDiagnostic> checkpoint;
|
||||
};
|
||||
|
||||
using CheckpointLoadResult = std::expected<WorldCheckpoint, CheckpointFileDiagnostic>;
|
||||
enum class CheckpointLoadAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
|
||||
|
||||
struct CheckpointLoadSubmission {
|
||||
CheckpointLoadAdmission admission = CheckpointLoadAdmission::InvalidRequest;
|
||||
std::uint64_t request_id = 0;
|
||||
std::future<CheckpointLoadResult> completion;
|
||||
};
|
||||
|
||||
enum class CheckpointReadPhase { Opened, BeforeRead };
|
||||
|
||||
struct CheckpointFilesOptions {
|
||||
std::size_t load_capacity = 4; // Includes the running read.
|
||||
std::size_t save_capacity = 8;
|
||||
std::size_t max_load_bytes = max_checkpoint_bytes;
|
||||
// Diagnostic/test seam on the reader. Captures must outlive shutdown.
|
||||
// Calling shutdown from this observer throws logic_error.
|
||||
std::function<void(CheckpointReadPhase)> read_observer;
|
||||
};
|
||||
|
||||
// Keep one instance for the window lifetime so accepted saves retain FIFO order
|
||||
// across world/session replacements. Workers own their paths, catalog and held
|
||||
// snapshots. The caller owns load-ticket fencing and UI completion handling.
|
||||
class CheckpointFiles {
|
||||
public:
|
||||
explicit CheckpointFiles(CheckpointFilesOptions options = {});
|
||||
explicit CheckpointFiles(std::vector<RulePackage> installed, CheckpointFilesOptions options = {});
|
||||
~CheckpointFiles();
|
||||
CheckpointFiles(const CheckpointFiles&) = delete;
|
||||
CheckpointFiles& operator=(const CheckpointFiles&) = delete;
|
||||
|
||||
// Obtain a healthy immutable view with SimulationRuntime::snapshot_for_save().
|
||||
// Materialization runs on the existing SaveService writer, bounded to
|
||||
// max_checkpoint_bytes. Rejected calls do not retain the snapshot.
|
||||
[[nodiscard]] SaveSubmission try_save(
|
||||
const std::filesystem::path& destination,
|
||||
const std::shared_ptr<const PublishedSnapshot>& snapshot);
|
||||
// Opens once and checks actual size/EOF under the byte limit. Modern failures
|
||||
// retain their diagnostics. Legacy imports receive a fresh stable world UUID
|
||||
// and the exact supported default manifest from this instance's catalog.
|
||||
[[nodiscard]] CheckpointLoadSubmission try_load(
|
||||
const std::filesystem::path& source, std::size_t workers = min_worker_count,
|
||||
ExecutionMode mode = ExecutionMode::Parallel);
|
||||
// Closes admission and drains both services, without holding the admission
|
||||
// mutex while joining. Destruction requires callers to stop using this object.
|
||||
void shutdown();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/checkpoint.hpp"
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class ColonyProfile { Default, PlankBeds };
|
||||
|
||||
// Constructed only after the selected packages match an implemented profile.
|
||||
class ColonyRules {
|
||||
public:
|
||||
[[nodiscard]] ColonyProfile profile() const noexcept { return profile_; }
|
||||
[[nodiscard]] BedConstructionMode bed_mode() const noexcept { return bed_mode_; }
|
||||
[[nodiscard]] const RulesManifest& manifest() const noexcept { return manifest_; }
|
||||
|
||||
private:
|
||||
ColonyRules(ColonyProfile profile, BedConstructionMode beds, RulesManifest manifest);
|
||||
ColonyProfile profile_;
|
||||
BedConstructionMode bed_mode_;
|
||||
RulesManifest manifest_;
|
||||
friend std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest&);
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<ColonyRules, RulesDiagnostic> compile_colony_rules(const RulesManifest&);
|
||||
[[nodiscard]] std::expected<ColonyRules, RulesDiagnostic> colony_rules(ColonyProfile);
|
||||
|
||||
// Initializes both the enacted mechanics and their frozen package identities.
|
||||
[[nodiscard]] std::expected<WorldCheckpoint, CheckpointDiagnostic> make_colony_checkpoint(
|
||||
ColonyProfile profile, std::size_t workers = min_worker_count,
|
||||
ExecutionMode mode = ExecutionMode::Parallel);
|
||||
|
||||
// Default rules preserve historical saved bed modes, including inactive worlds.
|
||||
// The optional plank-bed profile requires a saved nonstaged mode. This gate is
|
||||
// game-specific; generic codecs and SimulationRuntime accept caller-owned catalogs.
|
||||
[[nodiscard]] std::expected<void, CheckpointDiagnostic> validate_colony_checkpoint(
|
||||
const WorldCheckpoint&);
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,144 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t command_envelope_version = 1;
|
||||
|
||||
struct SessionIdentity {
|
||||
Void::Uuid::Uuid world;
|
||||
Void::Uuid::Uuid session;
|
||||
std::uint64_t city = 1;
|
||||
bool operator==(const SessionIdentity&) const = default;
|
||||
};
|
||||
|
||||
// Created by the trusted transport/local adapter, never decoded from payload data.
|
||||
// Reconnected clients keep their assigned slot within the same session.
|
||||
struct TrustedClient {
|
||||
std::uint8_t player;
|
||||
};
|
||||
|
||||
struct CommandPayload {
|
||||
CommandKind kind = CommandKind::PlaceBed;
|
||||
GridPosition cell{};
|
||||
std::uint8_t value = 0;
|
||||
GridPosition destination{};
|
||||
AgentId resident = 0;
|
||||
bool operator==(const CommandPayload&) const = default;
|
||||
};
|
||||
|
||||
struct LegacyCabinPayload {
|
||||
GridPosition cell;
|
||||
GridPosition sawmill;
|
||||
GridPosition stonecutter;
|
||||
bool operator==(const LegacyCabinPayload&) const = default;
|
||||
};
|
||||
|
||||
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<CommandPayload, LegacyCabinPayload,
|
||||
CancelProductionPayload, ResumeProductionPayload>;
|
||||
|
||||
struct CommandEnvelope {
|
||||
std::uint32_t version = command_envelope_version;
|
||||
Void::Uuid::Uuid world;
|
||||
Void::Uuid::Uuid session;
|
||||
std::uint64_t city = 1;
|
||||
std::uint64_t request = 0;
|
||||
SessionPayload payload;
|
||||
};
|
||||
|
||||
enum class DispatchStatus : std::uint8_t {
|
||||
Completed,
|
||||
UnsupportedVersion,
|
||||
WrongWorld,
|
||||
StaleSession,
|
||||
UnauthorizedClient,
|
||||
InvalidRequest,
|
||||
OutOfOrder,
|
||||
Conflict,
|
||||
Busy,
|
||||
Faulted
|
||||
};
|
||||
|
||||
struct DispatchReceipt {
|
||||
DispatchStatus status;
|
||||
// Meaningful for Completed. Revision counts successful dispatcher mutations
|
||||
// in this session, including legacy cabin placement, independently of ticks.
|
||||
CommandStatus command_status = CommandStatus::Unavailable;
|
||||
std::uint64_t tick = 0;
|
||||
std::uint64_t revision = 0;
|
||||
bool operator==(const DispatchReceipt&) const = default;
|
||||
};
|
||||
|
||||
enum class CommandMutationPhase : std::uint8_t { BeforeMutation, AfterMutation };
|
||||
|
||||
struct CommandDispatcherOptions {
|
||||
std::size_t max_receipts_per_client = 65'536;
|
||||
// Optional failure observer around authoritative application. An exception
|
||||
// fences the staged dispatcher, so the owner must discard its candidate.
|
||||
void (*mutation_observer)(CommandMutationPhase) = nullptr;
|
||||
};
|
||||
|
||||
// Single-owner component. The caller must pass the session's authoritative World.
|
||||
// Exact repeats retain their original result for the entire session. At capacity,
|
||||
// new requests receive Busy and stored receipts remain available. No eviction.
|
||||
// Domain rejections consume a request number; transient dispatch errors do not.
|
||||
// Copies may be staged with a candidate World and committed only after publication.
|
||||
// Any mutation exception poisons this instance. Old completed receipts remain
|
||||
// readable, while further effects require a newly constructed session/dispatcher.
|
||||
// Upstream replacement contract and tests: Void/Library#6
|
||||
// https://git.faumaray.com/Void/Library/issues/6
|
||||
class CommandDispatcher {
|
||||
public:
|
||||
explicit CommandDispatcher(SessionIdentity identity, CommandDispatcherOptions options = {});
|
||||
|
||||
[[nodiscard]] const SessionIdentity& identity() const noexcept { return identity_; }
|
||||
[[nodiscard]] std::uint64_t revision() const noexcept { return revision_; }
|
||||
[[nodiscard]] bool faulted() const noexcept { return faulted_; }
|
||||
[[nodiscard]] std::size_t receipt_count(TrustedClient client) const noexcept;
|
||||
[[nodiscard]] std::uint64_t next_request(TrustedClient client) const noexcept;
|
||||
|
||||
[[nodiscard]] DispatchReceipt dispatch(World& world, TrustedClient client, const CommandEnvelope& command);
|
||||
// Invalid context/conflicting reuse returns its dispatch error. An otherwise
|
||||
// valid request without a retained receipt returns nullopt without side effects.
|
||||
[[nodiscard]] std::optional<DispatchReceipt> lookup(TrustedClient client, const CommandEnvelope& command) const;
|
||||
|
||||
private:
|
||||
struct Record {
|
||||
std::uint64_t city;
|
||||
SessionPayload payload;
|
||||
DispatchReceipt receipt{DispatchStatus::Faulted};
|
||||
bool completed = false;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::optional<DispatchStatus> validate_context(
|
||||
TrustedClient client, const CommandEnvelope& command) const noexcept;
|
||||
[[nodiscard]] CommandStatus apply(World& world, TrustedClient client, const CommandEnvelope& command);
|
||||
|
||||
SessionIdentity identity_;
|
||||
CommandDispatcherOptions options_;
|
||||
std::array<std::vector<Record>, colony_player_slots> records_;
|
||||
std::uint64_t revision_ = 0;
|
||||
bool faulted_ = false;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,115 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
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<CustodyLine, custody_material_limit> 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<ReservationId, custody_reservation_limit> reservations{};
|
||||
std::array<CustodyEffect, 11> 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<Reservation, custody_reservation_limit> 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
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <expected>
|
||||
#include <span>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class QuantityTransferError {
|
||||
InvalidStorage,
|
||||
InvalidMaterial,
|
||||
MissingSelection,
|
||||
InvalidStock,
|
||||
InsufficientStock,
|
||||
Overflow,
|
||||
Capacity,
|
||||
};
|
||||
|
||||
// Pick up all lines for source.id; other delivery stops are left alone. Failure
|
||||
// leaves both owners unchanged. Optional output capacity is reserved in the same
|
||||
// commit, after accounting for the space freed by the pickup. No allocation.
|
||||
// This is one physical pickup, not an idempotent transfer or recipe conversion.
|
||||
[[nodiscard]] std::expected<void, QuantityTransferError> withdraw_reserved_materials(
|
||||
Storage& source, Inventory& destination, std::span<const MaterialReservation> materials,
|
||||
bool reserve_output_slot = false) noexcept;
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
using RulesDigest = std::array<std::byte, 32>;
|
||||
|
||||
struct RulesDiagnostic {
|
||||
std::string package;
|
||||
std::string source;
|
||||
std::string field;
|
||||
std::string message;
|
||||
std::size_t byte_offset = 0;
|
||||
};
|
||||
|
||||
struct RulesLimits {
|
||||
std::size_t package_bytes = 256 * 1024;
|
||||
std::size_t catalog_bytes = 4 * 1024 * 1024;
|
||||
std::size_t packages = 128;
|
||||
std::size_t definitions = 1024;
|
||||
std::size_t dependencies = 64;
|
||||
std::size_t references = 64;
|
||||
std::size_t json_depth = 24;
|
||||
std::size_t json_nodes = 16384;
|
||||
};
|
||||
|
||||
struct RuleDefinition {
|
||||
std::string id;
|
||||
std::string kind;
|
||||
std::string canonical_data;
|
||||
std::vector<std::string> references;
|
||||
};
|
||||
|
||||
struct FrozenRulePackage {
|
||||
std::string id;
|
||||
std::string exact_version;
|
||||
RulesDigest content_sha256{};
|
||||
bool operator==(const FrozenRulePackage&) const = default;
|
||||
};
|
||||
|
||||
class RulesManifest;
|
||||
struct RulePackageData;
|
||||
|
||||
// Schema 1 requires schema/id/version/dependencies/exclusive_capabilities/definitions.
|
||||
// Package IDs use lower-case dot-separated segments. Definition IDs and capabilities
|
||||
// use package:local-name. Each definition has id/kind/data/references, where data is
|
||||
// integer-valued strict JSON. Unknown metadata fields are errors. Set-like arrays are
|
||||
// sorted; arrays inside data retain order. Sources are diagnostic labels, never paths
|
||||
// to execute or open. Only one installed version of each package ID is allowed.
|
||||
class RulePackage {
|
||||
public:
|
||||
[[nodiscard]] const FrozenRulePackage& identity() const noexcept;
|
||||
[[nodiscard]] std::span<const RuleDefinition> definitions() const noexcept;
|
||||
[[nodiscard]] std::string_view canonical_json() const noexcept;
|
||||
|
||||
private:
|
||||
explicit RulePackage(std::shared_ptr<const RulePackageData> data);
|
||||
std::shared_ptr<const RulePackageData> data_;
|
||||
friend std::expected<RulePackage, RulesDiagnostic> load_rule_package(
|
||||
std::string_view, std::string_view, const RulesLimits&);
|
||||
friend std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
|
||||
std::span<const RulePackage>, std::span<const std::string>, const RulesLimits&);
|
||||
};
|
||||
|
||||
class RulesManifest {
|
||||
public:
|
||||
[[nodiscard]] std::span<const FrozenRulePackage> packages() const noexcept { return packages_; }
|
||||
[[nodiscard]] const RulesDigest& fingerprint() const noexcept { return fingerprint_; }
|
||||
// Schema-tagged canonical UTF-8 bytes shared by persistence and handshake callers.
|
||||
[[nodiscard]] std::string_view canonical_json() const noexcept { return canonical_json_; }
|
||||
bool operator==(const RulesManifest&) const = default;
|
||||
|
||||
private:
|
||||
RulesManifest(std::vector<FrozenRulePackage>, RulesDigest, std::string);
|
||||
std::vector<FrozenRulePackage> packages_;
|
||||
RulesDigest fingerprint_{};
|
||||
std::string canonical_json_;
|
||||
friend std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
|
||||
std::span<const RulePackage>, std::span<const std::string>, const RulesLimits&);
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<RulePackage, RulesDiagnostic> load_rule_package(
|
||||
std::string_view source, std::string_view json, const RulesLimits& limits = {});
|
||||
|
||||
// Resolves selected IDs and their transitive dependencies. Prerelease dependencies
|
||||
// require an exact constraint equal to that full version, optionally prefixed by '='.
|
||||
// Content digests are computed from the parsed content and never trusted from input.
|
||||
[[nodiscard]] std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
|
||||
std::span<const RulePackage> available, std::span<const std::string> selected,
|
||||
const RulesLimits& limits = {});
|
||||
|
||||
[[nodiscard]] std::expected<std::vector<RulePackage>, RulesDiagnostic> builtin_rule_packages();
|
||||
[[nodiscard]] std::expected<RulesManifest, RulesDiagnostic> default_rules_manifest();
|
||||
[[nodiscard]] std::string rules_digest_hex(const RulesDigest& digest);
|
||||
|
||||
} // namespace settlement
|
||||
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user