From 4cdfa22fb02d60f03afbe67d6d1763ac4a8c700c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 04:41:13 +0200 Subject: [PATCH 1/3] Cut 8: EquippedItem.ConditionRatio -- how healthy a behaviour actually is Operator ask (2026-09-19): thruster particles only reflected thrust intent, so a cooked or starved thruster looked identical to a healthy one. EquippedItem.ConditionRatio (Entity.cs) resolves a stat's actual value against what the same item, same lot, same modifiers would produce with Heat/Durability/PowerSupply pinned to their identity (NominalContext) -- quality and lot are not part of "perfect", so a cheap item still reads 1 at full health. The nominal side bypasses the resolver's cache (which is keyed only by (owner, stat) and would otherwise collide with the real cached value) with one direct Evaluate call, a handful of flops. Thruster.Condition and AetherDrive.Condition expose that ratio against each behaviour's own governing stat (Thrust, Torque) for presentation to read next. Co-Authored-By: Claude Opus 5 --- .../ServerShared/Behaviors/AetherDrive.cs | 5 +++ .../ServerShared/Behaviors/Thruster.cs | 8 +++- Assets/Scripts/ServerShared/Entity.cs | 40 +++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs b/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs index 5baf95eb8..72da7b29c 100644 --- a/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs +++ b/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs @@ -73,6 +73,11 @@ public class AetherDrive : Behavior, IPowerConsumer public AetherDriveData DriveData => _data; + // Cut 8 (operator ask 2026-09-19): the equivalent quantity to Thruster.Condition -- Torque is the stat that + // actually governs this behaviour's rotor spin-up (PowerRequest/Execute above both read it), so it is what + // "broken" means for a drive. 1f for the item-less ConsumableItemEffect case, same reasoning as Thruster. + public float Condition => Item?.ConditionRatio(_data.Torque) ?? 1f; + public float3 Axis { get => _axis; diff --git a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs index 7236ed5de..f88315ed3 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs @@ -49,9 +49,15 @@ public class Thruster : Behavior, IAnalogBehavior, IPowerConsumer } private ThrusterData _data; - + private float _input; + // Cut 8 (operator ask 2026-09-19): presentation's read of "how healthy does this thruster actually look" -- + // Thrust is the stat that governs this behaviour's real output, so it is the equivalent quantity to condition + // against. 1f for the ConsumableItemEffect constructor's item-less case; that path has no durability, heat or + // power-supply state to be broken by, so it always reads perfect. + public float Condition => Item?.ConditionRatio(_data.Thrust) ?? 1f; + public Thruster(ThrusterData data, EquippedItem item) : base(data, item) { _data = data; diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 8a051bc67..0d53c1020 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1390,6 +1390,46 @@ public class EquippedItem : IStatContext public float ScaleModifier(PerformanceStat stat) => Entity.Resolver.ScaleModifier(this, stat); public float ConstantModifier(PerformanceStat stat) => Entity.Resolver.ConstantModifier(this, stat); + // Cut 8 (operator ask 2026-09-19): "multiply [emission] by actual performance so a broken thruster emits a + // puny flame." One ratio per (item, stat): this item's actually-resolved value against what the same item, + // same lot, same quality, same modifier stack would produce with every degradable term at its identity -- + // full durability, optimal temperature, full power supply. Quality and lot are deliberately NOT part of + // "perfect": NominalContext forwards Lot/ScaleModifier/ConstantModifier unchanged and only pins Heat, + // Durability, PowerSupply and ConsumableProgress to 1, so a cheap item's honestly-lower ceiling still reads + // 1 at full health -- it is not reported as damaged for being cheap. + // + // Cost: Evaluate(stat) is the same resolver-cached read every other caller already pays for (ยง above), so it + // is a dictionary hit here unless something already invalidated it this tick. The nominal side cannot reuse + // that cache -- the resolver's cache key is (owner, stat) alone, and owner is `this`, so resolving a second, + // different context under the same key would clobber the real cached value -- so it calls stat.Evaluate + // directly against NominalContext, bypassing the cache entirely. That is one pass over the stat's own Terms + // list (Thrust/Torque declare at most three: Quality, Heat or Durability, PowerSupply), each a pow() and a + // multiply, i.e. a handful of flops with no allocation (NominalContext is a readonly struct). Cheap enough to + // call once per thruster per frame, which is all presentation (ShipInstance.Update) does with it. + // No epsilon guard on a zero/near-zero nominal: math.min/max (CultMath's own DXIL-lowering semantics, + // math.cs) resolve a NaN operand to the OTHER operand, not to NaN, so saturate(0f/0f) -- the one way nominal + // degenerates to exactly 0 (a stat authored with Max <= 0 and no ScaleModifier/ConstantModifier moving it off + // that) -- is a real, tested 0f (ConditionIsZeroNotNaNWhenTheNominalValueItselfDegeneratesToZero), not NaN. A + // manual guard here would duplicate that behaviour rather than add any. + public float ConditionRatio(PerformanceStat stat) => saturate(Evaluate(stat) / stat.Evaluate(new NominalContext(this))); + + // Perfect-conditions view of this same item for ConditionRatio above. Everything but the three degradable + // factors is forwarded to the real item so a modifier stack or a cheap lot's lower Quality term still shapes + // "perfect" the same way it shapes "actual" -- only Heat/Durability/PowerSupply/ConsumableProgress are + // pinned to their identity (1), since those are exactly the terms condition is supposed to measure. + private readonly struct NominalContext : IStatContext + { + private readonly EquippedItem _item; + public NominalContext(EquippedItem item) => _item = item; + public Lot Lot => _item.Lot; + public float HeatFactor(float exponent) => 1f; + public float DurabilityFactor(float exponent) => 1f; + public float ConsumableProgressFactor(float exponent) => 1f; + public float PowerSupplyFactor(float exponent) => 1f; + public float ScaleModifier(PerformanceStat stat) => _item.ScaleModifier(stat); + public float ConstantModifier(PerformanceStat stat) => _item.ConstantModifier(stat); + } + public void AddHeat(float heat, bool ignoreThermalMass = false) { foreach(var hullCoord in InsetShape.Coordinates) From ff7f8a5c2a611fc19020c1e2e7e3b0d8d294e5f2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 04:41:23 +0200 Subject: [PATCH 2/3] Cut 8: presentation reads Condition instead of recomputing durability ShipInstance's thruster and aether-drive emission were the operator's actual complaint (2026-09-19): thrust intent times a raw durability ratio that ignored heat and power and duplicated simulation arithmetic in presentation. Both now multiply intent by Thruster.Condition / AetherDrive.Condition -- no durability/heat/power math left in presentation. Unity-side; not covered by the shared test suite. Small and obvious for Self's batchmode run on merge to check. Co-Authored-By: Claude Opus 5 --- Assets/Scripts/Gameplay/ShipInstance.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Assets/Scripts/Gameplay/ShipInstance.cs b/Assets/Scripts/Gameplay/ShipInstance.cs index 7999d27cb..8a0b22b6e 100644 --- a/Assets/Scripts/Gameplay/ShipInstance.cs +++ b/Assets/Scripts/Gameplay/ShipInstance.cs @@ -123,16 +123,20 @@ public class ShipInstance : EntityInstance forceOverLifetime.xMultiplier = _aetherDrive.Drive.ThrustDirection.x * _aetherDrive.BaseForce; forceOverLifetime.zMultiplier = _aetherDrive.Drive.ThrustDirection.y * _aetherDrive.BaseForce; var emissionModule = _aetherDrive.Particles.emission; - emissionModule.rateOverTimeMultiplier = _aetherDrive.BaseEmission * thrust; + // Cut 8 (operator ask 2026-09-19): intent (thrust) times condition -- presentation reads the + // simulation's own ratio rather than recomputing any part of it. AetherDrive.Condition is the + // equivalent of Thruster.Condition below (Torque in place of Thrust). + emissionModule.rateOverTimeMultiplier = _aetherDrive.BaseEmission * thrust * _aetherDrive.Drive.Condition; } - + foreach (var thrusterInstance in _thrusters) { var emissionModule = thrusterInstance.System.emission; - var item = thrusterInstance.Thruster.Item.EquippableItem; - var data = Entity.ItemManager.GetData(item); thrusterInstance.MaxParticleCount = thrusterInstance.System.particleCount; - emissionModule.rateOverTimeMultiplier = thrusterInstance.BaseEmission * thrusterInstance.Thruster.Axis * (item.Durability / data.Durability); + // Cut 8 (operator ask 2026-09-19): intent (Axis) times condition (Thruster.Condition, the item's + // resolved Thrust against its own perfect-conditions Thrust) -- no durability/heat/power arithmetic + // recomputed here, only the same emission math that already existed. + emissionModule.rateOverTimeMultiplier = thrusterInstance.BaseEmission * thrusterInstance.Thruster.Axis * thrusterInstance.Thruster.Condition; } transform.rotation = Ship.Rotation.ToUnity(); From 57c053d15f36634c63b0d8d06eaadab6c094691f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 04:41:43 +0200 Subject: [PATCH 3/3] Cut 8: pin ConditionRatio -- perfect/dead/durability/heat/power/force-unchanged ConditionRatioTests.cs (8 Facts): a perfect item reads 1; the ratio falls with durability, temperature-off-plateau, and a partial power grant, each in isolation; it is 0 when the item produces nothing (both the ordinary durability=0 case and the degenerate Max=0 nominal, which relies on CultMath's NaN-favoring min/max rather than a manual guard); thrust force for a given input is bit-identical to BrownoutTests' own pinned values, proving Execute()'s physics is untouched by Condition being read every tick. mutation_tests_condition_ratio_cut8.py: one mutation per rule, mirroring cut7's harness; all 7 confirmed red (2 control/guard mutations revised after the first pass showed them un-killable -- see the harness's own comments). Co-Authored-By: Claude Opus 5 --- .../ConditionRatioTests.cs | 266 ++++++++++++++++++ tests/mutation_tests_condition_ratio_cut8.py | 194 +++++++++++++ 2 files changed, 460 insertions(+) create mode 100644 tests/Aetheria.Shared.Tests/ConditionRatioTests.cs create mode 100644 tests/mutation_tests_condition_ratio_cut8.py diff --git a/tests/Aetheria.Shared.Tests/ConditionRatioTests.cs b/tests/Aetheria.Shared.Tests/ConditionRatioTests.cs new file mode 100644 index 000000000..2ff03d18f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ConditionRatioTests.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; + +// Operator ask (2026-09-19, docs/... none yet -- this is Cut 8 on top of Cut 7's brownout work): "you can't +// currently tell when [a thruster is] busted -- the particle system it spawns responds only to thrust intent. +// Should multiply that by actual performance." EquippedItem.ConditionRatio (Entity.cs) is the one number that +// answers "how healthy does this item actually look": the item's resolved value for a stat against what the +// same item, same lot, same modifiers would produce with Heat/Durability/PowerSupply pinned to their identity. +// Thruster.Condition and AetherDrive.Condition (Thruster.cs/AetherDrive.cs) are that ratio read against each +// behaviour's own governing stat (Thrust, Torque); ShipInstance.cs (Unity-side, not covered here) multiplies +// presentation intent by it instead of recomputing any durability/heat/power arithmetic of its own. +// Each rule here has a matching mutation in tests/mutation_tests_condition_ratio_cut8.py. +public sealed class ConditionRatioTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-conditionratio-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public ConditionRatioTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private static GameplaySettings Settings() => new GameplaySettings + { + DefaultEntitySettings = new EntitySettings(), + Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } }, + QualityPriceModifier = new ExponentialLerp() + }; + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + // Optimal temperature 280, plateau 400 wide (matches BrownoutTests' own consumer shape): the ambient + // temperature this fixture starts at (280, set explicitly per test rather than relied on as a default) sits + // dead center of the plateau, so ThermalPerformance reads exactly 1 there. + private const float OptimalTemperature = 280f; + + private static EquippableItem Mint(CultCache cache, ItemManager items, ItemData design) => new EquippableItem + { + Data = cache.RefOf(design), + Durability = design is EquippableItemData equippable ? equippable.Durability : 0, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf(design), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + + private static string NewRoot() + { + var root = Path.Combine(Path.GetTempPath(), "aetheria-conditionratio-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + return root; + } + + // Hull, a Reactor (BrownoutTests' own shape: no capacitor, so a tick's grant ratio is a clean + // min(1, generation/demand)), and one Consumer carrying the given ThrusterData. Defaults to this instance's + // own catalog path; a test that needs two independent ships (the power-grant comparison below) passes a + // second, freshly rooted path rather than reopening the same file twice in one process. + private CultCache OpenCatalog(ThrusterData thruster, string catalogPath = null) + { + var cache = AetheriaStores.Open(catalogPath ?? Catalog, catalogWritable: true); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + var hullShape = new Shape(5, 5); + foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true; + cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10, Mass = 1000 }); + cache.Upsert(new GearData + { + Name = "Reactor", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10, + MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = OptimalTemperature, PlateauWidth = 400, + Behaviors = { new ReactorData + { + Charge = Constant(0), Efficiency = Constant(1), OverloadEfficiency = Constant(1), ThrottlingFactor = Constant(2) + } } + }); + cache.Upsert(new GearData + { + Name = "Consumer", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10, + MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = OptimalTemperature, PlateauWidth = 400, + Behaviors = { thruster } + }); + cache.FlushAsync().Wait(); + return cache; + } + + private Ship BuildShip(CultCache cache, float reactorCharge, out EquippedItem consumer) + { + var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var hull = Mint(cache, items, cache.GetByName("Skiff")); + var ship = new Ship(items, zone, hull, new EntitySettings()); + + var reactorData = cache.GetByName("Reactor"); + ((ReactorData) reactorData.Behaviors[0]).Charge = Constant(reactorCharge); + Assert.True(ship.TryEquip(Mint(cache, items, reactorData))); + Assert.True(ship.TryEquip(Mint(cache, items, cache.GetByName("Consumer")))); + + zone.Entities.Add(ship); + ship.LookDirection = float3(0, 0, 1); // Ship.Update's own steering pass stays a no-op, as BrownoutTests + ship.Activate(); + consumer = ship.Equipment.Single(e => e.Data.Name == "Consumer"); + + // Settle at the plateau's center: two ticks so UpdatePerformance's deltaTemp term reads 0 before a test + // drives its own change, matching HeatResponseTests' own settle pattern. + foreach (var cell in consumer.InsetShape.Coordinates) ship.Temperature[cell.x, cell.y] = OptimalTemperature; + consumer.UpdatePerformance(); + consumer.UpdatePerformance(); + return ship; + } + + // --- 1: a perfect item -- full durability, a grant far exceeding demand -- reads exactly 1, on a stat that + // --- declares Durability and PowerSupply together (both at their identity). The Heat term's own identity + // --- case is pinned by ConditionFallsWithTemperatureAwayFromThePlateauAlone's "atPlateau" reading below; + // --- combining it here too would make this test depend on UpdateTemperature's own ambient drift over the + // --- Update tick PowerSupply needs, which is a real dependency this test has no reason to take on. --- + [Fact] + public void APerfectItemsConditionIsOne() + { + var thrust = new PerformanceStat + { + Min = 0, Max = 100, + Terms = + { + new StatTerm { Source = StatSource.Durability, Exponent = 1 }, + new StatTerm { Source = StatSource.PowerSupply, Exponent = 1 } + } + }; + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var ship = BuildShip(cache, reactorCharge: 1000, out var consumer); + ship.Update(1f); + + Assert.Equal(1f, ship.GetBehavior().Condition, 4); + } + + // --- 2: durability alone. Full temperature/power, half durability, a stat with only a Durability term. --- + [Fact] + public void ConditionFallsWithDurabilityAlone() + { + var thrust = new PerformanceStat { Min = 0, Max = 100, Terms = { new StatTerm { Source = StatSource.Durability, Exponent = 1 } } }; + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var ship = BuildShip(cache, reactorCharge: 1000, out var consumer); + + consumer.EquippableItem.Durability = consumer.Data.Durability; // full + consumer.UpdatePerformance(); // direct call, not ship.Update -- no reason to also churn UpdateTemperature + var full = ship.GetBehavior().Condition; + + consumer.EquippableItem.Durability = consumer.Data.Durability * .5f; // half + consumer.UpdatePerformance(); + var half = ship.GetBehavior().Condition; + + Assert.Equal(1f, full, 4); + Assert.True(half > 0f && half < full, $"half={half} should sit strictly between 0 and full={full}"); + } + + // --- 3: temperature alone, away from the plateau. Full durability/power, a stat with only a Heat term. --- + [Fact] + public void ConditionFallsWithTemperatureAwayFromThePlateauAlone() + { + var thrust = new PerformanceStat { Min = 0, Max = 100, Terms = { new StatTerm { Source = StatSource.Heat, Exponent = 1 } } }; + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var ship = BuildShip(cache, reactorCharge: 1000, out var consumer); + var atPlateau = ship.GetBehavior().Condition; // BuildShip already settled at OptimalTemperature + + // Push the item's own temperature far outside the plateau (center 280, half-width 200 -> outside past + // 480), then read performance directly (not through ship.Update, whose UpdateTemperature would pull the + // value we just set back toward ambient equilibrium within the same tick, before UpdatePerformance ever + // sees it -- exactly HeatResponseTests' own SetTemperature-then-UpdatePerformance pattern). + foreach (var cell in consumer.InsetShape.Coordinates) ship.Temperature[cell.x, cell.y] = 900f; + consumer.UpdatePerformance(); + var offPlateau = ship.GetBehavior().Condition; + + Assert.Equal(1f, atPlateau, 4); + Assert.True(offPlateau > 0f && offPlateau < atPlateau, $"offPlateau={offPlateau} should sit strictly between 0 and atPlateau={atPlateau}"); + } + + // --- 4: power alone. Full durability/temperature, a partial grant, a stat with only a PowerSupply term + // --- (mirrors BrownoutTests' own Curved fixture). --- + [Fact] + public void ConditionFallsWithAPartialPowerGrantAlone() + { + var thrust = new PerformanceStat { Min = 0, Max = 100, Terms = { new StatTerm { Source = StatSource.PowerSupply, Exponent = 1 } } }; + + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var fullShip = BuildShip(cache, reactorCharge: 1000, out _); // demand 100, generation far exceeds it -> ratio 1 + fullShip.MovementDirection = float2(0, -1); // real thrust demand -- PowerRequest is 0 with no input at all + fullShip.Update(1f); + var full = fullShip.GetBehavior().Condition; + + var secondRoot = NewRoot(); + try + { + using var cache2 = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }, catalogPath: Path.Combine(secondRoot, "Aetheria.cc")); + var halfShip = BuildShip(cache2, reactorCharge: 50, out _); // demand 100, generation 50 -> ratio .5 + halfShip.MovementDirection = float2(0, -1); + halfShip.Update(1f); + var half = halfShip.GetBehavior().Condition; + + Assert.Equal(1f, full, 4); + Assert.True(half > 0f && half < full, $"half={half} should sit strictly between 0 and full={full}"); + } + finally { Directory.Delete(secondRoot, true); } + } + + // --- 5: dead ends at 0, not some small positive residue -- a fully destroyed item on a stat with Min=0 + // --- produces nothing, so the ratio itself is 0/0-guarded down to 0 rather than a divide-by-zero or NaN. --- + [Fact] + public void ConditionIsZeroWhenTheItemProducesNothing() + { + var thrust = new PerformanceStat { Min = 0, Max = 100, Terms = { new StatTerm { Source = StatSource.Durability, Exponent = 1 } } }; + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var ship = BuildShip(cache, reactorCharge: 1000, out var consumer); + + consumer.EquippableItem.Durability = 0f; + ship.Update(1f); + + Assert.Equal(0f, ship.GetBehavior().Condition, 4); + } + + // --- 5b: the guard's real reason to exist -- a stat authored with Max=0 (no terms at all) makes the nominal + // --- side degenerate to exactly 0 too, so actual/nominal is 0/0. Without the guard that is NaN, which is not + // --- equal to 0f (the ConditionIsZeroWhenTheItemProducesNothing case above never hits this: its nominal + // --- stays 100 -- only the numerator goes to 0 there). --- + [Fact] + public void ConditionIsZeroNotNaNWhenTheNominalValueItselfDegeneratesToZero() + { + var thrust = Constant(0); // Min == Max == 0, no Terms -- both actual and nominal evaluate to exactly 0 + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var ship = BuildShip(cache, reactorCharge: 1000, out _); + ship.Update(1f); + + Assert.Equal(0f, ship.GetBehavior().Condition, 4); + } + + // --- 6: presentation reading Condition must not have moved what the thruster actually does. Exact numbers + // --- from BrownoutTests.ThrusterAtFullGrantIsUnchangedFromToday and ...DegradesByItsAuthoredExponentNotLinearly, + // --- reproduced here against a ship that also reads Condition every tick, to prove Execute()'s own force + // --- math is untouched by this cut. --- + [Fact] + public void ThrustForceForAGivenInputIsUnchangedByThisCut() + { + var thrust = new PerformanceStat { Min = 0, Max = 100, Terms = { new StatTerm { Source = StatSource.PowerSupply, Exponent = 1 } } }; + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var ship = BuildShip(cache, reactorCharge: 1000, out _); // demand 100, generation far exceeds it -> ratio 1 + ship.MovementDirection = float2(0, -1); // reverse-thruster axis += -MovementDirection.y == 1 + ship.Update(1f); + + // Reading Condition after Update (as presentation would every frame) must not perturb the result. + _ = ship.GetBehavior().Condition; + + Assert.Equal(.1f, -ship.Velocity.y, 3); // 100 thrust / 1000 mass * dt 1, exactly as BrownoutTests pins it + } + + [Fact] + public void ThrustForceDegradesByItsAuthoredExponentUnchangedByThisCut() + { + var thrust = new PerformanceStat { Min = 0, Max = 100, Terms = { new StatTerm { Source = StatSource.PowerSupply, Exponent = 2 } } }; + using var cache = OpenCatalog(new ThrusterData { Thrust = thrust, Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) }); + var ship = BuildShip(cache, reactorCharge: 50, out _); // demand 100, generation 50 -> ratio .5 + ship.MovementDirection = float2(0, -1); + ship.Update(1f); + + _ = ship.GetBehavior().Condition; + + // Thrust = lerp(0, 100, pow(.5, 2)) = 25; velocity delta = 25 / 1000 mass * dt 1 = .025. + Assert.Equal(.025f, -ship.Velocity.y, 3); + } +} diff --git a/tests/mutation_tests_condition_ratio_cut8.py b/tests/mutation_tests_condition_ratio_cut8.py new file mode 100644 index 000000000..ba67066e9 --- /dev/null +++ b/tests/mutation_tests_condition_ratio_cut8.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Mutation tests for Cut 8, the operator's condition-ratio ask (2026-09-19): "you can't currently tell when +[a thruster is] busted -- the particle system it spawns responds only to thrust intent. Should multiply that by +actual performance." This follows Cut 7's brownout work (mutation_tests_stats_power_cut7.py) in this repo's own +numbering. + +EquippedItem.ConditionRatio (Entity.cs) is the one number that answers "how healthy does this item actually +look": the item's resolved value for a stat against what the same item, same lot, same modifier stack would +produce with Heat/Durability/PowerSupply pinned to their identity (NominalContext, the private struct right +below it). Thruster.Condition and AetherDrive.Condition (Thruster.cs/AetherDrive.cs) are that ratio read against +each behaviour's own governing stat. This script mutates each rule's own changed line and asserts the matching +ConditionRatioTests.cs Fact goes red for exactly that reason. A no-op control mutation proves the +read/replace/restore path is transparent. + +Usage: + python tests/mutation_tests_condition_ratio_cut8.py --cultlib-root + +Only touches files under this repository; every mutation is reversed before the script exits, including on +failure. +""" +from __future__ import annotations + +import argparse +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +TEST_PROJECT = REPO_ROOT / "tests" / "Aetheria.Shared.Tests" + + +@dataclass +class Mutation: + rule: str + file: str + anchor: str + mutated: str + test: str + expect: str # "red" (mutant must be killed) or "green" (the no-op control) + + +MUTATIONS: list[Mutation] = [ + # --- No-op control: proves the anchor/replace/restore mechanism is transparent --- + Mutation( + rule="control (no-op round trip)", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" public float ConditionRatio(PerformanceStat stat) => saturate(Evaluate(stat) / stat.Evaluate(new NominalContext(this)));", + mutated=" public float ConditionRatio(PerformanceStat stat) => saturate(Evaluate(stat) / stat.Evaluate(new NominalContext(this)));", + test="ConditionRatioTests.APerfectItemsConditionIsOne", + expect="green", + ), + + # --- The ratio must divide actual by nominal, not the reverse. A stat pinned to the identity on the nominal + # --- side but degraded (half durability) on the actual side proves direction: dividend and divisor swapped + # --- turns "half sits strictly below full" into "both saturate to 1" (nominal/actual > 1 either way, and + # --- saturate clamps it there), which is exactly as wrong as it sounds and just as easy to write by accident. + Mutation( + rule="ConditionRatio must divide actual by nominal, not the reverse", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" public float ConditionRatio(PerformanceStat stat) => saturate(Evaluate(stat) / stat.Evaluate(new NominalContext(this)));", + mutated=" public float ConditionRatio(PerformanceStat stat) => saturate(stat.Evaluate(new NominalContext(this)) / Evaluate(stat));", + test="ConditionRatioTests.ConditionFallsWithDurabilityAlone", + expect="red", + ), + + # --- Durability must actually be one of the terms NominalContext pins to identity -- if it is left to read + # --- the item's own live DurabilityFactor instead, a half-durability item's nominal denominator shrinks right + # --- along with its numerator and the ratio never leaves 1. --- + Mutation( + rule="NominalContext must pin DurabilityFactor to 1, not forward the item's live durability", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" public float DurabilityFactor(float exponent) => 1f;", + mutated=" public float DurabilityFactor(float exponent) => _item.DurabilityFactor(exponent);", + test="ConditionRatioTests.ConditionFallsWithDurabilityAlone", + expect="red", + ), + + # --- Same shape of bug, on Heat: if NominalContext forwards the item's live thermal performance instead of + # --- pinning it to 1, an off-plateau item's own nominal denominator degrades with it and the ratio never + # --- moves off 1. --- + Mutation( + rule="NominalContext must pin HeatFactor to 1, not forward the item's live thermal performance", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" public float HeatFactor(float exponent) => 1f;", + mutated=" public float HeatFactor(float exponent) => _item.HeatFactor(exponent);", + test="ConditionRatioTests.ConditionFallsWithTemperatureAwayFromThePlateauAlone", + expect="red", + ), + + # --- Same shape again, on PowerSupply -- the exact term Cut 7's brownout curve depends on. --- + Mutation( + rule="NominalContext must pin PowerSupplyFactor to 1, not forward the item's live grant", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" public float PowerSupplyFactor(float exponent) => 1f;", + mutated=" public float PowerSupplyFactor(float exponent) => _item.PowerSupplyFactor(exponent);", + test="ConditionRatioTests.ConditionFallsWithAPartialPowerGrantAlone", + expect="red", + ), + + # --- Zero must land exactly on zero, not divide-by-zero into NaN, when the nominal denominator itself + # --- degenerates (a Max=0 stat: both actual and nominal evaluate to exactly 0). ConditionRatio relies on + # --- CultMath's own NaN-favoring math.min/max (0/0 saturates to a real 0f, not NaN) rather than a manual + # --- epsilon guard -- dropping the saturate() call removes that protection and 0/0 surfaces as raw NaN, which + # --- is not equal to 0f. ConditionIsZeroWhenTheItemProducesNothing cannot catch this by itself, since its + # --- nominal stays 100 and only the numerator goes to 0 there. --- + Mutation( + rule="ConditionRatio must saturate the division, not return the raw quotient", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" public float ConditionRatio(PerformanceStat stat) => saturate(Evaluate(stat) / stat.Evaluate(new NominalContext(this)));", + mutated=" public float ConditionRatio(PerformanceStat stat) => Evaluate(stat) / stat.Evaluate(new NominalContext(this));", + test="ConditionRatioTests.ConditionIsZeroNotNaNWhenTheNominalValueItselfDegeneratesToZero", + expect="red", + ), + + # --- Thruster.Condition must read Thrust, the stat that actually governs this behaviour's force -- reading + # --- some other stat (here, the item's Visibility) would silently condition against the wrong quantity. --- + Mutation( + rule="Thruster.Condition must condition against the Thrust stat, not an unrelated one", + file="Assets/Scripts/ServerShared/Behaviors/Thruster.cs", + anchor=" public float Condition => Item?.ConditionRatio(_data.Thrust) ?? 1f;", + mutated=" public float Condition => Item?.ConditionRatio(_data.Visibility) ?? 1f;", + test="ConditionRatioTests.ConditionFallsWithDurabilityAlone", + expect="red", + ), +] + + +def replace_unique(path: Path, anchor: str, mutated: str) -> None: + original = path.read_text(encoding="utf-8") + count = original.count(anchor) + if count != 1: + raise SystemExit(f"{path}: anchor must occur exactly once, found {count}\n---\n{anchor}") + path.write_text(original.replace(anchor, mutated), encoding="utf-8") + + +def run_test(cultlib_root: str, test: str) -> tuple[int, str]: + proc = subprocess.run( + ["dotnet", "test", str(TEST_PROJECT), f"-p:CultLibRoot={cultlib_root}", + "--filter", f"FullyQualifiedName~{test}"], + capture_output=True, text=True, timeout=300, + ) + return proc.returncode, proc.stdout + proc.stderr + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--cultlib-root", required=True) + args = parser.parse_args() + + failures: list[str] = [] + originals: dict[str, str] = {} + for m in MUTATIONS: + if m.file not in originals: + originals[m.file] = (REPO_ROOT / m.file).read_text(encoding="utf-8") + + def restore_all() -> None: + for file, text in originals.items(): + (REPO_ROOT / file).write_text(text, encoding="utf-8") + + try: + for m in MUTATIONS: + print(f"\n=== {m.rule} (expect {m.expect}) ===") + path = REPO_ROOT / m.file + replace_unique(path, m.anchor, m.mutated) + code, output = run_test(args.cultlib_root, m.test) + passed = "Passed!" in output and code == 0 + if m.expect == "green": + if not passed: + failures.append(f"{m.rule}: expected green (test passing), got failure\n{output[-2000:]}") + else: + print(f"OK: {m.test} passed under a no-op mutation, as expected") + else: + if passed: + failures.append(f"{m.rule}: expected red (mutant killed), but {m.test} still passed") + else: + print(f"OK: {m.test} went red under the mutation, as expected") + # Restore this file immediately so the next mutation starts from a clean tree. + path.write_text(originals[m.file], encoding="utf-8") + finally: + restore_all() + + if failures: + print("\n=== FAILURES ===") + for f in failures: + print(f"- {f}") + return 1 + + print("\nAll mutations behaved as declared.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())