Compare commits

..
Author SHA1 Message Date
faumaray 59eb683404 docs(m02): record signed slice picking and WARP acceptance evidence 2026-12-03 00:15:16 +03:00
faumaray 9a55167201 integrate(m02): include the rendering branch publication history 2026-12-03 00:11:22 +03:00
faumaray a6989f35ad integrate(m02): include independently verified D3D11 voxel slices and picking 2026-12-03 00:11:22 +03:00
faumaray 41748ac964 docs(m02): record verified voxel region and cross-floor navigation foundation 2026-12-03 00:06:37 +03:00
faumaray 129d7f204b integrate(m02): stage immutable height-slice rendering for verification 2026-12-03 00:05:34 +03:00
faumaray 14987b240e integrate(m02): preserve valid off-window terrain interactions 2026-12-03 00:04:09 +03:00
faumaray 2017e5685a fix(navigation): preserve work contacts beyond the current search window 2026-12-03 00:04:09 +03:00
faumaray c40d9b2ae2 integrate(m02): include proven frontier navigation and bounded allocation 2026-12-02 23:57:01 +03:00
faumaray 17389b23d7 fix(navigation): distinguish reachable missing terrain from incidental reads 2026-12-02 23:57:01 +03:00
faumaray 6fdf5a90f7 Base the playable voxel milestone on the verified M01 exit 2026-12-02 23:49:43 +03:00
faumaray 3f1817a285 Integrate voxel movement and interaction queries with authoritative saves 2026-12-02 23:49:43 +03:00
faumaray 15887d5613 Record M01 software acceptance and trace the new VoidLibrary contract 2026-12-02 23:48:11 +03:00
faumaray 51311ca104 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray 69ce32c2b6 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray cd75eab191 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray f60375a9f3 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray 5dd0e35093 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 77781a5f1f Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 22420e9fe2 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 89bbb81317 Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray ba00651b45 Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray 7a7ff32e14 Verify door, stair and work access across signed chunk boundaries 2026-12-02 23:46:14 +03:00
faumaray e7046a92a1 Exercise settler routes against the real immutable voxel region
# Conflicts:
#	CMakeLists.txt
2026-12-02 23:39:19 +03:00
faumaray ee1eca7571 Trace bounded settler paths and their consulted voxel revisions 2026-12-02 23:39:09 +03:00
17 changed files with 1237 additions and 0 deletions

No files matched your search

