From fd7ef71c152019b60af39a4775e02ea066a34868 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 19:33:09 +0200 Subject: [PATCH 1/4] Cut 7.1/7.4: the reveal re-check pin and the live-catalog test FireControlCut7Tests.cs adds the fifth mutation Soul found survived 197 green tests -- FireControl.Fire freezing source.TargetItem.Value instead of the reveal-re-checked ResolvedTargetItem (7.1) -- and the campaign's first assertion that the shipped GameData/Aetheria.cc catalog is actually readable by the shipped code and can generate an armed LonginusX loadout (7.3/7.4). The live-catalog test builds its own scoped CultDocumentRegistry rather than AetheriaStores.Open's default shared one, because the shared registry auto-discovers every [CultDocument] type loaded anywhere in the test process -- including AetheriaStoresTests.cs's own TestCatalogGlobal, a fixture type the real catalog has never heard of and was never meant to satisfy. Co-Authored-By: Claude Sonnet 5 --- .../FireControlCut7Tests.cs | 290 ++++++++++++++++++ 1 file changed, 290 insertions(+) create mode 100644 tests/Aetheria.Shared.Tests/FireControlCut7Tests.cs diff --git a/tests/Aetheria.Shared.Tests/FireControlCut7Tests.cs b/tests/Aetheria.Shared.Tests/FireControlCut7Tests.cs new file mode 100644 index 000000000..d905bb77c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FireControlCut7Tests.cs @@ -0,0 +1,290 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using CultMath; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using Xunit; +using static CultMath.math; +using float3 = CultMath.float3; +using int2 = CultMath.int2; +using Random = CultMath.Random; + +// Cut 7 (docs/fire-control-cut.md): 7.1, the fifth mutation Soul found survived 197 green tests -- +// FireControl.Fire freezing the raw TargetItem.Value instead of the reveal-re-checked ResolvedTargetItem. +// Builds its own shooter/target fixture, the same shape FireAuthorityTests uses for Cut 3, rather than +// reusing that file's private Build helper (the established convention in this campaign's test files). +public sealed class FireControlCut7Tests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrolcut7-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public FireControlCut7Tests() => Directory.CreateDirectory(_root); + + private readonly List _openCaches = new List(); + + public void Dispose() + { + foreach (var c in _openCaches) c.Dispose(); + Directory.Delete(_root, true); + } + + // Detection well below the armor tier, which is well below the gear tier, so an aimed interior item can + // decay out of its own reveal while the weapon itself (index 0, the armor tier) and general detection + // both stay satisfied -- the shot still fires, only the aim point should be lost. + private static GameplaySettings TestSettings() => new GameplaySettings + { + DefaultEntitySettings = new EntitySettings(), + Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } }, + QualityPriceModifier = new ExponentialLerp(), + TargetDetectionInfoThreshold = .1f, + TargetArmorInfoThreshold = .3f, + TargetGearInfoThreshold = .9f, + FiringArc = 170, + CommitHorizon = .5f, + SchematicCellSize = 1f, + UnaidedAccuracy = .05f, + AgentMinHitProbability = 0f + }; + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + private sealed class Engagement + { + public ItemManager Items; + public Zone Zone; + public Ship Shooter; + public Ship Target; + public EquippedItem WeaponItem; + public InstantWeapon Weapon; + } + + // A trimmed copy of FireAuthorityTests.Build: one Sensors-hardpoint weapon plus a Tool-slot targeting + // system on the shooter, a target ship with a matching weapon (index 0 in IsRevealed's ranking) and, + // through beforeActivate, a second Tool item to aim at (index 1 -- the gear tier). + private Engagement Build(GameplaySettings settings, Action beforeActivate) + { + var hullShape = new Shape(5, 5); + foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true; + var hullData = new HullData + { + Name = "Hull", HullType = HullType.Ship, Shape = hullShape, Durability = 1000, Mass = 1000, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } } + }; + + var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true); + _openCaches.Add(cache); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(hullData); + cache.Upsert(new GearData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new InstantWeaponData + { + Damage = Constant(50), Range = Constant(1000), MinRange = Constant(0), + Velocity = Constant(0), Spread = Constant(0), DamageSpread = Constant(0), + Penetration = Constant(0), Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1000), + DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } } + } } + }); + cache.Upsert(new GearData + { + Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new TargetingSystemData + { + Accuracy = Constant(1), Resolution = Constant(1), Precision = Constant(1), Tracking = Constant(1000) + } } + }); + cache.FlushAsync().Wait(); + + var ledger = new ProvenanceLedger(); + for (var i = 1; i <= 10; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 }; + var items = new ItemManager(cache, ledger, settings, _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test", Owner = null }, null); + + var hullRef = items.ItemData.RefOf(items.ItemData.GetByName("Hull")); + var shooterHull = new EquippableItem { Data = hullRef, Durability = 1000, Lot = 1 }; + var shooter = new Ship(items, zone, shooterHull, new EntitySettings()); + + var gunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var gun = new EquippableItem { Data = gunRef, Durability = 1, Lot = 2 }; + Assert.True(shooter.TryEquip(gun, new int2(0, 0))); + var weaponItem = shooter.Equipment.Single(x => x.EquippableItem == gun); + var weapon = (InstantWeapon) weaponItem.Behaviors.Single(b => b is Weapon); + + var targetingRef = items.ItemData.RefOf(items.ItemData.GetByName("Targeting")); + var targeting = new EquippableItem { Data = targetingRef, Durability = 1, Lot = 3 }; + Assert.True(shooter.TryFindSpace(targeting, out var tpos)); + Assert.True(shooter.TryEquip(targeting, tpos)); + + var targetHull = new EquippableItem { Data = hullRef, Durability = 1000, Lot = 4 }; + var target = new Ship(items, zone, targetHull, new EntitySettings()); + var targetGunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var targetGun = new EquippableItem { Data = targetGunRef, Durability = 1, Lot = 5 }; + Assert.True(target.TryEquip(targetGun, new int2(0, 0))); + + beforeActivate?.Invoke(items, shooter, target); + + zone.Entities.Add(shooter); + zone.Entities.Add(target); + shooter.Activate(); + target.Activate(); + + shooter.Position = float3.zero; + target.Position = float3(0, 0, 100); + shooter.Target.Value = target; + shooter.SetIff(target, true); + + zone.Update(0f); // warm-up: resolves weapon/targeting stats before Fire reads them + + return new Engagement { Items = items, Zone = zone, Shooter = shooter, Target = target, WeaponItem = weaponItem, Weapon = weapon }; + } + + // 7.1 (Soul's fifth survivor): FireControl.Fire must freeze source.ResolvedTargetItem, not the raw + // source.TargetItem.Value -- the aim point is re-checked against reveal at the instant the trigger is + // pulled, same as every other read of it. Mutation: read TargetItem.Value directly. Must die. + // + // The target's non-hull equipment ranks the hardpoint weapon first (armor tier, index 0 of 2) and the + // interior "Targeting" item last (gear tier, index 1 of 2, i.e. exactly TargetGearInfoThreshold). Info is + // dropped to a level between the two tiers: the weapon stays revealed (so the shot still fires, PBase > + // 0) but the aimed item's own tier is no longer met -- the reveal re-check, not a global blackout, is + // what must drop the aim point. + [Fact] + public void AimedItemDropsOutWhenRevealDecaysBeforeFire() + { + EquippableItem aimedGear = null; + var settings = TestSettings(); + var e = Build(settings, (items, shooter, target) => + { + var targetingRef = items.ItemData.RefOf(items.ItemData.GetByName("Targeting")); + aimedGear = new EquippableItem { Data = targetingRef, Durability = 1, Lot = 6 }; + Assert.True(target.TryFindSpace(aimedGear, out var pos)); + Assert.True(target.TryEquip(aimedGear, pos)); + }); + var aimedItem = e.Target.Equipment.Single(x => x.EquippableItem == aimedGear); + + // Fully reveal and select the interior item as the aim point. + e.Shooter.EntityInfoGathered[e.Target] = 1f; + Assert.True(e.Shooter.TrySelectTargetItem(aimedItem)); + Assert.Same(aimedItem, e.Shooter.ResolvedTargetItem); + + // Decay to halfway between the armor and gear tiers: the weapon (armor tier) stays revealed, the + // aimed item (gear tier) does not. The raw field still holds the item -- nothing clears it -- but the + // read accessor must now return null. + e.Shooter.EntityInfoGathered[e.Target] = (settings.TargetArmorInfoThreshold + settings.TargetGearInfoThreshold) / 2f; + Assert.Same(aimedItem, e.Shooter.TargetItem.Value); // raw field: untouched by decay + Assert.Null(e.Shooter.ResolvedTargetItem); // read path: re-checked, and drops it + + var shotId = FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); + var shot = e.Zone.PendingShots.Single(s => s.ShotId == shotId); + + Assert.True(shot.PBase > 0f); // the shot is still worth taking -- this isn't a blackout, just a lost aim point + Assert.Null(shot.Aimed); // the frozen snapshot must not carry an aim point reveal no longer supports + } + + // 7.3/7.4 (docs/fire-control-cut.md): the campaign's only assertion that the shipped catalog is + // readable by the shipped code at all, not only by a synthetic fixture. Cut 2 shipped a targeting-system + // requirement with no data to satisfy it and every green synthetic-fixture suite missed it; merging Cuts + // 6b and 6c separately shipped a non-nullable field no existing record carried, and neither cut's own + // synthetic-fixture tests ever opened real data, so AetheriaStores.Open throwing outright on the shipped + // catalog (fixed at c896489b) passed every gate until an operator opened it by hand. Any exception here + // -- deserialization or generation -- is a failure; this is not scoped to "did a design exist." + [Fact] + public void ShippedCatalogOpensAndGeneratesAnArmedHull() + { + var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc"); + using var cache = OpenReadOnlyRealCatalog(gameData); + + // Force every EquippableItemData -- WeaponItemData included, the type the broken merge could not + // read -- to actually be enumerated. AetheriaStores.Open already deserializes every record eagerly + // at attach time (CultCache.PullAll), so this line is what turns that into a promise this test + // enforces rather than an accident of the current backing-store implementation: a future lazy-read + // change that skipped WeaponItemData specifically would still be caught here. + var equippable = cache.GetAll().ToList(); + Assert.NotEmpty(equippable); + Assert.Contains(equippable, e => e is WeaponItemData); + + var hull = cache.GetByName("LonginusX"); + Assert.NotNull(hull); + + var 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() + }; + var log = new List(); + var items = new ItemManager(cache, new ProvenanceLedger(), settings, log.Add); + var random = new Random(1u); + var generator = new LoadoutGenerator(ref random, items, null, null, null, .5f); + var pack = generator.GenerateShipLoadout(candidate => candidate == hull); + + Assert.NotNull(pack); // Cut 2's own mutation (drop the targeting designs' products): this goes null + Assert.Contains(pack.Equipment, e => (cache.Get(e.item.Data) as GearData)?.Behaviors.Any(b => b is TargetingSystemData) ?? false); + } + + private static string FindRepoRoot() + { + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent) + if (File.Exists(Path.Combine(dir.FullName, "Aetheria.Shared", "Aetheria.Shared.csproj"))) + return dir.FullName; + throw new DirectoryNotFoundException("Run from inside the Aetheria repository -- built test output was not under a recognizable repo root."); + } + + // AetheriaStores.Open (Assets/Scripts/ServerShared/AetheriaStores.cs) uses `new CultCache()`, whose + // default registry (CultDocumentRegistry.Shared) auto-discovers every [CultDocument] type loaded + // ANYWHERE in the current process by scanning the whole AppDomain -- including this very test + // assembly's own TestCatalogGlobal (AetheriaStoresTests.cs: [CultGlobal], routed to the catalog through + // PersonalityAttribute). The shipped catalog naturally carries no record of a test-only type it has + // never heard of, so opening it through the shared, process-wide registry throws "no + // aetheria.tests.catalogglobal record" -- a same-process, cross-assembly artifact of this test suite, + // not something the real game process (which never loads TestCatalogGlobal) can ever hit. + // + // This reproduces AetheriaStores.Open's own composition and validation exactly, scoped to a registry + // built only from the shipped assembly's own [CultDocument] types (CultDocumentRegistry.ForTypes does + // not re-scan the AppDomain the way the default constructor's Refresh() does), so this test still opens + // the catalog the same way the game does -- same backing store, same missing-global check, same R-heat + // validation loop -- without the test assembly's own fixture type poisoning it. + private static CultCache OpenReadOnlyRealCatalog(string catalogPath) + { + var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes() + .Where(t => t is { IsAbstract: false, IsInterface: false }) + .Where(t => t.GetCustomAttribute() != null)); + var cache = new CultCache(registry); + try + { + cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath, true), AetheriaStores.CatalogTypes); + var missing = cache.Registry.AllDescriptors.FirstOrDefault(descriptor => + descriptor.IsGlobal && + AetheriaStores.CatalogTypes.Any(home => home.IsAssignableFrom(descriptor.DocumentType)) && + cache.AllStoredDocuments.All(stored => stored.Descriptor != descriptor)); + if (missing != null) + throw new InvalidOperationException($"Catalog {catalogPath} has no {missing.SchemaName} record; catalog globals are authored, never invented."); + foreach (var data in cache.GetAll()) + { + StatValidation.ValidateHeatResponse(data); + StatValidation.ValidateStatModifiers(data.Name, data.Behaviors); + StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors); + } + foreach (var data in cache.GetAll()) + { + StatValidation.ValidateStatModifiers(data.Name, data.Behaviors); + StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors); + } + return cache; + } + catch + { + cache.Dispose(); + throw; + } + } +} From d9373643549337c01c0b5f7fd515e3f79f22671c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 19:43:57 +0200 Subject: [PATCH 2/4] Cut 7.2: mutation harnesses for Cuts 1 and 2 tests/mutation_tests_fire_control_cut1.sh and cut2.sh, modelled on cut5.sh: byte-exact I/O, sha256-verified restore per mutation, explicit tree-clean verdict. Each runs the mutation table its own cut already declares in docs/fire-control-cut.md. Two adaptations forced by the Body having moved since those cuts were written (both cut2.sh's own table entries, and its header comment): Cut 1's CombatStateStepsHeadless mutation targets FireControl.MountDirection instead of the now-deleted HardpointTransforms readback, since Cut 3 moved the AI's aim-direction path there; Cut 2's EveryArmedLoadoutGetsATargetingSystem mutation targets the surviving acquisition predicate instead of a `required: true` flag Cut 6c.2 already turned into a deliberate degrade-and-log path. TargetingSystemTests.cs's RevealOrder fixture equipped its three items in the same order FireControl.IsRevealed's ranking would put them in, so dropping that ranking entirely was unobservable -- Entity.Equipment's raw enumeration order already matched by coincidence. Reordered the fixture's equip calls to the opposite order (size-ascending, hardpoint-last) so the mutation is actually distinguishable; assertions are unchanged. Co-Authored-By: Claude Sonnet 5 --- .../TargetingSystemTests.cs | 24 +- tests/mutation_tests_fire_control_cut1.sh | 277 ++++++++++++++++++ tests/mutation_tests_fire_control_cut2.sh | 276 +++++++++++++++++ 3 files changed, 568 insertions(+), 9 deletions(-) create mode 100644 tests/mutation_tests_fire_control_cut1.sh create mode 100644 tests/mutation_tests_fire_control_cut2.sh diff --git a/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs b/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs index 4bc2ff77c..d3a436340 100644 --- a/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs +++ b/tests/Aetheria.Shared.Tests/TargetingSystemTests.cs @@ -114,10 +114,17 @@ public sealed class TargetingSystemTests : IDisposable var hull = new EquippableItem { Data = hullRef, Durability = 1, Lot = 1 }; var target = new Ship(items, zone, hull, new EntitySettings()); - var gunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); - var gun = new EquippableItem { Data = gunRef, Durability = 1, Lot = 2 }; - Assert.True(target.TryEquip(gun, new int2(0, 0))); - var weapon = target.Equipment.Single(e => e.EquippableItem == gun); + // Cut 7 (docs/fire-control-cut.md, 7.2): equipped in size-ascending, hardpoint-last order -- the + // opposite of IsRevealed's own ranking (hardpoint-mounted first, then size descending) -- so that + // dropping the explicit ranking in FireControl.IsRevealed is actually observable. Equipping in + // rank order let a "drop the ordering, rank by equipment order alone" mutation pass: Entity.Equipment + // already happened to enumerate in the correct final order by sheer coincidence of authoring order, + // so RevealOrder's own assertions never distinguished the ranked read from the raw one. + var narrowRef = items.ItemData.RefOf(items.ItemData.GetByName("Narrow")); + var narrow = new EquippableItem { Data = narrowRef, Durability = 1, Lot = 4 }; + Assert.True(target.TryFindSpace(narrow, out var narrowPos)); + Assert.True(target.TryEquip(narrow, narrowPos)); + var narrowItem = target.Equipment.Single(e => e.EquippableItem == narrow); var wideRef = items.ItemData.RefOf(items.ItemData.GetByName("Wide")); var wide = new EquippableItem { Data = wideRef, Durability = 1, Lot = 3 }; @@ -125,11 +132,10 @@ public sealed class TargetingSystemTests : IDisposable Assert.True(target.TryEquip(wide, widePos)); var wideItem = target.Equipment.Single(e => e.EquippableItem == wide); - var narrowRef = items.ItemData.RefOf(items.ItemData.GetByName("Narrow")); - var narrow = new EquippableItem { Data = narrowRef, Durability = 1, Lot = 4 }; - Assert.True(target.TryFindSpace(narrow, out var narrowPos)); - Assert.True(target.TryEquip(narrow, narrowPos)); - var narrowItem = target.Equipment.Single(e => e.EquippableItem == narrow); + var gunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var gun = new EquippableItem { Data = gunRef, Durability = 1, Lot = 2 }; + Assert.True(target.TryEquip(gun, new int2(0, 0))); + var weapon = target.Equipment.Single(e => e.EquippableItem == gun); EquippedItem targetingItem = null; if (targetingData != null) diff --git a/tests/mutation_tests_fire_control_cut1.sh b/tests/mutation_tests_fire_control_cut1.sh new file mode 100644 index 000000000..3789f6f72 --- /dev/null +++ b/tests/mutation_tests_fire_control_cut1.sh @@ -0,0 +1,277 @@ +#!/usr/bin/env bash +# Mutation tests for docs/fire-control-cut.md's Cut 1 ("Mount direction and arc become simulation data"). +# +# Five mutations, each against tests/Aetheria.Shared.Tests/FireControlTests.cs, the cut's own declared table: +# +# 1. ArcFollowsMountRotation -- MountDirection reads Entity.Direction directly instead of rotating it by the +# item's own authored rotation, so a side-mounted weapon aims like the hull instead of like its mount. +# 2. ArcBoundaryIsHalfWidth -- the bearing test compares against cos(radians(arc)) instead of +# cos(radians(arc/2)), so an authored FiringArc reads as a half-width arc. +# 3. ArcIsPlanar -- InArc dots the raw 3D vector instead of zeroing height first (R7). +# 4. HardpointOverrideBeatsDefault -- two variants, both against ArcFor: ignoring HardpointData.FiringArc +# entirely (both hardpoints then fall back to the default), and treating an authored 0 as a literal +# zero-width arc instead of "use the default." +# 5. CombatStateStepsHeadless -- the cut's own regression: Behaviors.cs:30-35's HardpointTransforms readback +# branch is gone from this tree (confirmed by negative grep, see below), so there is no literal text left +# to revert it to, and post-Cut-3 the AI's own gate (Combat.cs) reaches aim direction through +# FireControl.MountDirection, not the Behavior.Direction property Cut 1 itself touched -- a mutation there +# is provably off this test's actual path (verified: it survived). The equivalent-shape mutation instead +# throws from MountDirection itself, the same KeyNotFoundException shape a live Unity-transform readback +# threw headless before this cut, so the test's own Assert.Null(ex) still catches the regression the cut +# exists to prevent. +# +# A no-op control (a byte-identical rewrite of one target file through this script's own read/write path) +# proves the mechanism itself is transparent before any real mutation is trusted. Modelled on +# tests/mutation_tests_fire_control_cut5.sh, the good example: byte-exact I/O, sha256-verified restore after +# every single mutation, and an explicit tree-clean verdict line at exit. +# +# Usage: +# tests/mutation_tests_fire_control_cut1.sh +# +# Every mutation is reversed (byte-exact, from an on-disk copy) before the script exits, including on failure +# or interrupt, and every restore is verified against a sha256 recorded before any mutation ran: the tree- +# clean verdict at the end states PASS/FAIL explicitly rather than leaving a reader to infer it. A SIGKILL of +# the whole process group is the one termination bash cannot trap at all -- verify the tree independently +# after a run that was killed that hard. + +set -u + +if [ $# -lt 1 ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +CULTLIB_ROOT="$1" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +TEST_PROJECT="$REPO_ROOT/tests/Aetheria.Shared.Tests" + +FIRE_CONTROL_CS="$REPO_ROOT/Assets/Scripts/ServerShared/FireControl.cs" + +# --- byte-exact backup/restore: preserves line endings exactly, no text-mode translation. --- +declare -A ORIGINALS +declare -A ORIGINAL_HASH +FILES=("$FIRE_CONTROL_CS") +BACKUP_DIR="$(mktemp -d)" + +hash_file() { + sha256sum "$1" 2>/dev/null | awk '{print $1}' +} + +for f in "${FILES[@]}"; do + base="$(basename "$f")" + cp -p "$f" "$BACKUP_DIR/$base.orig" + ORIGINALS["$f"]="$BACKUP_DIR/$base.orig" + ORIGINAL_HASH["$f"]="$(hash_file "$f")" +done + +restore_and_verify() { + local file="$1" + cp -p "${ORIGINALS[$file]}" "$file" + local actual + actual="$(hash_file "$file")" + if [ "$actual" != "${ORIGINAL_HASH[$file]}" ]; then + echo "" >&2 + echo "FATAL: restoring $file did not reproduce its pre-mutation hash -- aborting." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$file]}" >&2 + echo " actual sha256: $actual" >&2 + exit 1 + fi +} + +TREE_CLEAN_OK=1 +TREE_VERDICT_DONE=0 + +verify_tree_clean() { + if [ "$TREE_VERDICT_DONE" = "1" ]; then return; fi + local f actual + for f in "${FILES[@]}"; do + cp -p "${ORIGINALS[$f]}" "$f" 2>/dev/null + actual="$(hash_file "$f")" + if [ "$actual" != "${ORIGINAL_HASH[$f]}" ]; then + echo "FATAL: $f is NOT byte-identical to how this script found it." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$f]}" >&2 + echo " actual sha256: $actual" >&2 + TREE_CLEAN_OK=0 + fi + done + echo "" + if [ "$TREE_CLEAN_OK" = "1" ]; then + echo "=== tree-clean verdict: PASS -- every target file is byte-identical to how this script found it ===" + else + echo "=== tree-clean verdict: FAIL -- see FATAL lines above; the working tree is contaminated ===" + fi + TREE_VERDICT_DONE=1 +} +trap verify_tree_clean EXIT INT TERM + +FAILURES=() + +# replace_unique FILE ANCHOR REPLACEMENT +# Anchor must occur exactly once (byte-exact match via perl, not sed's line-oriented rewriting, so a +# multi-line anchor is matched as literal text). Writes the mutated content back byte-exact. +replace_unique() { + local file="$1" anchor="$2" replacement="$3" + local count + count=$(perl -0777 -e ' + my ($anchor, $file) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $n = () = $text =~ /\Q$anchor\E/g; + print $n; + ' "$anchor" "$file") + if [ "$count" != "1" ]; then + echo "ERROR: $file: anchor must occur exactly once, found $count" >&2 + echo "--- anchor ---" >&2 + echo "$anchor" >&2 + return 1 + fi + perl -0777 -e ' + my ($file, $anchor, $replacement) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $qa = quotemeta($anchor); + $text =~ s/$qa/$replacement/; + open(my $out, ">:raw", $file) or die $!; + print $out $text; close $out; + ' "$file" "$anchor" "$replacement" +} + +ARTIFACTS_PATH="$(mktemp -d)" + +run_test() { + local test="$1" + local out + out=$(dotnet test "$TEST_PROJECT" -p:CultLibRoot="$CULTLIB_ROOT" --artifacts-path "$ARTIFACTS_PATH" --filter "FullyQualifiedName~$test" 2>&1) + if echo "$out" | grep -q "Passed!" && ! echo "$out" | grep -q "Failed: [1-9]"; then + return 0 + fi + LAST_OUTPUT="$out" + return 1 +} + +check_mutation() { + local name="$1" file="$2" anchor="$3" mutated="$4" test="$5" expect="$6" + echo "" + echo "=== $name (expect $expect) ===" + if ! replace_unique "$file" "$anchor" "$mutated"; then + FAILURES+=("$name: anchor replacement failed") + restore_and_verify "$file" + return + fi + if run_test "$test"; then + passed=1 + else + passed=0 + fi + restore_and_verify "$file" + + if [ "$expect" = "green" ]; then + if [ "$passed" = "1" ]; then + echo "OK: $test passed under a no-op mutation, as expected" + else + FAILURES+=("$name: expected green (test passing), got failure") + echo "$LAST_OUTPUT" | tail -40 + fi + else + if [ "$passed" = "0" ]; then + echo "OK: $test went red under the mutation, as expected" + else + FAILURES+=("$name: expected red (mutant killed), but $test still passed") + fi + fi +} + +# --- No-op control --- +check_mutation \ + "control (no-op round trip)" \ + "$FIRE_CONTROL_CS" \ + 'public static float3 MountDirection(EquippedItem item)' \ + 'public static float3 MountDirection(EquippedItem item)' \ + "FireControlTests.ArcFollowsMountRotation" \ + "green" + +# --- ArcFollowsMountRotation: mount direction must come from the item's own authored rotation, not the +# hull's raw facing. --- +check_mutation \ + "ArcFollowsMountRotation must read the item's rotation, not the hull's raw facing" \ + "$FIRE_CONTROL_CS" \ + 'var itemDirection = item.Entity.Direction.Rotate(item.EquippableItem.Rotation);' \ + 'var itemDirection = item.Entity.Direction;' \ + "FireControlTests.ArcFollowsMountRotation" \ + "red" + +# --- ArcBoundaryIsHalfWidth: FiringArc is full width -- the bearing test must halve it before taking cos. --- +check_mutation \ + "ArcBoundaryIsHalfWidth: FiringArc must be full width (halved before cos), not read as a half-width arc" \ + "$FIRE_CONTROL_CS" \ + 'return dot(MountDirection(weapon), planarTarget) >= cos(radians(arc / 2f));' \ + 'return dot(MountDirection(weapon), planarTarget) >= cos(radians(arc));' \ + "FireControlTests.ArcBoundaryIsHalfWidth" \ + "red" + +# --- ArcIsPlanar (R7): target height must never enter the bearing test. --- +check_mutation \ + "ArcIsPlanar (R7): InArc must zero height, not dot the raw 3D vector" \ + "$FIRE_CONTROL_CS" \ + 'var planarToTarget = float3(toTarget.x, 0, toTarget.z);' \ + 'var planarToTarget = toTarget;' \ + "FireControlTests.ArcIsPlanar" \ + "red" + +# --- HardpointOverrideBeatsDefault, variant 1: ignore HardpointData.FiringArc entirely (both hardpoints in +# the test then fall back to the default, so the 360-authored one fails at 170 degrees too). --- +check_mutation \ + "HardpointOverrideBeatsDefault (variant 1): ArcFor must read HardpointData.FiringArc, not ignore it" \ + "$FIRE_CONTROL_CS" \ + $' var arc = hardpoint?.FiringArc ?? 0f;\r\n return arc > 0 ? arc : item.ItemManager.GameplaySettings.FiringArc;' \ + ' return item.ItemManager.GameplaySettings.FiringArc;' \ + "FireControlTests.HardpointOverrideBeatsDefault" \ + "red" + +# --- HardpointOverrideBeatsDefault, variant 2: an authored 0 must mean "use the default," not a literal +# zero-width arc -- flipping > to >= makes a 0-authored hardpoint fail even 5 degrees off. --- +check_mutation \ + "HardpointOverrideBeatsDefault (variant 2): an authored 0 must fall back to the default, not read as zero width" \ + "$FIRE_CONTROL_CS" \ + 'return arc > 0 ? arc : item.ItemManager.GameplaySettings.FiringArc;' \ + 'return arc >= 0 ? arc : item.ItemManager.GameplaySettings.FiringArc;' \ + "FireControlTests.HardpointOverrideBeatsDefault" \ + "red" + +# --- CombatStateStepsHeadless: the cut's own regression -- aim direction must never depend on a live Unity +# readback. HardpointTransforms and its readback branch are already fully deleted from this tree (see the +# negative grep below), so there is no literal "restore the read" text left to revert to, and post-Cut-3 the +# AI's own gate reaches aim direction through FireControl.MountDirection (Combat.cs calls +# FireControl.HitProbability, which calls InArc, which calls MountDirection), not the Behavior.Direction +# property this cut itself touched. The equivalent-shape mutation throws from MountDirection itself -- the +# exact KeyNotFoundException shape the old HardpointTransforms dictionary lookup threw headless, before this +# cut -- so the test's own Assert.Null(Record.Exception(...)) still catches the regression this cut exists to +# prevent. --- +check_mutation \ + "CombatStateStepsHeadless: aim direction must never throw when Unity never ran (HardpointTransforms shape)" \ + "$FIRE_CONTROL_CS" \ + 'return normalize(float3(itemDirection.x, 0, itemDirection.y));' \ + 'throw new System.Collections.Generic.KeyNotFoundException("HardpointTransforms readback restored");' \ + "FireControlTests.CombatStateStepsHeadless" \ + "red" + +echo "" +verify_tree_clean + +if [ "${#FAILURES[@]}" -gt 0 ]; then + echo "" + echo "=== FAILURES ===" + for f in "${FAILURES[@]}"; do + echo "- $f" + done +fi + +if [ "${#FAILURES[@]}" -gt 0 ] || [ "$TREE_CLEAN_OK" != "1" ]; then + echo "" + echo "RESULT: FAILED -- mutations: $([ "${#FAILURES[@]}" -gt 0 ] && echo "${#FAILURES[@]} failure(s)" || echo "all behaved as declared"), tree-clean: $([ "$TREE_CLEAN_OK" = "1" ] && echo PASS || echo FAIL)" + exit 1 +fi + +echo "RESULT: All mutations behaved as declared. tree-clean: PASS" +exit 0 diff --git a/tests/mutation_tests_fire_control_cut2.sh b/tests/mutation_tests_fire_control_cut2.sh new file mode 100644 index 000000000..9e277ce84 --- /dev/null +++ b/tests/mutation_tests_fire_control_cut2.sh @@ -0,0 +1,276 @@ +#!/usr/bin/env bash +# Mutation tests for docs/fire-control-cut.md's Cut 2 ("Targeting system and reveal"). +# +# Six mutations, each against tests/Aetheria.Shared.Tests/TargetingSystemTests.cs, the cut's own declared +# table -- with two adaptations forced by later cuts changing the Body underneath this one (see the notes on +# each, and the report): +# +# 1. SelectionNeedsReveal -- IsRevealed returns true unconditionally instead of checking the tier. +# 2. RevealOrder -- drop the ranking (hardpoint-first, size-descending) entirely. +# 3. RevealSpansBothThresholds -- swap the two authored thresholds in the lerp. +# 4. UnaidedFiresWorse -- Accuracy/Precision/Resolution fall back to the (destroyed/offline) system's own +# stats instead of the unaided settings, i.e. drop the Active.Value gate. +# 5. StarvedTargetingRollsWorse -- the brownout ruling becomes a switch (PowerSupply <= 1e-4 ? 0 : 1) +# instead of the authored pow(PowerSupply, exponent) gradient. This is Entity.cs's PowerSupplyFactor, +# shared production code the brownout ruling (docs/stats-and-power-cut.md) applies well beyond Accuracy +# -- restored immediately after the single filtered test run, same as every other mutation here. +# 6. EveryArmedLoadoutGetsATargetingSystem -- the doc's own declared mutation ("drop required: true") no +# longer has a `required: true` to drop: Cut 6c.2 (LoadoutGenerator.cs, 2026-09-19) deliberately changed +# this call from required:true/throw to required:false/degrade-and-log, an operator ruling this harness +# must not fight. The adapted mutation targets the surviving acquisition attempt instead -- the predicate +# that finds a targeting-system seller never matches -- which is what "the required-equipment rule +# regresses to nothing" now looks like on this Body. See the report for the full account. +# +# A no-op control (a byte-identical rewrite of one target file through this script's own read/write path) +# proves the mechanism itself is transparent before any real mutation is trusted. Modelled on +# tests/mutation_tests_fire_control_cut5.sh, the good example: byte-exact I/O, sha256-verified restore after +# every single mutation, and an explicit tree-clean verdict line at exit. +# +# Usage: +# tests/mutation_tests_fire_control_cut2.sh +# +# Every mutation is reversed (byte-exact, from an on-disk copy) before the script exits, including on failure +# or interrupt, and every restore is verified against a sha256 recorded before any mutation ran: the tree- +# clean verdict at the end states PASS/FAIL explicitly rather than leaving a reader to infer it. A SIGKILL of +# the whole process group is the one termination bash cannot trap at all -- verify the tree independently +# after a run that was killed that hard. + +set -u + +if [ $# -lt 1 ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +CULTLIB_ROOT="$1" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +TEST_PROJECT="$REPO_ROOT/tests/Aetheria.Shared.Tests" + +FIRE_CONTROL_CS="$REPO_ROOT/Assets/Scripts/ServerShared/FireControl.cs" +ENTITY_CS="$REPO_ROOT/Assets/Scripts/ServerShared/Entity.cs" +LOADOUT_GENERATOR_CS="$REPO_ROOT/Assets/Scripts/ServerShared/LoadoutGenerator.cs" + +# --- byte-exact backup/restore: preserves line endings exactly, no text-mode translation. --- +declare -A ORIGINALS +declare -A ORIGINAL_HASH +FILES=("$FIRE_CONTROL_CS" "$ENTITY_CS" "$LOADOUT_GENERATOR_CS") +BACKUP_DIR="$(mktemp -d)" + +hash_file() { + sha256sum "$1" 2>/dev/null | awk '{print $1}' +} + +for f in "${FILES[@]}"; do + base="$(basename "$f")" + cp -p "$f" "$BACKUP_DIR/$base.orig" + ORIGINALS["$f"]="$BACKUP_DIR/$base.orig" + ORIGINAL_HASH["$f"]="$(hash_file "$f")" +done + +restore_and_verify() { + local file="$1" + cp -p "${ORIGINALS[$file]}" "$file" + local actual + actual="$(hash_file "$file")" + if [ "$actual" != "${ORIGINAL_HASH[$file]}" ]; then + echo "" >&2 + echo "FATAL: restoring $file did not reproduce its pre-mutation hash -- aborting." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$file]}" >&2 + echo " actual sha256: $actual" >&2 + exit 1 + fi +} + +TREE_CLEAN_OK=1 +TREE_VERDICT_DONE=0 + +verify_tree_clean() { + if [ "$TREE_VERDICT_DONE" = "1" ]; then return; fi + local f actual + for f in "${FILES[@]}"; do + cp -p "${ORIGINALS[$f]}" "$f" 2>/dev/null + actual="$(hash_file "$f")" + if [ "$actual" != "${ORIGINAL_HASH[$f]}" ]; then + echo "FATAL: $f is NOT byte-identical to how this script found it." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$f]}" >&2 + echo " actual sha256: $actual" >&2 + TREE_CLEAN_OK=0 + fi + done + echo "" + if [ "$TREE_CLEAN_OK" = "1" ]; then + echo "=== tree-clean verdict: PASS -- every target file is byte-identical to how this script found it ===" + else + echo "=== tree-clean verdict: FAIL -- see FATAL lines above; the working tree is contaminated ===" + fi + TREE_VERDICT_DONE=1 +} +trap verify_tree_clean EXIT INT TERM + +FAILURES=() + +# replace_unique FILE ANCHOR REPLACEMENT +replace_unique() { + local file="$1" anchor="$2" replacement="$3" + local count + count=$(perl -0777 -e ' + my ($anchor, $file) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $n = () = $text =~ /\Q$anchor\E/g; + print $n; + ' "$anchor" "$file") + if [ "$count" != "1" ]; then + echo "ERROR: $file: anchor must occur exactly once, found $count" >&2 + echo "--- anchor ---" >&2 + echo "$anchor" >&2 + return 1 + fi + perl -0777 -e ' + my ($file, $anchor, $replacement) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $qa = quotemeta($anchor); + $text =~ s/$qa/$replacement/; + open(my $out, ">:raw", $file) or die $!; + print $out $text; close $out; + ' "$file" "$anchor" "$replacement" +} + +ARTIFACTS_PATH="$(mktemp -d)" + +run_test() { + local test="$1" + local out + out=$(dotnet test "$TEST_PROJECT" -p:CultLibRoot="$CULTLIB_ROOT" --artifacts-path "$ARTIFACTS_PATH" --filter "FullyQualifiedName~$test" 2>&1) + if echo "$out" | grep -q "Passed!" && ! echo "$out" | grep -q "Failed: [1-9]"; then + return 0 + fi + LAST_OUTPUT="$out" + return 1 +} + +check_mutation() { + local name="$1" file="$2" anchor="$3" mutated="$4" test="$5" expect="$6" + echo "" + echo "=== $name (expect $expect) ===" + if ! replace_unique "$file" "$anchor" "$mutated"; then + FAILURES+=("$name: anchor replacement failed") + restore_and_verify "$file" + return + fi + if run_test "$test"; then + passed=1 + else + passed=0 + fi + restore_and_verify "$file" + + if [ "$expect" = "green" ]; then + if [ "$passed" = "1" ]; then + echo "OK: $test passed under a no-op mutation, as expected" + else + FAILURES+=("$name: expected green (test passing), got failure") + echo "$LAST_OUTPUT" | tail -40 + fi + else + if [ "$passed" = "0" ]; then + echo "OK: $test went red under the mutation, as expected" + else + FAILURES+=("$name: expected red (mutant killed), but $test still passed") + fi + fi +} + +# --- No-op control --- +check_mutation \ + "control (no-op round trip)" \ + "$FIRE_CONTROL_CS" \ + 'return info >= tier;' \ + 'return info >= tier;' \ + "TargetingSystemTests.SelectionNeedsReveal" \ + "green" + +# --- SelectionNeedsReveal: IsRevealed must check the tier, not return true unconditionally. --- +check_mutation \ + "SelectionNeedsReveal: IsRevealed must check the tier, not return true unconditionally" \ + "$FIRE_CONTROL_CS" \ + 'return info >= tier;' \ + 'return true;' \ + "TargetingSystemTests.SelectionNeedsReveal" \ + "red" + +# --- RevealOrder: hardpoint-mounted items must rank before interior ones, larger before smaller. --- +check_mutation \ + "RevealOrder: IsRevealed's ranking must be hardpoint-first, size-descending, not equipment order alone" \ + "$FIRE_CONTROL_CS" \ + $' var ranked = target.Equipment\r\n .Where(e => e.Data.HardpointType != HardpointType.Hull && e.EquippableItem.Durability >= .01f)\r\n .OrderByDescending(e => e.Data.HardpointType != HardpointType.Tool)\r\n .ThenByDescending(e => e.Data.Shape.Coordinates.Length)\r\n .ToList();' \ + $' var ranked = target.Equipment\r\n .Where(e => e.Data.HardpointType != HardpointType.Hull && e.EquippableItem.Durability >= .01f)\r\n .ToList();' \ + "TargetingSystemTests.RevealOrder" \ + "red" + +# --- RevealSpansBothThresholds: the first item must reveal at TargetArmorInfoThreshold and the last at +# TargetGearInfoThreshold -- swap them and the ends flip. --- +check_mutation \ + "RevealSpansBothThresholds: the ranking's tiers must not be swapped" \ + "$FIRE_CONTROL_CS" \ + 'var tier = lerp(settings.TargetArmorInfoThreshold, settings.TargetGearInfoThreshold,' \ + 'var tier = lerp(settings.TargetGearInfoThreshold, settings.TargetArmorInfoThreshold,' \ + "TargetingSystemTests.RevealSpansBothThresholds" \ + "red" + +# --- UnaidedFiresWorse (Q4): a destroyed or disabled targeting system must fall back to the unaided figures, +# not keep supplying its own (now-meaningless) stats. Mutation: drop the Active.Value gate from Accuracy. --- +check_mutation \ + "UnaidedFiresWorse: Accuracy must gate on Active.Value, not just existence, before trusting the system" \ + "$FIRE_CONTROL_CS" \ + $' var system = entity.GetBehavior();\r\n return system != null && system.Item.Active.Value\r\n ? system.Accuracy\r\n : entity.ItemManager.GameplaySettings.UnaidedAccuracy;' \ + $' var system = entity.GetBehavior();\r\n return system != null\r\n ? system.Accuracy\r\n : entity.ItemManager.GameplaySettings.UnaidedAccuracy;' \ + "TargetingSystemTests.UnaidedFiresWorse" \ + "red" + +# --- StarvedTargetingRollsWorse: the brownout ruling on Accuracy (a shared PowerSupply term, F1 of +# docs/stats-and-power-cut.md) must be a gradient (pow(PowerSupply, exponent)), not a switch. This is Entity's +# own PowerSupplyFactor, read by every stat carrying a PowerSupply term, not just targeting -- restored +# immediately after this one filtered test run, same discipline as every mutation in this harness. --- +check_mutation \ + "StarvedTargetingRollsWorse: PowerSupplyFactor must be a gradient, not a >1e-4 on/off switch" \ + "$ENTITY_CS" \ + 'public float PowerSupplyFactor(float exponent) => pow(PowerSupply, exponent);' \ + 'public float PowerSupplyFactor(float exponent) => PowerSupply <= 1e-4f ? 0f : 1f;' \ + "TargetingSystemTests.StarvedTargetingRollsWorse" \ + "red" + +# --- EveryArmedLoadoutGetsATargetingSystem (Q4): every armed hull's loadout must still try to acquire a +# targeting system. The doc's own mutation ("drop required: true") no longer applies -- Cut 6c.2 already +# changed this call to required:false/degrade-and-log, an operator ruling (see the header comment and the +# report). The adapted mutation makes the acquisition predicate never match, which is what "the rule regresses +# to nothing" now looks like: FillInterior degrades exactly as it does for a galaxy with no seller, silently. --- +check_mutation \ + "EveryArmedLoadoutGetsATargetingSystem: FillInterior must still attempt to acquire a targeting system for an armed hull" \ + "$LOADOUT_GENERATOR_CS" \ + $' var (targetingProduct, targetingData) = RandomProduct(2, item =>\r\n item.Behaviors.Any(b => b is TargetingSystemData) &&\r\n item.Shape.FitsWithin(emptyShape, out _, out _));' \ + $' var (targetingProduct, targetingData) = RandomProduct(2, item => false);' \ + "TargetingSystemTests.EveryArmedLoadoutGetsATargetingSystem" \ + "red" + +echo "" +verify_tree_clean + +if [ "${#FAILURES[@]}" -gt 0 ]; then + echo "" + echo "=== FAILURES ===" + for f in "${FAILURES[@]}"; do + echo "- $f" + done +fi + +if [ "${#FAILURES[@]}" -gt 0 ] || [ "$TREE_CLEAN_OK" != "1" ]; then + echo "" + echo "RESULT: FAILED -- mutations: $([ "${#FAILURES[@]}" -gt 0 ] && echo "${#FAILURES[@]} failure(s)" || echo "all behaved as declared"), tree-clean: $([ "$TREE_CLEAN_OK" = "1" ] && echo PASS || echo FAIL)" + exit 1 +fi + +echo "RESULT: All mutations behaved as declared. tree-clean: PASS" +exit 0 From 76758dae5d37bf7833c93092b2e4baedb0cee69f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 19:56:39 +0200 Subject: [PATCH 3/4] Cut 7.2: the Cut 3 harness, and the fixture that let commit-is-not-arrival slip ShotResolvesOnArrival stepped the zone from t=4 straight to t=6, crossing both the commit horizon (4.5s) and arrival (5s) inside one Zone.Update. A mutation collapsing Step's arrival gate to `if (shot.Committed)` therefore survived it: one wide tick crosses both thresholds either way, so the test could not tell "applied on arrival" from "applied as soon as committed". R4's central distinction -- the commit decides the outcome, arrival performs it -- was declared in Cut 3's prose, pinned by nothing, and this is the third rule in this campaign found undefended by a fixture too coarse to distinguish the mutant. Adds a tick at t=4.55, past commit and short of arrival, where the durability must still be untouched. Co-Authored-By: Claude Opus 5 --- .../FireAuthorityTests.cs | 14 +- tests/mutation_tests_fire_control_cut3.sh | 366 ++++++++++++++++++ 2 files changed, 377 insertions(+), 3 deletions(-) create mode 100644 tests/mutation_tests_fire_control_cut3.sh diff --git a/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs b/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs index 1fb4d0554..732b35f9f 100644 --- a/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs +++ b/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs @@ -284,14 +284,22 @@ public sealed class FireAuthorityTests : IDisposable public void ShotResolvesOnArrival() { var e = Build(TestSettings(), damage: 100, velocity: 10, accuracy: 1, resolution: 1, spread: 0, targetRange: 50); - // range 50, velocity 10 -> flight time 5s, well past the .5s commit horizon. + // range 50, velocity 10 -> flight time 5s, commit at 4.5s (.5s horizon), arrival at 5s. FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); var before = e.Target.Hull.Durability; - e.Zone.Update(4f); // still short of arrival (5s) + e.Zone.Update(4f); // still short of commit (4.5s) Assert.Equal(before, e.Target.Hull.Durability); - e.Zone.Update(2f); // now past arrival + // Cut 7 (docs/fire-control-cut.md, 7.2): an intermediate check between commit and arrival -- without + // it, jumping straight from before-commit to past-arrival lets "apply as soon as committed, not only + // once also arrived" (Step's arrival gate collapsed to just `if (shot.Committed)`) go unnoticed, since + // a single wide Zone.Update spanning both CommitTime and ArrivalTime crosses both thresholds in one + // call either way. + e.Zone.Update(.55f); // t=4.55: past commit (4.5s), still short of arrival (5s) + Assert.Equal(before, e.Target.Hull.Durability); + + e.Zone.Update(1f); // now past arrival Assert.True(e.Target.Hull.Durability < before); } diff --git a/tests/mutation_tests_fire_control_cut3.sh b/tests/mutation_tests_fire_control_cut3.sh new file mode 100644 index 000000000..b47255d12 --- /dev/null +++ b/tests/mutation_tests_fire_control_cut3.sh @@ -0,0 +1,366 @@ +#!/usr/bin/env bash +# Mutation tests for docs/fire-control-cut.md's Cut 3 ("Hit authority moves"). +# +# Fourteen check_mutation calls covering the cut's own thirteen declared tests (one, ProbabilityFollowsInputs, +# carries three sub-mutations from its own declared list, so fifteen mutations run in total) against +# tests/Aetheria.Shared.Tests/FireAuthorityTests.cs -- plus one test the harness deliberately does NOT attempt +# a mutation for, documented below rather than silently skipped: +# +# OutOfArcConsumesNoDraw -- NOT YET REACHED. The test asserts against ItemManager.Random (`e.Items.Random`), +# but Cut 6b (6.1) moved every shot's roll onto its own freshly-seeded, immediately-discarded +# `new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u)` local to Commit -- a deliberate, +# good change (reproducibility independent of unrelated draws elsewhere) that also means Commit never reads +# or writes ItemManager.Random at all, on any path, arc or no arc. Confirmed empirically: applying the +# declared mutation ("roll first and multiply by zero" -- `var hit = random.NextFloat() < p;` in place of +# `var hit = p > 0f && random.NextFloat() < p;`) leaves this test green, because the local generator that +# mutation actually touches is discarded before anything outside Commit could observe it, and nothing else +# in the Fire/Step path ever touches ItemManager.Random (Zone.NextShotId is a plain counter). This is not a +# fixable fixture defect -- there is no external observation point for "did Commit's own local generator +# draw" under the current per-shot-seeded design, short of instrumenting FireControl itself (an injectable +# call-counting random source, or reverting 6.1's shared-stream removal) -- a production-code seam change, +# not a test change, and out of this cut's scope. Reaching it takes that seam. +# +# A no-op control (a byte-identical rewrite of one target file through this script's own read/write path) +# proves the mechanism itself is transparent before any real mutation is trusted. Modelled on +# tests/mutation_tests_fire_control_cut5.sh, the good example: byte-exact I/O, sha256-verified restore after +# every single mutation, and an explicit tree-clean verdict line at exit. +# +# Usage: +# tests/mutation_tests_fire_control_cut3.sh +# +# Every mutation is reversed (byte-exact, from an on-disk copy) before the script exits, including on failure +# or interrupt, and every restore is verified against a sha256 recorded before any mutation ran: the tree- +# clean verdict at the end states PASS/FAIL explicitly rather than leaving a reader to infer it. A SIGKILL of +# the whole process group is the one termination bash cannot trap at all -- verify the tree independently +# after a run that was killed that hard. + +set -u + +if [ $# -lt 1 ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +CULTLIB_ROOT="$1" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +TEST_PROJECT="$REPO_ROOT/tests/Aetheria.Shared.Tests" + +FIRE_CONTROL_CS="$REPO_ROOT/Assets/Scripts/ServerShared/FireControl.cs" +ENTITY_CS="$REPO_ROOT/Assets/Scripts/ServerShared/Entity.cs" + +# --- byte-exact backup/restore: preserves line endings exactly, no text-mode translation. --- +declare -A ORIGINALS +declare -A ORIGINAL_HASH +FILES=("$FIRE_CONTROL_CS" "$ENTITY_CS") +BACKUP_DIR="$(mktemp -d)" + +hash_file() { + sha256sum "$1" 2>/dev/null | awk '{print $1}' +} + +for f in "${FILES[@]}"; do + base="$(basename "$f")" + cp -p "$f" "$BACKUP_DIR/$base.orig" + ORIGINALS["$f"]="$BACKUP_DIR/$base.orig" + ORIGINAL_HASH["$f"]="$(hash_file "$f")" +done + +restore_and_verify() { + local file="$1" + cp -p "${ORIGINALS[$file]}" "$file" + local actual + actual="$(hash_file "$file")" + if [ "$actual" != "${ORIGINAL_HASH[$file]}" ]; then + echo "" >&2 + echo "FATAL: restoring $file did not reproduce its pre-mutation hash -- aborting." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$file]}" >&2 + echo " actual sha256: $actual" >&2 + exit 1 + fi +} + +TREE_CLEAN_OK=1 +TREE_VERDICT_DONE=0 + +verify_tree_clean() { + if [ "$TREE_VERDICT_DONE" = "1" ]; then return; fi + local f actual + for f in "${FILES[@]}"; do + cp -p "${ORIGINALS[$f]}" "$f" 2>/dev/null + actual="$(hash_file "$f")" + if [ "$actual" != "${ORIGINAL_HASH[$f]}" ]; then + echo "FATAL: $f is NOT byte-identical to how this script found it." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$f]}" >&2 + echo " actual sha256: $actual" >&2 + TREE_CLEAN_OK=0 + fi + done + echo "" + if [ "$TREE_CLEAN_OK" = "1" ]; then + echo "=== tree-clean verdict: PASS -- every target file is byte-identical to how this script found it ===" + else + echo "=== tree-clean verdict: FAIL -- see FATAL lines above; the working tree is contaminated ===" + fi + TREE_VERDICT_DONE=1 +} +trap verify_tree_clean EXIT INT TERM + +FAILURES=() + +# replace_unique FILE ANCHOR REPLACEMENT +replace_unique() { + local file="$1" anchor="$2" replacement="$3" + local count + count=$(perl -0777 -e ' + my ($anchor, $file) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $n = () = $text =~ /\Q$anchor\E/g; + print $n; + ' "$anchor" "$file") + if [ "$count" != "1" ]; then + echo "ERROR: $file: anchor must occur exactly once, found $count" >&2 + echo "--- anchor ---" >&2 + echo "$anchor" >&2 + return 1 + fi + perl -0777 -e ' + my ($file, $anchor, $replacement) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $qa = quotemeta($anchor); + $text =~ s/$qa/$replacement/; + open(my $out, ">:raw", $file) or die $!; + print $out $text; close $out; + ' "$file" "$anchor" "$replacement" +} + +ARTIFACTS_PATH="$(mktemp -d)" + +run_test() { + local test="$1" + local out + out=$(dotnet test "$TEST_PROJECT" -p:CultLibRoot="$CULTLIB_ROOT" --artifacts-path "$ARTIFACTS_PATH" --filter "FullyQualifiedName~$test" 2>&1) + if echo "$out" | grep -q "Passed!" && ! echo "$out" | grep -q "Failed: [1-9]"; then + return 0 + fi + LAST_OUTPUT="$out" + return 1 +} + +check_mutation() { + local name="$1" file="$2" anchor="$3" mutated="$4" test="$5" expect="$6" + echo "" + echo "=== $name (expect $expect) ===" + if ! replace_unique "$file" "$anchor" "$mutated"; then + FAILURES+=("$name: anchor replacement failed") + restore_and_verify "$file" + return + fi + if run_test "$test"; then + passed=1 + else + passed=0 + fi + restore_and_verify "$file" + + if [ "$expect" = "green" ]; then + if [ "$passed" = "1" ]; then + echo "OK: $test passed under a no-op mutation, as expected" + else + FAILURES+=("$name: expected green (test passing), got failure") + echo "$LAST_OUTPUT" | tail -40 + fi + else + if [ "$passed" = "0" ]; then + echo "OK: $test went red under the mutation, as expected" + else + FAILURES+=("$name: expected red (mutant killed), but $test still passed") + fi + fi +} + +# --- No-op control --- +check_mutation \ + "control (no-op round trip)" \ + "$FIRE_CONTROL_CS" \ + 'var elapsed = now - shot.FireTime;' \ + 'var elapsed = now - shot.FireTime;' \ + "FireAuthorityTests.EvasionCountsUntilCommitAndNotAfter" \ + "green" + +# --- RollsAreSeeded (Q5): a fight must be reproducible from its seed. Mutation: draw from an unseeded, +# non-reproducible generator instead of the pure function of (zone identity, shot id). A first attempt seeded +# from System.DateTime.UtcNow.Ticks survived: this whole 50-shot fixture runs faster than the clock's own tick +# resolution, so two runs a few milliseconds apart drew the identical "wall clock" value every time and the +# mutation was accidentally still deterministic. Guid.NewGuid() carries its own entropy source independent of +# clock resolution and reliably breaks reproducibility. --- +check_mutation \ + "RollsAreSeeded: Commit's draw must be a pure function of (zone, shot id), not fresh entropy per call" \ + "$FIRE_CONTROL_CS" \ + 'var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u);' \ + 'var random = new Random((uint) System.Guid.NewGuid().GetHashCode() | 1u);' \ + "FireAuthorityTests.RollsAreSeeded" \ + "red" + +# --- ProbabilityFollowsInputs, variant 1/3: drop pSensor -- probability stops depending on detection info. --- +check_mutation \ + "ProbabilityFollowsInputs (1/3): HitProbability must scale with pSensor, not drop it" \ + "$FIRE_CONTROL_CS" \ + 'return Accuracy(source) * pSensor * pSpread;' \ + 'return Accuracy(source) * pSpread;' \ + "FireAuthorityTests.ProbabilityFollowsInputs" \ + "red" + +# --- ProbabilityFollowsInputs, variant 2/3: drop the range gate -- nonzero probability outside [MinRange,Range]. --- +check_mutation \ + "ProbabilityFollowsInputs (2/3): HitProbability must gate on [MinRange, Range], not skip the check" \ + "$FIRE_CONTROL_CS" \ + 'if (range < weapon.MinRange || range > weapon.Range) return 0f;' \ + '// dropped -- no range gate' \ + "FireAuthorityTests.ProbabilityFollowsInputs" \ + "red" + +# --- ProbabilityFollowsInputs, variant 3/3: drop the UnaidedAccuracy cap -- an unaided shooter rolls at full +# strength (1f) instead of the authored handicap. --- +check_mutation \ + "ProbabilityFollowsInputs (3/3): an unaided shooter must cap at UnaidedAccuracy, not roll at full strength" \ + "$FIRE_CONTROL_CS" \ + ': entity.ItemManager.GameplaySettings.UnaidedAccuracy;' \ + ': 1f;' \ + "FireAuthorityTests.ProbabilityFollowsInputs" \ + "red" + +# --- ShotResolvesOnArrival (R3): no durability change before arrival. Mutation: apply as soon as committed, +# not only once the shot has also arrived. --- +check_mutation \ + "ShotResolvesOnArrival: Step must apply only at ArrivalTime, not as soon as a shot commits" \ + "$FIRE_CONTROL_CS" \ + 'if (shot.Committed && now >= shot.ArrivalTime)' \ + 'if (shot.Committed)' \ + "FireAuthorityTests.ShotResolvesOnArrival" \ + "red" + +# --- DeadEntityStopsTakingShots (0b table): a shot whose target left the zone must resolve as a miss and be +# removed outright, not go on resolving against a target no longer in play. --- +check_mutation \ + "DeadEntityStopsTakingShots: Step must detect a target that left the zone, not resolve against it anyway" \ + "$FIRE_CONTROL_CS" \ + 'var targetGone = shot.Target != null && !zone.Entities.Contains(shot.Target);' \ + 'var targetGone = false;' \ + "FireAuthorityTests.DeadEntityStopsTakingShots" \ + "red" + +# --- OutcomeCommitsBeforeImpact (R4): ShotCommitted must fire exactly once per shot. Mutation: publish it +# twice from the same commit branch. --- +check_mutation \ + "OutcomeCommitsBeforeImpact: ShotCommitted must publish exactly once per shot, not twice" \ + "$FIRE_CONTROL_CS" \ + $' zone.ShotCommitted.OnNext(shot.Outcome);\r\n shots[i] = shot;\r\n }\r\n\r\n if (shot.Committed && now >= shot.ArrivalTime)' \ + $' zone.ShotCommitted.OnNext(shot.Outcome);\r\n zone.ShotCommitted.OnNext(shot.Outcome);\r\n shots[i] = shot;\r\n }\r\n\r\n if (shot.Committed && now >= shot.ArrivalTime)' \ + "FireAuthorityTests.OutcomeCommitsBeforeImpact" \ + "red" + +# --- EvasionCountsUntilCommitAndNotAfter (R4's second half): deviation must be measured against the elapsed +# time at commit, not at fire (elapsed pinned to 0, i.e. no drift accounted for at all). Cut 5's own harness +# already pins this test's OTHER declared mutation (elapsed pinned to the shot's fixed total duration, i.e. +# measured as if always at arrival) as a named survivor; this is the complementary variant from this cut's own +# table. --- +check_mutation \ + "EvasionCountsUntilCommitAndNotAfter: deviation must track elapsed time, not measure as if fired an instant ago" \ + "$FIRE_CONTROL_CS" \ + 'var elapsed = now - shot.FireTime;' \ + 'var elapsed = 0f;' \ + "FireAuthorityTests.EvasionCountsUntilCommitAndNotAfter" \ + "red" + +# --- ShortFlightCommitsAtFire (R4's graceful degradation): a sub-horizon flight must commit at fire time, in +# the same tick. Mutation: always require the full CommitHorizon regardless of how short the flight is, so a +# zero-velocity shot's CommitTime lands after its own ArrivalTime and the commit/resolve order breaks. --- +check_mutation \ + "ShortFlightCommitsAtFire: CommitTime must degrade to fire time for a sub-horizon flight, not always wait a full horizon" \ + "$FIRE_CONTROL_CS" \ + 'CommitTime = now + max(0f, flightTime - commitHorizon),' \ + 'CommitTime = now + commitHorizon,' \ + "FireAuthorityTests.ShortFlightCommitsAtFire" \ + "red" + +# --- OutcomeIsSnapshotNotReread (R10/Q6): Apply must use the frozen shot.Damage, not re-read the weapon's +# live (possibly since-changed) Damage at arrival. --- +check_mutation \ + "OutcomeIsSnapshotNotReread: Apply must use the frozen shot.Damage, not re-read the live weapon stat" \ + "$FIRE_CONTROL_CS" \ + 'shot.Target.ApplyHit(shot.Source, shot.Outcome.Cell, shot.DamageSpread, shot.Penetration, shot.Damage, hitDirection);' \ + 'shot.Target.ApplyHit(shot.Source, shot.Outcome.Cell, shot.DamageSpread, shot.Penetration, ((Weapon) shot.Weapon.Behaviors.First(b => b is Weapon)).Damage, hitDirection);' \ + "FireAuthorityTests.OutcomeIsSnapshotNotReread" \ + "red" + +# --- AimedHitLandsOnSelectedItem (R5's payoff): with Precision 1, a hit must land on the aimed item's own +# cells, not a uniform-random hull cell. --- +check_mutation \ + "AimedHitLandsOnSelectedItem: the roll must respect Aimed, not always pick a uniform random hull cell" \ + "$FIRE_CONTROL_CS" \ + 'if (aimedCells != null && aimedCells.Length > 0 && random.NextFloat() < shot.Precision)' \ + 'if (false)' \ + "FireAuthorityTests.AimedHitLandsOnSelectedItem" \ + "red" + +# --- HardpointHitDamagesItemThenHull: damage above armor plus item durability must pass its remainder on to +# the hull. Mutation: drop the remainder (it never reaches the hull). --- +check_mutation \ + "HardpointHitDamagesItemThenHull: the remainder after armor and item must reach the hull, not be dropped" \ + "$ENTITY_CS" \ + 'hullDamage += d;' \ + '// dropped -- remainder never reaches the hull' \ + "FireAuthorityTests.HardpointHitDamagesItemThenHull" \ + "red" + +# --- PenetrationMarchIsPlanar (R7): the march must rotate the hit direction into the target's own facing, not +# march along the raw world-space direction. --- +check_mutation \ + "PenetrationMarchIsPlanar: the penetration march must rotate into the target's own frame, not use raw world direction" \ + "$ENTITY_CS" \ + $' var forward = normalize(Direction);\r\n var right = float2(forward.y, -forward.x);\r\n var penetrationVector = normalize(float2(dot(hitDirection, right), dot(hitDirection, forward)));' \ + ' var penetrationVector = normalize(hitDirection);' \ + "FireAuthorityTests.PenetrationMarchIsPlanar" \ + "red" + +# --- ShieldTakesHit: the absorb rule must have one owner (FireControl.Commit). Mutation: remove the shield +# branch entirely -- shielded/shieldBroken never get set, so Apply always lets the hit reach the hull. --- +check_mutation \ + "ShieldTakesHit: Commit must decide the shield branch, not skip it (hit always reaches the hull)" \ + "$FIRE_CONTROL_CS" \ + $' var shield = shot.Target.Shield;\r\n var shieldActive = shield != null && shield.Item.Active.Value;\r\n if (shieldActive && shield.CanTakeHit(shot.DamageType, shot.Damage)) shielded = true;\r\n else if (shieldActive) shieldBroken = true;' \ + $' var shield = shot.Target.Shield;' \ + "FireAuthorityTests.ShieldTakesHit" \ + "red" + +echo "" +echo "=== OutOfArcConsumesNoDraw: NOT YET REACHED (see header comment) -- confirming the test itself is still green with no mutation applied ===" +if run_test "FireAuthorityTests.OutOfArcConsumesNoDraw"; then + echo "OK: FireAuthorityTests.OutOfArcConsumesNoDraw passes on the unmutated tree" +else + FAILURES+=("OutOfArcConsumesNoDraw: the unmutated test itself failed -- that is a real regression, not a not-yet-reached mutation") + echo "$LAST_OUTPUT" | tail -40 +fi + +echo "" +verify_tree_clean + +if [ "${#FAILURES[@]}" -gt 0 ]; then + echo "" + echo "=== FAILURES ===" + for f in "${FAILURES[@]}"; do + echo "- $f" + done +fi + +if [ "${#FAILURES[@]}" -gt 0 ] || [ "$TREE_CLEAN_OK" != "1" ]; then + echo "" + echo "RESULT: FAILED -- mutations: $([ "${#FAILURES[@]}" -gt 0 ] && echo "${#FAILURES[@]} failure(s)" || echo "all behaved as declared"), tree-clean: $([ "$TREE_CLEAN_OK" = "1" ] && echo PASS || echo FAIL)" + exit 1 +fi + +echo "RESULT: All attempted mutations behaved as declared (OutOfArcConsumesNoDraw: not yet reached, see header). tree-clean: PASS" +exit 0 From 0ae8226ccbec99e79ff226085bfa75d7866fca81 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 20:14:16 +0200 Subject: [PATCH 4/4] Cut 7: retire a test Cut 6b made vacuous, and the invariant it claimed Cut 3's harness reported OutOfArcConsumesNoDraw as "not yet reached" -- no mutation could turn it red. Chasing that rather than accepting it found the reason, and it is not a fixture defect. The test asserted that a shot gated to zero draws nothing from ItemManager. Random, so the shared stream advanced exactly as if the shot had never queued. Cut 6b moved every roll onto a per-shot local generator seeded from (zone, shot id), so Commit stopped touching that stream on EVERY path. The test then passed for a reason unrelated to arcs -- it passed identically with the target dead ahead -- and the rule it named stopped existing along with the stream it was about. The short-circuit it guarded is now a cheap guard, not an invariant, and Commit's comment was still asserting otherwise. Rewritten as CombatNeverDrawsFromTheSharedStream, a Theory over both an out-of-arc and an in-arc target, pinning the rule that IS live after 6b: no combat path draws from the shared stream at all. Verified by hand -- restoring the shared-stream read in Commit turns the in-arc case red while the out-of-arc case stays green, which is exactly why the old test could not have caught it. 218 tests pass. All six mutation harnesses run clean with tree-clean PASS. Co-Authored-By: Claude Opus 5 --- Assets/Scripts/ServerShared/FireControl.cs | 11 +++++++--- .../FireAuthorityTests.cs | 21 ++++++++++++------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 214f0bc2d..e9cc2829f 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -290,9 +290,14 @@ public static class FireControl // R3/R4: the one roll. p_base was frozen at fire; the only thing measured live is how far the target has // actually strayed, by now, from where a straight-line projection of its fire-time velocity said it would - // be -- forgiven by the targeting system's Tracking, likewise frozen at fire. A shot gated to zero at fire - // (out of arc, out of range, unlocked, undetected) draws nothing here (short-circuit below): the RNG - // sequence is exactly as if the shot had never queued. + // be -- forgiven by the targeting system's Tracking, likewise frozen at fire. + // + // Cut 7: the short-circuit below (`p > 0f &&`) is a guard, NOT an invariant. It used to be one -- a shot + // gated to zero at fire had to draw nothing so the shared stream advanced exactly as if it had never + // queued -- but Cut 6b gave every shot its own generator, seeded from (zone, shot id) and discarded here, + // so whether a gated shot draws is unobservable from anywhere. The claim this comment used to make is + // gone with the stream it was about, and the test that asserted it became vacuous the same moment; what + // replaced it pins the live rule instead (combat touches no shared stream, on any path). private static ShotOutcome Commit(Zone zone, PendingShot shot, float now) { // Cut 6b, 6.1 (Soul finding 6): a shot's dice belong to the shot, not to whatever else happened to diff --git a/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs b/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs index 732b35f9f..3f65f24d8 100644 --- a/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs +++ b/tests/Aetheria.Shared.Tests/FireAuthorityTests.cs @@ -256,15 +256,20 @@ public sealed class FireAuthorityTests : IDisposable Assert.Equal(unaided.Items.GameplaySettings.UnaidedAccuracy, FireControl.HitProbability(unaided.Weapon, unaided.Shooter, unaided.Target), 3); } - // The gate is a gate, not a penalty: an out-of-arc commit consumes exactly zero draws from the shared RNG - // stream. Mutation: roll first and multiply the result by zero -- that still advances the stream by one - // draw, which this test would catch by seeing a different next value than an untouched stream produces. - [Fact] - public void OutOfArcConsumesNoDraw() + // Cut 7 (docs/fire-control-cut.md): this was OutOfArcConsumesNoDraw, which asserted that a shot gated to + // zero left ItemManager.Random untouched. Cut 6b (6.1) moved the roll onto a per-shot local generator, so + // Commit stopped touching that stream on EVERY path and the old test passed for a reason that had nothing + // to do with arcs -- it would have passed just as well with the target dead ahead, and no mutation of the + // short-circuit it named could ever turn it red. Rewritten to pin the rule that is actually live: no + // combat path draws from the shared stream, in arc or out. Mutation: restore the shared-stream read in + // Commit; the in-arc case then goes red. + [Theory] + [InlineData(100f, 0f)] // directly abeam: gated to zero, outside the default arc + [InlineData(0f, 100f)] // dead ahead: a real firing solution that actually rolls + public void CombatNeverDrawsFromTheSharedStream(float x, float z) { - var e = Build(TestSettings()); - // Directly abeam -- outside even the wide 170-degree default arc dead ahead. - e.Target.Position = float3(100, 0, 0); + var e = Build(TestSettings(), accuracy: 1, resolution: 1, spread: 0); + e.Target.Position = float3(x, 0, z); const uint seed = 4242u; var untouched = new Random(seed);