Skip to content
Prev Previous commit
Next Next commit
fix: close the weave-origin holes the review found
meters_to_cell rejects millimetre values at or above 2^31. A dropped legacy op no longer spends budget or returns a consequence. Collapse endpoint b uses the same island check as a. push_ice asserts that bound and still emits the ice sheet after the writes.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 20, 2026
commit bc553b4521a2d2e5721a8d02099683592844c088
84 changes: 84 additions & 0 deletions astraweave-gameplay/src/weaving.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ pub fn apply_weave_op(
if matches!(op.kind, WeaveOpKind::CollapseBridge) && op.b.is_none() {
anyhow::bail!("Collapse needs A->B");
}
if !legacy_geometry_kept(kind, &compiled) {
anyhow::bail!("weave origin is outside the island");
}
match op.kind {
WeaveOpKind::ReinforcePath | WeaveOpKind::RaisePlatform | WeaveOpKind::CollapseBridge => {
if budget.terrain_edits <= 0 {
Expand Down Expand Up @@ -147,6 +150,16 @@ pub fn apply_weave_op(
Ok(consequence)
}

fn legacy_geometry_kept(kind: u8, compiled: &astraweave_weaving::CompiledOp) -> bool {
match kind {
0 | 4 => compiled.fortify.is_some(),
1 => compiled.collapse.is_some(),
2 | 3 => compiled.write_count > 0,
5 => compiled.ice_min_milli.is_some(),
_ => false,
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -663,4 +676,75 @@ mod tests {
"RedirectWind must decrement weather_ops by exactly 1"
);
}

#[test]
fn dropped_origin_does_not_spend_budget_or_return_a_consequence() {
let mut world = create_test_world();
let mut physics = create_test_physics();
let nav_src = vec![];
let mut budget = create_test_budget();
let op = WeaveOp {
kind: WeaveOpKind::FreezeWater,
a: vec3(1.0e20, f32::NAN, f32::INFINITY),
b: None,
budget_cost: 1,
};
let mut logger = |_: String| {};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&op,
&mut logger,
)
.expect_err("a dropped freeze must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.weather_ops, 3);
assert_eq!(budget.terrain_edits, 5);

let reinforce = WeaveOp {
kind: WeaveOpKind::ReinforcePath,
a: vec3(f32::NEG_INFINITY, 0.0, 0.0),
b: None,
budget_cost: 1,
};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&reinforce,
&mut logger,
)
.expect_err("a dropped reinforce must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.terrain_edits, 5);
}

#[test]
fn far_collapse_endpoint_does_not_spend_budget() {
let mut world = create_test_world();
let mut physics = create_test_physics();
let nav_src = vec![];
let mut budget = create_test_budget();
let op = WeaveOp {
kind: WeaveOpKind::CollapseBridge,
a: vec3(0.0, 0.0, 0.0),
b: Some(vec3(1.0e20, 0.0, (i32::MAX as f32) / 1000.0)),
budget_cost: 1,
};
let mut logger = |_: String| {};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&op,
&mut logger,
)
.expect_err("a far collapse endpoint must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.terrain_edits, 5);
}
}
40 changes: 19 additions & 21 deletions astraweave-weaving/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
//! those commands into [`FieldWrite`]s.

use crate::field::{
encode_write, milli_corner, FieldWrite, NullField, Shape, SimField, WriteOp, MAX_FIELD_WRITES,
encode_write, FieldWrite, NullField, Shape, SimField, WriteOp, CELL_MM, MAX_FIELD_WRITES,
};
use crate::mod_queue::{
WeaveCommand, WeaveNode, WeaveScratch, KIND_DECAY, KIND_DENSITY, KIND_GRAVITY, KIND_HEAT,
KIND_PHASE, KIND_VOLUME, KIND_WIND, MAX_WEAVE_COMMANDS,
WeaveCommand, WeaveNode, WeaveScratch, ISLAND_HALF_CELLS, KIND_DECAY, KIND_DENSITY,
KIND_GRAVITY, KIND_HEAT, KIND_PHASE, KIND_VOLUME, KIND_WIND, MAX_WEAVE_COMMANDS,
};
use crate::templates::{builtin, writes_for, TEMPLATE_FREEZE};
use astraweave_nav::{NavChange, NavChangeKind};
Expand Down Expand Up @@ -230,25 +230,23 @@ fn store_writes(frame: &mut WeaveFrame, writes: &[FieldWrite]) -> u32 {
}

fn push_ice(frame: &mut WeaveFrame, tick: u64, seq: u32, origin: [i32; 3], radius: u8) {
debug_assert!(
origin
.iter()
.all(|cell| (-ISLAND_HALF_CELLS..=ISLAND_HALF_CELLS).contains(cell)),
"freeze origin is outside the island; queue_weave rejects it before writes are stored"
);
let radius = radius as i32;
let Some(min_milli) = milli_corner(
origin[0].checked_sub(radius),
Some(origin[1]),
origin[2].checked_sub(radius),
) else {
return;
};
let Some(max_milli) = milli_corner(
origin[0]
.checked_add(radius)
.and_then(|cell| cell.checked_add(1)),
origin[1].checked_add(1),
origin[2]
.checked_add(radius)
.and_then(|cell| cell.checked_add(1)),
) else {
return;
};
let min_milli = [
(origin[0] - radius) * CELL_MM,
origin[1] * CELL_MM,
(origin[2] - radius) * CELL_MM,
];
let max_milli = [
(origin[0] + radius + 1) * CELL_MM,
(origin[1] + 1) * CELL_MM,
(origin[2] + radius + 1) * CELL_MM,
];
let sheet_index = frame.sheet_count as usize;
if sheet_index < MAX_SINKS {
frame.sheets[sheet_index] = IceSheet {
Expand Down
23 changes: 22 additions & 1 deletion astraweave-weaving/src/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ pub fn meters_to_cell(m: f32) -> Option<i32> {
return None;
}
let milli = m * 1000.0;
if milli < i32::MIN as f32 || milli > i32::MAX as f32 {
// `i32::MAX as f32` is `2^31`. `>` lets that value through and `as i32`
// saturates. Every smaller finite `f32` is at most `2147483392` and fits.
if milli < i32::MIN as f32 || milli >= i32::MAX as f32 {
return None;
}
Some((milli as i32).div_euclid(CELL_MM))
Expand Down Expand Up @@ -253,6 +255,25 @@ mod tests {
use super::*;

#[test]
fn meters_to_cell_rejects_non_finite_and_the_i32_edge() {
let positive = (i32::MAX as f32) / 1000.0;
assert!(
meters_to_cell(positive).is_none(),
"nearest f32 to 2^31/1000 ({positive}) must not saturate"
);
let negative = (i32::MIN as f32) / 1000.0;
assert_eq!(
meters_to_cell(negative),
Some(-2_147_484),
"negative edge ({negative}) must stay negative and must not saturate"
);
assert!(meters_to_cell(f32::NAN).is_none());
assert!(meters_to_cell(f32::INFINITY).is_none());
assert!(meters_to_cell(f32::NEG_INFINITY).is_none());
assert_eq!(meters_to_cell(1.0), Some(1));
assert_eq!(meters_to_cell(-1.5), Some(-2));
}

fn gravity_conversion_matches_9810() {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
assert_eq!(gravity_mm_s2(WORLD_GRAVITY_MILLI_G), -9810);
assert_eq!(gravity_mm_s2(0), 0);
Expand Down
55 changes: 53 additions & 2 deletions astraweave-weaving/src/legacy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,17 @@ pub fn compile_legacy(kind: u8, points: LegacyPoints) -> CompiledOp {
compiled.write_count = count;
}
1 => {
if let (Some(bx), Some(bz)) = (bx, bz) {
if let (Some(bx), Some(by), Some(bz)) = (bx, by, bz) {
if cell_origin(bx, by, bz).is_none() {
return empty_compiled();
}
compiled.collapse = Some(DirectorCollapse {
ax: ax as i32,
ay: az as i32,
bx: bx as i32,
by: bz as i32,
});
}
let _ = by;
}
2 => {
let (mods, count) = writes_for(&builtin(TEMPLATE_WIND).unwrap(), origin, 1);
Expand Down Expand Up @@ -239,4 +241,53 @@ mod tests {
assert_eq!(min[0], (ISLAND_HALF_CELLS - 2) * crate::field::CELL_MM);
assert_eq!(min[1], 0);
}

#[test]
fn non_finite_and_i32_edge_origins_drop_the_op() {
for origin in [
f32::NAN,
f32::INFINITY,
f32::NEG_INFINITY,
(i32::MAX as f32) / 1000.0,
(i32::MIN as f32) / 1000.0,
] {
let compiled = compile_legacy(
5,
LegacyPoints {
a: [origin, 0.0, 0.0],
b: None,
tick: 1,
seq: 1,
},
);
assert_eq!(compiled.write_count, 0, "{origin}");
assert!(compiled.ice_min_milli.is_none(), "{origin}");
}
}

#[test]
fn far_collapse_endpoint_is_rejected() {
let compiled = compile_legacy(
1,
LegacyPoints {
a: [0.0, 0.0, 0.0],
b: Some([1.0e20, 0.0, 0.0]),
tick: 0,
seq: 0,
},
);
assert!(compiled.collapse.is_none());
assert_eq!(compiled.write_count, 0);
let kept = compile_legacy(
1,
LegacyPoints {
a: [0.0, 0.0, 0.0],
b: Some([10.0, 0.0, 10.0]),
tick: 0,
seq: 0,
},
);
let line = kept.collapse.unwrap();
assert_eq!((line.ax, line.ay, line.bx, line.by), (0, 0, 10, 10));
}
}
2 changes: 1 addition & 1 deletion astraweave-weaving/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub use field::{
};
pub use gameplay_qa::{load_bundled_scenario, run_scenario, FailureArtifact, RunOutcome};
pub use intents::{IntentProposer, WeaveIntent};
pub use legacy::{compile_legacy, LegacyPoints};
pub use legacy::{compile_legacy, CompiledOp, LegacyPoints};
pub use level::{Camera, LevelStats, Player, VeilweaverLevel};
pub use mod_queue::{
parse_template_toml, queue_weave, QueueError, WeaveCommand, WeaveScratch, WeaveTemplate,
Expand Down
8 changes: 5 additions & 3 deletions docs/architecture/gameplay.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ lifecycle_status: active
integration_status: mixed
summary: "Wired TYPES (QuestLog/Stats/Inventory->ui; BiomeRule/ResourceNode->terrain; Dialogue->audio), but combat (perform_attack_sweep), apply_weave_op & the Combat/Crafting/Quest plugins are example-only; water_movement.rs fully dormant. gameplay.md §1,§6"
owns: [astraweave-gameplay]
doc_version: "1.3"
doc_version: "1.4"
last_verified_commit: 1e306e13
---

Expand All @@ -21,7 +21,7 @@ last_verified_commit: 1e306e13
|---|---|
| **System name** | Gameplay System (combat, crafting, quests/dialogue, Veilweaver slice/tutorial, in-crate weaving glue, water-movement logic) |
| **Primary crates** | `astraweave-gameplay` (single crate) |
| **Document version** | 1.3 |
| **Document version** | 1.4 |
| **Last verified against commit** | `1e306e13` |
| **Last verified date** | 2026-10-15 |
| **Status** | Active (mixed wiring: a subset of types are consumed by other engine crates; the ECS combat/craft/quest plugins, `perform_attack_sweep`, `apply_weave_op`, and `water_movement` are wired only by examples/the slice-runtime crate, not by an in-engine runtime caller) |
Expand Down Expand Up @@ -304,7 +304,7 @@ WeaveTutorialState mutated (anchors stabilized, triggers active)
| 1 | `perform_attack_sweep` returns `None` for sweeps shorter than `1e-3` | Yes | Test `test_negligible_sweep_distance_returns_none` (`combat_physics.rs:591`) |
| 2 | A parry blocks damage exactly once: it is consumed (`window=0.0, active=false`) on the hit it blocks | Yes | Tests `test_parry_blocks_damage`, `test_parry_window_zero_does_not_parry`, `test_parry_inactive_does_not_parry` (`combat_physics.rs`) |
| 3 | Iframes block damage **without** being consumed | Yes | Test `test_iframes_block_damage` (`combat_physics.rs:393`) |
| 4 | `apply_weave_op` bails (no mutation) when the relevant budget field is `<= 0`, else decrements it by exactly 1 | Yes | Tests `*_no_budget`, `redirect_wind_budget_decrements`, `test_apply_weave_op_budget_depletion` (`weaving.rs`) |
| 4 | `apply_weave_op` bails (no mutation, no budget spend) when the relevant budget field is `<= 0`, and when `compile_legacy` drops the op because an origin is outside the island. A kept op decrements the matching budget by exactly 1 | Yes | Tests `*_no_budget`, `redirect_wind_budget_decrements`, `test_apply_weave_op_budget_depletion`, `dropped_origin_does_not_spend_budget_or_return_a_consequence`, `far_collapse_endpoint_does_not_spend_budget` (`weaving.rs`) |
| 5 | `FreezeWater` performs no truth mutation (consumes `weather_ops` only) | Partial | Doc-only (verified 2026-06-25). Enforced by the inline comment + budget decrement at `weaving.rs:94-105`; the `FreezeWater` arm provably contains no `w`/`phys` mutation. Confirmed there is **no** dedicated test asserting physics/world are unchanged — `mutation_tests.rs` has no `FreezeWater` truth-mutation test (only a budget-path test). |
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
| 6 | `WaterPlayerState::update` clamps `submersion` to `[0,1]` before mode selection | Yes | `water_movement.rs:207`; tests `update_threshold_boundaries_exact` and others |
| 7 | ECS `combat_system` uses Manhattan distance (`|dx|+|dy|`), not Euclidean | Yes | Tests `combat_distance_check_with_offset_positions`, `combat_system_distance_subtraction_matters` (`ecs.rs`) |
Expand Down Expand Up @@ -349,6 +349,8 @@ No benchmarks live in this crate's runtime path beyond `benches/combat_pipeline`

## 12. Maintenance Notes

**Revision 1.4 (2026-10-20):** `apply_weave_op` returns an error and does not spend budget when `compile_legacy` drops an origin. Invariant 4.

**Update this doc when:**
- Any Active file in §5 gains/loses a production caller (re-run the wired-vs-dormant grep — this is the doc's highest-value signal).
- A new `WeaveOpKind` variant is added (touch §3, §7, and the `apply_weave_op`/`WeaveConsequence` match arms).
Expand Down
4 changes: 2 additions & 2 deletions docs/architecture/weaving.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ This crate hosts **two distinct pipelines** that do not call each other. Both ar
| 10 | Enemy patrol targets and wave spawn positions are a function of `(world_seed, draw_index, SIM_SYSTEM_ENEMY_PATROL \| SIM_SYSTEM_SPAWNER)`. Offsets are rejection samples in the disk (`disk_xz`); no `thread_rng` and no `sin`/`cos`. Active spawn ids are sorted before round-robin. | Yes | `enemy.rs`, `spawner.rs`; tests `patrol_target_is_bit_identical_for_the_same_seed`, `spawn_positions_are_bit_identical_for_the_same_seed`. |
| 11 | `run_aravath_slice` is one resolve at `ARAVATH_SLICE_SEED`. The scripted and goal policies of `aravath_slice_sword` finish on the same SHA-256 trace. That digest is required case `gameplay_qa_aravath_slice`. | Yes | `gameplay_qa.rs` test `replay_aravath_slice_scenario`. `determinism-replay.yml` merges `replay-hash-gameplay-qa.json`. |
| 12 | `weave_tick` does not allocate. Modifiers are stamped in command order. One reaction per cell. Freeze emits one ice AABB and one `NavChange` with `NavChangeKind::Weave` on the command's start tick. | Yes | `eval.rs`, `tests/no_alloc.rs`, `astraweave-core/tests/replay_hash.rs` case `weaving`. |
| 13 | `queue_weave` rejects an origin outside ±`ISLAND_HALF_CELLS` (2048) on any axis. It does not saturate. `meters_to_cell` returns `None` before the float-to-int cast when the millimetre value does not fit in `i32`, and `compile_legacy` drops the op when the cell is outside that cube. Ice bounds use `checked_mul`. `parse_template_toml` rejects an id that does not fit `u16` before the cast (`template id {id} does not fit u16`). `0` and ids 1–7 are engine ids. In-range casts keep their bytes. | Yes | `mod_queue.rs` tests `origins_outside_the_island_are_rejected_without_saturation` and `parse_rejects_engine_ids_and_accepts_modifier_data`. `legacy.rs` test `far_origin_does_not_saturate_into_a_milli_aabb`. |
| 13 | `queue_weave` rejects an origin outside ±`ISLAND_HALF_CELLS` (2048) on any axis. It does not saturate. `meters_to_cell` returns `None` when the metre value is non-finite or `m * 1000 >= i32::MAX as f32` (and when it is below `i32::MIN as f32`) before the float-to-int cast. `compile_legacy` drops the op when `a` or collapse endpoint `b` is outside that cube. `push_ice` `debug_assert`s the island bound and then multiplies; it does not drop a sheet after writes are stored. `parse_template_toml` rejects an id that does not fit `u16` before the cast. `0` and ids 1–7 are engine ids. In-range casts keep their bytes. | Yes | `field.rs` `meters_to_cell_rejects_non_finite_and_the_i32_edge`. `legacy.rs` `far_origin_does_not_saturate_into_a_milli_aabb`, `non_finite_and_i32_edge_origins_drop_the_op`, `far_collapse_endpoint_is_rejected`. `mod_queue.rs` `origins_outside_the_island_are_rejected_without_saturation`. |

---

Expand Down Expand Up @@ -428,7 +428,7 @@ This is a pure-CPU logic crate; performance is benchmark-tracked but not a runti

| Version | Date | Notes |
|---|---|---|
| 1.9 | 2026-10-20 | `meters_to_cell` rejects a non-finite or out-of-`i32` metre value before the saturating cast. `compile_legacy` drops an origin outside ±2048 cells. Ice millimetres use checked multiply. In-range `weaving` bytes stay on the same path. |
| 1.9 | 2026-10-20 | `meters_to_cell` rejects a non-finite metre value, and any millimetre value at or above `i32::MAX as f32`, before the saturating cast. `compile_legacy` drops `a` or collapse `b` outside ±2048 cells. `push_ice` asserts the island bound instead of returning after writes are stored. `apply_weave_op` does not spend budget for a dropped op. In-range `weaving` bytes stay on the plain multiply. |
| 1.8 | 2026-10-16 | Restamp `fb1c8ec2`. Summary, status, and the §4 greybox row match the startup cache. `weaving` still hashes `NullField`. |
| 1.7 | 2026-10-16 | Restamp `1e275a9e`. Cargo consumers are the greybox, gameplay, scripting, security, the core replay test, `aravath_weave`, and the two older quest examples. |
| 1.6 | 2026-10-16 | Greybox caller. `Combat::tick` calls `run_aravath_slice` and the window shows `Cover broke` when `cover_intact` is false. |
Expand Down