+2
View File
@@ -49,6 +49,7 @@ add_library(settlement_core
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
@@ -143,6 +144,7 @@ if(BUILD_TESTING)
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
)
+4
View File
@@ -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.
+50
View File
@@ -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.
+50
View File
@@ -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)
+49
View File
@@ -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.
+48
View File
@@ -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.
+49
View File
@@ -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.
+53
View File
@@ -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.
+49
View File
@@ -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.
+52
View File
@@ -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.
+8
View File
@@ -13,6 +13,14 @@
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)
## Первый переход с текущего клиента
### Потактный эталон прототипа
+7
View File
@@ -40,3 +40,10 @@
- Сценарий работает на 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)
+28
View File
@@ -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
View File
@@ -49,6 +49,10 @@
У текущего `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)
@@ -64,3 +68,5 @@
| [Ограниченные разреженные объёмы и атомарные правки страниц, #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,84 @@
#pragma once
#include "settlement/core/voxel_region.hpp"
#include <Void/Core/Uuid.hpp>
#include <cstddef>
#include <optional>
#include <span>
#include <stop_token>
#include <vector>
namespace settlement {
enum class VoxelNavigationStatus {
Reachable, Unreachable, Unavailable, SearchBoundary, LimitExceeded,
Cancelled, InvalidInput, AllocationFailed
};
struct VoxelNavigationLimits {
std::size_t max_vertices = 65'536;
std::size_t max_steps = 1'000'000;
std::size_t max_samples = 4'000'000;
std::size_t max_scratch_bytes = 8 * 1024 * 1024;
std::size_t max_goals = 64;
std::size_t max_dependencies = 4096;
};
struct VoxelReadSet {
RegionId region = 0;
Void::Uuid::Uuid session;
// Sorted unique chunk coordinates, including blocked and unavailable reads.
std::vector<ChunkStamp> chunks;
[[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept;
};
struct VoxelTraversalResult {
VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput;
VoxelReadSet consulted;
};
struct VoxelPathRequest {
RegionId region = 0;
Void::Uuid::Uuid session;
VoxelPosition start;
// The caller chooses a finite search window contained in the region.
VoxelBounds search_bounds;
std::vector<VoxelPosition> goals;
VoxelNavigationLimits limits;
};
struct VoxelPathResult {
VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput;
std::optional<VoxelPosition> goal;
// Excludes start, includes goal. An already satisfied goal has an empty route.
std::vector<VoxelPosition> route;
std::size_t cost = 0;
std::size_t visited = 0;
VoxelReadSet consulted;
};
// Ordinary settlers occupy the foot cell and the cell above, with solid support
// below. A transition is one cardinal horizontal move and at most one step.
[[nodiscard]] VoxelTraversalResult voxel_standing(
const VoxelRegion& world, const Void::Uuid::Uuid& session, VoxelPosition foot,
VoxelNavigationLimits limits = {}, std::stop_token stop = {});
[[nodiscard]] VoxelTraversalResult voxel_transition(
const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits = {},
std::stop_token stop = {});
// Finds a shortest known route within the requested window. Equal costs choose
// the lexicographically first goal; each vertex's neighbors use coordinate order.
// A negative result distinguishes missing chunks and an escapable window edge.
[[nodiscard]] VoxelPathResult find_voxel_path(
const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop = {});
// Candidate feet touch the target by a face of either body cell, or stand one
// cell above / two below it. The target must be loaded. Work policy stays with
// the owner; navigation only proves contact and a supported clear body volume.
// request.goals is ignored; the same bounds, identity and limits apply.
[[nodiscard]] VoxelPathResult find_voxel_interaction_path(
const VoxelRegion& world, const VoxelPathRequest& request,
VoxelPosition target, std::stop_token stop = {});
} // namespace settlement
+306
View File
@@ -0,0 +1,306 @@
#include "settlement/core/voxel_navigation.hpp"
#include <Void/Algorithms/Graph.hpp>
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <limits>
#include <new>
#include <stdexcept>
namespace settlement {
namespace {
using Status = VoxelNavigationStatus;
struct NavigationFailure { Status status; };
std::optional<VoxelPosition> offset(VoxelPosition p, int x, int y, int z) noexcept {
const auto nx = std::int64_t{p.x} + x, ny = std::int64_t{p.y} + y, nz = std::int64_t{p.z} + z;
constexpr auto low = std::numeric_limits<std::int32_t>::min();
constexpr auto high = std::numeric_limits<std::int32_t>::max();
if (nx < low || nx > high || ny < low || ny > high || nz < low || nz > high) return {};
return VoxelPosition{static_cast<std::int32_t>(nx), static_cast<std::int32_t>(ny), static_cast<std::int32_t>(nz)};
}
bool valid_bounds(const VoxelBounds& b, const VoxelBounds& region) noexcept {
return b.lower.x < b.upper.x && b.lower.y < b.upper.y && b.lower.z < b.upper.z &&
b.lower.x >= region.lower.x && b.lower.y >= region.lower.y && b.lower.z >= region.lower.z &&
b.upper.x <= region.upper.x && b.upper.y <= region.upper.y && b.upper.z <= region.upper.z;
}
class Queries {
public:
Queries(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelNavigationLimits limits, std::stop_token stop)
: world_(world), limits_(limits), stop_(stop), reads{world.descriptor().id, session, {}} {
if (session.is_nil()) throw NavigationFailure{Status::InvalidInput};
if (limits.max_dependencies > reads.chunks.max_size()) throw NavigationFailure{Status::LimitExceeded};
const auto bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
if (!bytes || *bytes > limits.max_scratch_bytes) throw NavigationFailure{Status::LimitExceeded};
reads.chunks.reserve(limits.max_dependencies);
}
VoxelSample sample(VoxelPosition p) {
if (stop_.stop_requested()) throw NavigationFailure{Status::Cancelled};
if (samples_ == limits_.max_samples) throw NavigationFailure{Status::LimitExceeded};
++samples_;
auto value = world_.sample(p);
auto at = std::lower_bound(reads.chunks.begin(), reads.chunks.end(), value.stamp.coordinate,
[](const auto& stamp, const auto& coordinate) { return stamp.coordinate < coordinate; });
if (at == reads.chunks.end() || at->coordinate != value.stamp.coordinate) {
if (reads.chunks.size() == limits_.max_dependencies) throw NavigationFailure{Status::LimitExceeded};
reads.chunks.insert(at, value.stamp);
}
return value;
}
Status standing(VoxelPosition foot) {
const auto above = offset(foot, 0, 0, 1), below = offset(foot, 0, 0, -1);
if (!above || !below) return Status::Unreachable;
const auto body = sample(foot), head = sample(*above), support = sample(*below);
// A known obstruction is conclusive even if another cell is unavailable.
if (body.availability == VoxelAvailability::Outside || head.availability == VoxelAvailability::Outside ||
support.availability == VoxelAvailability::Outside ||
(body.availability == VoxelAvailability::Loaded && voxel_blocks_passage(body.material)) ||
(head.availability == VoxelAvailability::Loaded && voxel_blocks_passage(head.material)) ||
(support.availability == VoxelAvailability::Loaded && !voxel_provides_support(support.material))) return Status::Unreachable;
if (body.availability == VoxelAvailability::Unavailable || head.availability == VoxelAvailability::Unavailable ||
support.availability == VoxelAvailability::Unavailable) return Status::Unavailable;
return Status::Reachable;
}
Status transition(VoxelPosition from, VoxelPosition to) {
const auto dx = std::int64_t{to.x} - from.x, dy = std::int64_t{to.y} - from.y;
const auto dz = std::int64_t{to.z} - from.z;
if (!((dx == -1 || dx == 1) && dy == 0) && !((dy == -1 || dy == 1) && dx == 0)) return Status::Unreachable;
if (dz < -1 || dz > 1) return Status::Unreachable;
const auto first = standing(from), second = standing(to);
Status swept = Status::Reachable;
if (dz != 0) {
const auto upper = offset(dz > 0 ? from : to, 0, 0, 2);
if (!upper) return Status::Unreachable;
const auto cell = sample(*upper);
if (cell.availability == VoxelAvailability::Outside ||
(cell.availability == VoxelAvailability::Loaded && voxel_blocks_passage(cell.material))) swept = Status::Unreachable;
else if (cell.availability == VoxelAvailability::Unavailable) swept = Status::Unavailable;
}
if (first == Status::Unreachable || second == Status::Unreachable || swept == Status::Unreachable) return Status::Unreachable;
if (first == Status::Unavailable || second == Status::Unavailable || swept == Status::Unavailable) return Status::Unavailable;
return Status::Reachable;
}
const VoxelRegion& world_;
VoxelNavigationLimits limits_;
std::stop_token stop_;
VoxelReadSet reads;
private:
std::size_t samples_ = 0;
};
struct NeighborList {
std::array<std::size_t, 12> values{};
std::size_t size = 0;
auto begin() const { return values.begin(); }
auto end() const { return values.begin() + static_cast<std::ptrdiff_t>(size); }
};
class WalkingGraph {
public:
WalkingGraph(Queries& queries, VoxelBounds bounds, std::size_t sx, std::size_t sy, std::size_t count)
: queries_(queries), bounds_(bounds), sx_(sx), sy_(sy), count_(count) {}
std::size_t vertex_count() const noexcept { return count_; }
std::size_t index(VoxelPosition p) const noexcept {
return static_cast<std::size_t>(std::int64_t{p.x} - bounds_.lower.x) + sx_ *
(static_cast<std::size_t>(std::int64_t{p.y} - bounds_.lower.y) + sy_ *
static_cast<std::size_t>(std::int64_t{p.z} - bounds_.lower.z));
}
VoxelPosition position(std::size_t i) const noexcept {
return {static_cast<std::int32_t>(bounds_.lower.x + static_cast<std::int64_t>(i % sx_)),
static_cast<std::int32_t>(bounds_.lower.y + static_cast<std::int64_t>((i / sx_) % sy_)),
static_cast<std::int32_t>(bounds_.lower.z + static_cast<std::int64_t>(i / (sx_ * sy_)))};
}
NeighborList neighbors(std::size_t i) const {
NeighborList result;
const auto from = position(i);
// This is lexicographic VoxelPosition order, including all step heights.
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
for (auto direction : directions) for (int dz = -1; dz <= 1; ++dz) {
const auto to = offset(from, direction[0], direction[1], dz);
if (!to) continue;
const auto state = queries_.transition(from, *to);
// Only inconclusive edges out of reached vertices can extend the
// search into missing data. Raw reads may already have been ruled
// out by a known wall, floor or obstructed swept body volume.
if (state == Status::Unavailable) unavailable = true;
if (state != Status::Reachable) continue;
if (!bounds_.contains(*to)) { boundary = true; continue; }
result.values[result.size++] = index(*to);
}
return result;
}
mutable bool boundary = false;
mutable bool unavailable = false;
private:
Queries& queries_;
VoxelBounds bounds_;
std::size_t sx_, sy_, count_;
};
VoxelPathResult search(Queries& queries, const VoxelPathRequest& request,
std::span<const VoxelPosition> goals, std::span<const VoxelPosition> omitted = {}) {
VoxelPathResult result;
if (goals.empty() && omitted.empty()) return result;
const auto& limits = request.limits;
if (omitted.size() > limits.max_goals || goals.size() > limits.max_goals - omitted.size()) {
result.status = Status::LimitExceeded; return result;
}
for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result;
const auto sx = static_cast<std::size_t>(request.search_bounds.upper.x - request.search_bounds.lower.x);
const auto sy = static_cast<std::size_t>(request.search_bounds.upper.y - request.search_bounds.lower.y);
const auto sz = static_cast<std::size_t>(request.search_bounds.upper.z - request.search_bounds.lower.z);
const auto count = Void::Numeric::checked_mul(sx, sy).and_then(
[sz](auto xy) { return Void::Numeric::checked_mul(xy, sz); });
// Void BFS retains four size_t vectors plus visited. Route construction and
// the read-set reserve coexist with them. No adjacency matrix is allocated.
const auto vertex_bytes = count.and_then([](auto size) {
return Void::Numeric::checked_mul(size, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition));
});
const auto read_bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes ||
*count > std::vector<std::size_t>{}.max_size() ||
*count > std::vector<std::uint8_t>{}.max_size() ||
*count > std::vector<VoxelPosition>{}.max_size()) {
result.status = Status::LimitExceeded; return result;
}
const auto bytes = Void::Numeric::checked_add(*vertex_bytes, *read_bytes);
if (!bytes || *bytes > limits.max_scratch_bytes) {
result.status = Status::LimitExceeded; return result;
}
const auto start_state = queries.standing(request.start);
if (start_state != Status::Reachable) { result.status = start_state; return result; }
WalkingGraph graph(queries, request.search_bounds, sx, sy, *count);
const Void::Algorithms::WorkLimits work{
limits.max_vertices, limits.max_steps, limits.max_scratch_bytes - *read_bytes, 1};
auto traversal = Void::Algorithms::bfs(graph, graph.index(request.start), work, queries.stop_);
if (!traversal) {
result.status = traversal.error().code == Void::Algorithms::AlgorithmError::Code::cancelled ? Status::Cancelled : Status::LimitExceeded;
return result;
}
result.visited = traversal->order.size();
std::size_t distance = Void::Algorithms::TraversalResult::npos;
bool possible_goal = false;
for (auto goal : goals) {
// Explicit validation also covers the library's start==target fast path.
const auto standing = queries.standing(goal);
possible_goal = possible_goal || standing != Status::Unreachable;
if (standing != Status::Reachable) continue;
const auto cost = traversal->depth[graph.index(goal)];
if (cost < distance || (cost == distance && cost != Void::Algorithms::TraversalResult::npos &&
(!result.goal || goal < *result.goal))) { distance = cost; result.goal = goal; }
}
if (!result.goal) {
// Interaction contacts outside the selected window still matter to a
// global negative. Their feasibility cannot manufacture a frontier;
// BFS must also have reached a valid exit or an unresolved transition.
for (auto goal : omitted) {
const auto standing = queries.standing(goal);
possible_goal = possible_goal || standing != Status::Unreachable;
}
result.status = Status::Unreachable;
if (possible_goal) {
if (graph.unavailable) result.status = Status::Unavailable;
else if (graph.boundary) result.status = Status::SearchBoundary;
}
return result;
}
result.status = Status::Reachable;
result.cost = distance;
result.route.reserve(distance);
auto vertex = graph.index(*result.goal);
const auto start = graph.index(request.start);
while (vertex != start) {
result.route.push_back(graph.position(vertex));
vertex = traversal->parent[vertex];
}
std::reverse(result.route.begin(), result.route.end());
return result;
}
template<class Function>
VoxelTraversalResult check(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelNavigationLimits limits, std::stop_token stop, Function&& function) {
VoxelTraversalResult result;
result.consulted = {world.descriptor().id, session, {}};
try {
Queries queries(world, session, limits, stop);
try { result.status = function(queries); }
catch (const NavigationFailure& failure) { result.status = failure.status; }
result.consulted = std::move(queries.reads);
} catch (const NavigationFailure& failure) { result.status = failure.status; }
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
return result;
}
VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request,
std::optional<VoxelPosition> target, std::stop_token stop) {
VoxelPathResult result;
result.consulted = {world.descriptor().id, request.session, {}};
if (request.region != world.descriptor().id || request.session.is_nil() ||
!valid_bounds(request.search_bounds, world.descriptor().bounds) ||
!request.search_bounds.contains(request.start)) return result;
try {
Queries queries(world, request.session, request.limits, stop);
try {
if (target) {
const auto cell = queries.sample(*target);
if (cell.availability != VoxelAvailability::Loaded) {
result.status = cell.availability == VoxelAvailability::Unavailable ? Status::Unavailable : Status::InvalidInput;
} else {
std::array<VoxelPosition, 10> goals{};
std::array<VoxelPosition, 10> omitted{};
std::size_t size = 0, omitted_size = 0;
const auto add_goal = [&](std::optional<VoxelPosition> goal) {
if (!goal) return;
if (request.search_bounds.contains(*goal)) goals[size++] = *goal;
else omitted[omitted_size++] = *goal;
};
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
for (auto direction : directions) for (int dz : {-1, 0}) {
add_goal(offset(*target, direction[0], direction[1], dz));
}
for (int dz : {-2, 1}) {
add_goal(offset(*target, 0, 0, dz));
}
result = search(queries, request, std::span(goals.data(), size),
std::span(omitted.data(), omitted_size));
}
} else result = search(queries, request, request.goals);
} catch (const NavigationFailure& failure) { result.status = failure.status; }
result.consulted = std::move(queries.reads);
} catch (const NavigationFailure& failure) { result.status = failure.status; }
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
return result;
}
} // namespace
bool VoxelReadSet::current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept {
return region == world.descriptor().id && !session.is_nil() && epoch == session &&
std::all_of(chunks.begin(), chunks.end(), [&](const auto& stamp) { return world.matches(stamp); });
}
VoxelTraversalResult voxel_standing(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelPosition foot, VoxelNavigationLimits limits, std::stop_token stop) {
return check(world, session, limits, stop, [&](Queries& queries) { return queries.standing(foot); });
}
VoxelTraversalResult voxel_transition(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits, std::stop_token stop) {
return check(world, session, limits, stop, [&](Queries& queries) { return queries.transition(from, to); });
}
VoxelPathResult find_voxel_path(const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop) {
return path(world, request, {}, stop);
}
VoxelPathResult find_voxel_interaction_path(const VoxelRegion& world, const VoxelPathRequest& request,
VoxelPosition target, std::stop_token stop) {
return path(world, request, target, stop);
}
} // namespace settlement
+392
View File
@@ -0,0 +1,392 @@
#include "settlement/core/voxel_navigation.hpp"
#include "settlement/core/worker_pool.hpp"
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <future>
#include <limits>
#include <queue>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace settlement;
using Status = VoxelNavigationStatus;
using Void::Testing::Test;
void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
Void::Uuid::Uuid epoch(std::uint8_t value = 1) {
Void::Uuid::Uuid result;
result.bytes.back() = value;
return result;
}
template<class Material>
void install(VoxelRegion& world, ChunkCoordinate chunk, Material material) {
std::array<MaterialId, voxel_chunk_cells> cells{};
for (std::uint8_t z = 0; z < 32; ++z) for (std::uint8_t y = 0; y < 32; ++y) for (std::uint8_t x = 0; x < 32; ++x) {
const auto p = join_voxel(chunk, {x, y, z});
if (p && world.descriptor().bounds.contains(*p)) cells[*voxel_index({x, y, z})] = material(*p);
}
auto candidate = world.prepare_restored(chunk, 1, cells);
require(candidate.has_value(), "valid fixture page refused");
require(world.activate(std::span(&*candidate, 1)).has_value(), "valid fixture activation refused");
}
void edit(VoxelRegion& world, VoxelPosition p, MaterialId material) {
const VoxelEdit change{p, material, world.sample(p).stamp.revision};
require(world.edit(std::span(&change, 1)).has_value(), "fixture edit refused");
}
VoxelRegion flat(VoxelBounds bounds = {{0, 0, 0}, {8, 8, 4}}) {
VoxelRegion world({1, 42, 1, bounds});
const auto low = split_voxel({static_cast<std::int32_t>(bounds.lower.x), static_cast<std::int32_t>(bounds.lower.y), static_cast<std::int32_t>(bounds.lower.z)}).chunk;
const auto high = split_voxel({static_cast<std::int32_t>(bounds.upper.x - 1), static_cast<std::int32_t>(bounds.upper.y - 1), static_cast<std::int32_t>(bounds.upper.z - 1)}).chunk;
for (auto z = low.z; z <= high.z; ++z) for (auto y = low.y; y <= high.y; ++y) for (auto x = low.x; x <= high.x; ++x) {
install(world, {x, y, z}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; });
}
return world;
}
VoxelPathRequest request(const VoxelRegion& world, VoxelPosition start, std::vector<VoxelPosition> goals) {
return {world.descriptor().id, epoch(), start, world.descriptor().bounds, std::move(goals), {}};
}
VoxelRegion stairs(bool closed) {
VoxelRegion world({7, 42, 1, {{28, 0, 0}, {38, 3, 8}}});
for (int x : {0, 1}) install(world, {x, 0, 0}, [closed](auto p) {
const auto height = std::clamp(p.x - 31, 0, 3);
if (p.z <= height) return MaterialId::Stone;
if ((p.y == 0 || p.y == 2) && p.z <= height + 2) return MaterialId::Stone;
if (p.x == 30 && p.y == 1 && (p.z == 1 || p.z == 2)) return closed ? MaterialId::DoorClosed : MaterialId::DoorOpen;
return MaterialId::Air;
});
return world;
}
void require_route(const VoxelRegion& world, const VoxelPathRequest& query, const VoxelPathResult& result) {
require(result.status == Status::Reachable && result.goal.has_value(), "expected a reachable goal");
require(result.cost == result.route.size(), "cost differs from actual route");
auto from = query.start;
for (auto to : result.route) {
require(voxel_transition(world, query.session, from, to).status == Status::Reachable, "returned route crosses invalid transition");
from = to;
}
require(from == *result.goal && result.consulted.current(world, query.session), "route target or read stamps invalid");
require(std::is_sorted(result.consulted.chunks.begin(), result.consulted.chunks.end(),
[](const auto& a, const auto& b) { return a.coordinate < b.coordinate; }), "read stamps not canonical");
}
struct [[= Void::Testing::name("VoxelNavigationTests")]] VoxelNavigationTests : Void::Testing::Suite<VoxelNavigationTests> {
[[= Void::Testing::tag("voxel-navigation")]] Test doorway_stairs_and_upper_work_contact();
[[= Void::Testing::tag("voxel-navigation")]] Test support_edit_invalidates_route_before_next_step();
[[= Void::Testing::tag("voxel-navigation")]] Test body_headroom_and_step_sweep_are_required();
[[= Void::Testing::tag("voxel-navigation")]] Test missing_support_page_and_negative_answer_are_dependencies();
[[= Void::Testing::tag("voxel-navigation")]] Test known_blockers_do_not_require_unrelated_missing_data();
[[= Void::Testing::tag("voxel-navigation")]] Test reachable_missing_frontier_waits_for_actual_gateway();
[[= Void::Testing::tag("voxel-navigation")]] Test unrepresentable_vector_capacity_is_a_bounded_refusal();
[[= Void::Testing::tag("voxel-navigation")]] Test interaction_contacts_outside_window_need_frontier_evidence();
[[= Void::Testing::tag("voxel-navigation")]] Test unchanged_chunks_and_old_snapshots_remain_usable();
[[= Void::Testing::tag("voxel-navigation")]] Test bounded_search_has_distinct_incomplete_and_error_results();
[[= Void::Testing::tag("voxel-navigation")]] Test invalid_same_goal_and_extreme_coordinate_windows();
[[= Void::Testing::tag("voxel-navigation")]] Test goals_and_neighbors_have_stable_shortest_ties();
[[= Void::Testing::tag("voxel-navigation")]] Test shortest_costs_match_exhaustive_small_grid();
[[= Void::Testing::tag("voxel-navigation")]] Test real_parallel_queries_preserve_route_and_readsets();
};
Test VoxelNavigationTests::doorway_stairs_and_upper_work_contact() {
auto world = stairs(true);
auto query = request(world, {29, 1, 1}, {{36, 1, 4}});
auto blocked = find_voxel_path(world, query);
require(blocked.status == Status::Unreachable, "closed two-cell door was passable");
const std::array changes{VoxelEdit{{30, 1, 1}, MaterialId::DoorOpen, 1}, VoxelEdit{{30, 1, 2}, MaterialId::DoorOpen, 1}};
require(world.edit(changes).has_value(), "door opening failed");
require(!blocked.consulted.current(world, epoch()), "door change retained negative result");
auto found = find_voxel_path(world, query);
require_route(world, query, found);
require(found.cost == 7 && std::any_of(found.route.begin(), found.route.end(), [](auto p) { return p.x == 32 && p.z == 2; }), "path failed actual border stair");
edit(world, {37, 1, 4}, MaterialId::Stone);
auto work = find_voxel_interaction_path(world, query, {37, 1, 4});
require_route(world, query, work);
require(work.goal == VoxelPosition{36, 1, 4}, "upper work position lacks direct face contact");
}
Test VoxelNavigationTests::support_edit_invalidates_route_before_next_step() {
auto world = stairs(false);
const auto query = request(world, {32, 1, 2}, {{36, 1, 4}});
auto found = find_voxel_path(world, query);
require_route(world, query, found);
const auto held = world;
edit(world, {33, 1, 2}, MaterialId::Air);
require(!found.consulted.current(world, epoch()), "support change did not expire route");
require(voxel_standing(world, epoch(), query.start).status == Status::Reachable, "future support edit invalidated current foot");
require(voxel_transition(world, epoch(), query.start, found.route.front()).status == Status::Unreachable, "unsafe stored next step still allowed");
require(find_voxel_path(world, query).status == Status::Unreachable, "missing stair allowed a two-cell rise");
require(found.consulted.current(held, epoch()), "retained immutable geometry changed");
edit(world, {33, 1, 2}, MaterialId::Stone);
require_route(world, query, find_voxel_path(world, query));
}
Test VoxelNavigationTests::body_headroom_and_step_sweep_are_required() {
auto world = flat();
require(voxel_standing(world, epoch(), {2, 2, 1}).status == Status::Reachable, "ordinary stance refused");
edit(world, {3, 2, 1}, MaterialId::Stone);
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "single stair refused");
edit(world, {2, 2, 3}, MaterialId::Stone);
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Unreachable, "step rose through source ceiling");
require(voxel_transition(world, epoch(), {3, 2, 2}, {2, 2, 1}).status == Status::Unreachable, "step descended through swept ceiling");
edit(world, {2, 2, 3}, MaterialId::Air);
edit(world, {3, 2, 3}, MaterialId::DoorClosed);
require(voxel_standing(world, epoch(), {3, 2, 2}).status == Status::Unreachable, "head entered closed upper door");
edit(world, {3, 2, 3}, MaterialId::DoorOpen);
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "open door blocked head");
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 3, 1}).status == Status::Unreachable, "diagonal corner cutting accepted");
require(voxel_transition(world, epoch(), {2, 2, 1}, {2, 2, 2}).status == Status::Unreachable, "unsupported vertical movement accepted");
}
Test VoxelNavigationTests::missing_support_page_and_negative_answer_are_dependencies() {
VoxelRegion world({1, 42, 1, {{-3, 0, -1}, {3, 3, 4}}});
install(world, {-1, 0, 0}, [](auto) { return MaterialId::Air; });
install(world, {0, 0, 0}, [](auto) { return MaterialId::Air; });
auto check = voxel_standing(world, epoch(), {-1, 1, 0});
require(check.status == Status::Unavailable, "unloaded support treated as empty or solid");
require(std::any_of(check.consulted.chunks.begin(), check.consulted.chunks.end(), [](const auto& s) { return s.coordinate == ChunkCoordinate{-1, 0, -1} && s.availability == VoxelAvailability::Unavailable; }), "missing support page omitted from reads");
install(world, {-1, 0, -1}, [](auto) { return MaterialId::Stone; });
require(!check.consulted.current(world, epoch()), "missing-to-loaded support kept stale result");
require(voxel_standing(world, epoch(), {-1, 1, 0}).status == Status::Reachable, "new support still unavailable");
auto query = request(world, {-1, 1, 0}, {{1, 1, 0}});
auto negative = find_voxel_path(world, query);
require(negative.status == Status::Unavailable, "missing route support was proven unreachable");
install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; });
require(!negative.consulted.current(world, epoch()), "negative path omitted queried missing chunk");
require_route(world, query, find_voxel_path(world, query));
}
Test VoxelNavigationTests::known_blockers_do_not_require_unrelated_missing_data() {
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
install(world, {0, 0, 0}, [](auto p) {
return p.z == 0 || (p.x == 2 && p.z <= 2) ? MaterialId::Stone : MaterialId::Air;
});
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
auto result = find_voxel_path(world, query);
require(result.status == Status::Unreachable, "solid floor and closed wall unnecessarily wait for missing lower page");
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::Unreachable,
"loaded interaction behind known wall unnecessarily waits for missing lower page");
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
return s.coordinate == ChunkCoordinate{0, 0, -1} && s.availability == VoxelAvailability::Unavailable;
}), "conclusively blocked reads lost their actual dependency stamps");
query.goals = {{35, 5, 1}};
result = find_voxel_path(world, query);
require(result.status == Status::Unreachable, "disconnected unknown goal manufactured reachable frontier");
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
return s.coordinate == ChunkCoordinate{1, 0, 0} && s.availability == VoxelAvailability::Unavailable;
}), "unknown goal reads were not retained");
query.goals = {{5, 5, 1}};
query.search_bounds.upper = {8, 6, 4};
require(find_voxel_path(world, query).status == Status::SearchBoundary,
"actual reachable window exit was replaced by irrelevant missing data");
install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; });
query.search_bounds = world.descriptor().bounds;
require(find_voxel_path(world, query).status == Status::Unreachable,
"lower-page activation changed proven blocked reachability");
for (int x : {0, 1}) for (int z : {1, 2}) edit(world, {x, 3, z}, MaterialId::Stone);
query.goals = {{1, 5, 1}};
query.search_bounds.upper.x = 2;
require(find_voxel_path(world, query).status == Status::Unreachable,
"known blocked transitions beyond search window manufactured an exit");
}
Test VoxelNavigationTests::reachable_missing_frontier_waits_for_actual_gateway() {
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
const auto floor = [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; };
install(world, {0, 0, 0}, floor);
auto blocked_goal = request(world, {1, 1, 1}, {{5, 5, 1}});
edit(world, {5, 5, 2}, MaterialId::Stone);
require(find_voxel_path(world, blocked_goal).status == Status::Unreachable,
"missing branch elsewhere manufactured access to conclusively blocked goal");
edit(world, {5, 5, 2}, MaterialId::Air);
auto query = request(world, {1, 1, 1}, {{35, 5, 1}});
auto pending = find_voxel_path(world, query);
require(pending.status == Status::Unavailable, "reachable missing gateway was proven unreachable");
install(world, {1, 0, 0}, floor);
require(!pending.consulted.current(world, epoch()), "gateway activation did not invalidate pending answer");
auto result = find_voxel_path(world, query);
require_route(world, query, result);
require(result.cost == 38, "loaded gateway changed shortest path cost");
}
Test VoxelNavigationTests::unrepresentable_vector_capacity_is_a_bounded_refusal() {
auto world = flat();
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
query.limits.max_dependencies = std::vector<ChunkStamp>{}.max_size() + 1;
query.limits.max_scratch_bytes = std::numeric_limits<std::size_t>::max();
require(find_voxel_path(world, query).status == Status::LimitExceeded, "unrepresentable read reserve escaped path API");
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::LimitExceeded,
"unrepresentable read reserve escaped interaction API");
require(voxel_standing(world, epoch(), query.start, query.limits).status == Status::LimitExceeded,
"unrepresentable read reserve escaped stance API");
require(voxel_transition(world, epoch(), query.start, {2, 1, 1}, query.limits).status == Status::LimitExceeded,
"unrepresentable read reserve escaped transition API");
}
Test VoxelNavigationTests::interaction_contacts_outside_window_need_frontier_evidence() {
auto world = flat();
edit(world, {3, 3, 1}, MaterialId::Stone);
for (auto blocker : {VoxelPosition{2, 3, 2}, VoxelPosition{3, 2, 2}, VoxelPosition{3, 4, 2}, VoxelPosition{3, 3, 3}}) {
edit(world, blocker, MaterialId::Stone);
}
auto query = request(world, {1, 1, 1}, {});
query.search_bounds.upper.x = 6;
auto complete = find_voxel_interaction_path(world, query, {3, 3, 1});
require_route(world, query, complete);
require(complete.goal == VoxelPosition{4, 3, 1}, "expanded window did not reach sole valid contact");
query.search_bounds.upper.x = 4;
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::SearchBoundary,
"clipped valid interaction contact was classified globally unreachable");
// A valid omitted goal cannot manufacture an exit from an enclosed start.
for (auto p : {VoxelPosition{0, 1, 1}, VoxelPosition{1, 0, 1}, VoxelPosition{1, 2, 1}, VoxelPosition{2, 1, 1}}) {
edit(world, p, MaterialId::Stone);
edit(world, {p.x, p.y, 2}, MaterialId::Stone);
}
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::Unreachable,
"omitted contact manufactured an escape from a known enclosed start");
// The only useful contact is beyond x=31, in an unavailable page.
VoxelRegion pending({1, 42, 1, {{0, 0, 0}, {40, 8, 4}}});
install(pending, {0, 0, 0}, [](auto p) {
if (p.z == 0 || p == VoxelPosition{31, 3, 1}) return MaterialId::Stone;
if (p == VoxelPosition{30, 3, 2} || p == VoxelPosition{31, 2, 2} ||
p == VoxelPosition{31, 4, 2} || p == VoxelPosition{31, 3, 3}) return MaterialId::Stone;
return MaterialId::Air;
});
auto partial = request(pending, {29, 1, 1}, {});
partial.search_bounds.upper.x = 32;
const auto waiting = find_voxel_interaction_path(pending, partial, {31, 3, 1});
require(waiting.status == Status::Unavailable, "unresolved interaction exit was proven unreachable");
install(pending, {1, 0, 0}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; });
require(!waiting.consulted.current(pending, epoch()), "missing omitted contact was absent from dependencies");
require(find_voxel_interaction_path(pending, partial, {31, 3, 1}).status == Status::SearchBoundary,
"loaded omitted contact failed to expose reachable window exit");
partial.search_bounds.upper.x = 36;
auto reached = find_voxel_interaction_path(pending, partial, {31, 3, 1});
require_route(pending, partial, reached);
require(reached.goal == VoxelPosition{32, 3, 1}, "expanded gateway did not expose actual contact");
}
Test VoxelNavigationTests::unchanged_chunks_and_old_snapshots_remain_usable() {
auto world = flat({{0, 0, 0}, {100, 8, 4}});
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
query.search_bounds.upper.x = 8;
auto route = find_voxel_path(world, query);
require_route(world, query, route);
edit(world, {97, 2, 1}, MaterialId::Stone);
require(route.consulted.current(world, epoch()), "unconsulted page invalidated a path");
require(!route.consulted.current(world, epoch(2)), "old session accepted same numeric revisions");
VoxelRegion other({2, 42, 1, world.descriptor().bounds});
require(!route.consulted.current(other, epoch()), "another region accepted old route");
}
Test VoxelNavigationTests::bounded_search_has_distinct_incomplete_and_error_results() {
auto world = flat();
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
query.limits.max_vertices = 1;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "vertex budget fabricated unreachable");
query.limits = {}; query.limits.max_scratch_bytes = 8;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "scratch budget ignored");
query.limits = {}; query.limits.max_steps = 1;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "traversal budget fabricated unreachable");
query.limits = {}; query.limits.max_samples = 2;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "material query budget ignored");
query.limits = {}; query.limits.max_dependencies = 0;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "read-set bound ignored");
query.limits = {}; query.limits.max_goals = 0;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "goal bound ignored");
query.limits = {};
std::stop_source cancelled; cancelled.request_stop();
require(find_voxel_path(world, query, cancelled.get_token()).status == Status::Cancelled, "cancellation fabricated unreachable");
auto clipped_interaction = query;
clipped_interaction.search_bounds.upper = {2, 2, 4};
require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::SearchBoundary,
"interaction with all feet clipped fabricated invalid input");
clipped_interaction.region = 2;
require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::InvalidInput,
"clipped interaction bypassed region identity");
query.search_bounds.upper.x = 4; query.goals = {{3, 5, 1}};
for (int y = 0; y < 8; ++y) { edit(world, {2, y, 1}, MaterialId::Stone); edit(world, {2, y, 2}, MaterialId::Stone); }
// The accessible edge at x=0 has no escape (region bound), but y edges do
// not either. Make a window smaller than the region along y as well.
query.search_bounds.upper.y = 6;
require(find_voxel_path(world, query).status == Status::SearchBoundary, "clipped search claimed global unreachability");
VoxelRegion sparse({1, 42, 1, {{std::numeric_limits<std::int32_t>::min(), 0, 0}, {std::int64_t{std::numeric_limits<std::int32_t>::max()} + 1, 8, 4}}});
auto huge = request(sparse, {0, 1, 1}, {{1, 1, 1}});
require(find_voxel_path(sparse, huge).status == Status::LimitExceeded, "sparse huge extent allocated densely");
}
Test VoxelNavigationTests::invalid_same_goal_and_extreme_coordinate_windows() {
auto world = flat();
auto query = request(world, {1, 1, 1}, {{1, 1, 1}});
auto same = find_voxel_path(world, query);
require_route(world, query, same);
require(same.route.empty() && same.cost == 0, "already-at-goal result wrong");
edit(world, {1, 1, 2}, MaterialId::Stone);
require(find_voxel_path(world, query).status == Status::Unreachable, "blocked start==goal bypassed geometry");
query.session = {};
require(find_voxel_path(world, query).status == Status::InvalidInput, "nil session accepted");
for (auto x : {std::numeric_limits<std::int32_t>::min(), std::numeric_limits<std::int32_t>::max() - 3}) {
const VoxelBounds b{{x, 0, 0}, {std::int64_t{x} + 4, 3, 4}};
auto edge = flat(b);
auto edge_query = request(edge, {x, 1, 1}, {{static_cast<std::int32_t>(std::int64_t{x} + 3), 1, 1}});
const auto route = find_voxel_path(edge, edge_query);
require_route(edge, edge_query, route);
require(route.cost == 3, "extreme coordinate route wrapped");
}
}
Test VoxelNavigationTests::goals_and_neighbors_have_stable_shortest_ties() {
auto world = flat();
auto query = request(world, {3, 3, 1}, {{4, 3, 1}, {2, 3, 1}, {3, 4, 1}});
auto result = find_voxel_path(world, query);
require(result.goal == VoxelPosition{2, 3, 1} && result.cost == 1, "equal goals depend on request order");
std::reverse(query.goals.begin(), query.goals.end());
require(find_voxel_path(world, query).route == result.route, "goal order changed route");
query.goals = {{4, 4, 1}};
result = find_voxel_path(world, query);
require(result.route == std::vector<VoxelPosition>{{3, 4, 1}, {4, 4, 1}}, "equal paths violated coordinate neighbor order");
}
Test VoxelNavigationTests::shortest_costs_match_exhaustive_small_grid() {
for (std::uint32_t pattern = 0; pattern < 16; ++pattern) {
std::array<bool, 49> walls{};
for (std::size_t i = 0; i < walls.size(); ++i) walls[i] = ((i * 13 + pattern * 7) % 17) < 4;
walls[8] = false; walls[40] = false;
auto world = flat({{0, 0, 0}, {7, 7, 4}});
std::vector<VoxelEdit> changes;
for (int y = 0; y < 7; ++y) for (int x = 0; x < 7; ++x) if (walls[static_cast<std::size_t>(x + 7 * y)]) {
changes.push_back({{x, y, 1}, MaterialId::Stone, 1}); changes.push_back({{x, y, 2}, MaterialId::Stone, 1});
}
require(world.edit(changes).has_value(), "small oracle fixture failed");
std::array<int, 49> distance; distance.fill(-1); distance[8] = 0;
std::queue<int> queue; queue.push(8);
while (!queue.empty()) {
const auto v = queue.front(); queue.pop();
for (auto d : std::array<std::array<int, 2>, 4>{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}}) {
const int x = v % 7 + d[0], y = v / 7 + d[1];
if (x < 0 || x >= 7 || y < 0 || y >= 7) continue;
const auto n = static_cast<std::size_t>(x + 7 * y);
if (walls[n] || distance[n] >= 0) continue;
distance[n] = distance[static_cast<std::size_t>(v)] + 1; queue.push(static_cast<int>(n));
}
}
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
auto result = find_voxel_path(world, query);
if (distance[40] < 0) require(result.status == Status::Unreachable, "oracle blocked path found");
else {
require_route(world, query, result);
require(result.cost == static_cast<std::size_t>(distance[40]), "Void graph route differs from exhaustive grid cost");
}
}
}
Test VoxelNavigationTests::real_parallel_queries_preserve_route_and_readsets() {
const auto world = stairs(false);
const auto query = request(world, {29, 1, 1}, {{36, 1, 4}});
const auto expected = find_voxel_path(world, query);
require_route(world, query, expected);
for (std::size_t workers : {2U, 6U, 12U}) {
WorkerPool pool(workers);
std::vector<std::future<VoxelPathResult>> futures;
for (int i = 0; i < 12; ++i) futures.push_back(pool.submit([&] { return find_voxel_path(world, query); }));
std::reverse(futures.begin(), futures.end());
for (auto& future : futures) {
auto result = future.get();
require(result.status == expected.status && result.route == expected.route && result.goal == expected.goal &&
result.consulted.chunks == expected.consulted.chunks, "worker completion order altered navigation");
}
}
}
} // namespace