diff --git a/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs b/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs index 4cf999279..44658d332 100644 --- a/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs +++ b/Assets/Scripts/ServerShared/Behaviors/TargetingSystem.cs @@ -22,7 +22,10 @@ public class TargetingSystemData : BehaviorData // The info level (see Entity.EntityInfoGathered) at which sensor state stops limiting hits. Below the // system's own resolution, an otherwise-earned hit still degrades on account of thin sensor data; - // consumed by Cut 3's roll. + // consumed by Cut 3's roll. Higher is better, same as every other stat here: Cut 6c.1 (operator ruling + // 2026-09-19) has FireControl.HitProbability take Resolution's reciprocal to derive the actual info + // ceiling (ceiling = detection + (1 - detection) / Resolution), so authoring a bigger number buys a lower + // ceiling -- less info needed -- rather than the field's own value being read as the ceiling directly. [Inspectable, JsonProperty("resolution"), Key(2), RuntimeInspectable] public PerformanceStat Resolution = new PerformanceStat(); diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 79a4318fd..2d9698b5d 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -147,7 +147,15 @@ public static class FireControl var settings = source.ItemManager.GameplaySettings; var info = source.EntityInfoGathered.TryGetValue(target, out var gathered) ? gathered : 0f; - var pSensor = saturate(unlerp(settings.TargetDetectionInfoThreshold, Resolution(source), info)); + // Cut 6c, 6c.1 (operator ruling 2026-09-19): Resolution stays a benefit -- higher is better -- so the + // formula takes its reciprocal to derive the actual info ceiling instead of reading Resolution as + // that ceiling directly. Resolution 1 (the unaided fallback above) yields a ceiling of 1: needs + // complete information, the floor by construction. A higher Resolution pulls the ceiling down toward + // the detection threshold, needing less info before sensor state stops limiting hits. The max guards + // a zero or negative authored Resolution; no authored value should ever reach it. + var demandCeiling = settings.TargetDetectionInfoThreshold + + (1f - settings.TargetDetectionInfoThreshold) / max(Resolution(source), 1e-3f); + var pSensor = saturate(unlerp(settings.TargetDetectionInfoThreshold, demandCeiling, info)); float pSpread; if (weapon.Spread > 0) diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index 242854d20..11e277f7f 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -263,20 +263,35 @@ public class LoadoutGenerator // fire is a last resort, not an alternative loadout choice. EquipHardpoints runs before FillInterior // (OutfitEntity), so entity.Weapons is already populated here. Zenith and anything else with no // weapon hardpoints gets none. + // + // Cut 6c, 6c.2: this used to be `required: true` and throw InvalidLoadoutException when no seller was + // available -- a galaxy that happened not to draw a targeting design's manufacturer failed entity + // generation outright, a single point of failure the ten-seed smoke never sampled. It degrades instead: + // required: false, so RandomProducts' own manufacturer-widening fallback never fires and an unmet + // requirement returns null quietly rather than searching outside the galaxy for one. An entity that + // ends up with no targeting system fires through FireControl's unaided fallback + // (GameplaySettings.UnaidedTracking, Cut 5.1) rather than not firing at all -- that floor is what makes + // this degrade safe. The gap is logged so it surfaces as content debt (AetherDb loadout reports it per + // seed) instead of vanishing silently. if (entity.Weapons.Any()) { emptyShape = entity.UnoccupiedSpace; var (targetingProduct, targetingData) = RandomProduct(2, item => item.Behaviors.Any(b => b is TargetingSystemData) && - item.Shape.FitsWithin(emptyShape, out _, out _), required: true); - if (targetingData == null) throw new InvalidLoadoutException("No compatible targeting system found for entity!"); - - targetingData.Shape.FitsWithin(emptyShape, out var targetingRotation, out var targetingPosition); - var targetingSystem = ItemManager.CreateInstance(targetingProduct) as EquippableItem; - targetingSystem.Rotation = targetingRotation; - if (!entity.TryEquip(targetingSystem, targetingPosition)) - throw new InvalidLoadoutException("Failed to equip selected targeting system!"); + item.Shape.FitsWithin(emptyShape, out _, out _)); + if (targetingData == null) + { + ItemManager.Log("No targeting system available for armed entity; it will fire unaided."); + } + else + { + targetingData.Shape.FitsWithin(emptyShape, out var targetingRotation, out var targetingPosition); + var targetingSystem = ItemManager.CreateInstance(targetingProduct) as EquippableItem; + targetingSystem.Rotation = targetingRotation; + if (!entity.TryEquip(targetingSystem, targetingPosition)) + throw new InvalidLoadoutException("Failed to equip selected targeting system!"); + } } } diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 31f9c139a..d9cd1bedf 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7974aa48cd0dd2aafb9fa3bb4b03377d4be5315bc94307ef1d77a192cdb03e38 -size 12689974 +oid sha256:566407075ba92e82e1e1cd3c2658656ac7710c265e1a3577d569e94feed30b44 +size 12691318 diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs new file mode 100644 index 000000000..2bd717924 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs @@ -0,0 +1,277 @@ +/* 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 CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; +using float3 = CultMath.float3; +using int2 = CultMath.int2; +using Random = CultMath.Random; + +// Cut 6c (docs/fire-control-cut.md, "the formula gets fixed, and the single point of failure"): pins 6c.1 +// (Resolution is a benefit, not a cost -- HitProbability takes its reciprocal) and 6c.2 (a galaxy with no +// seller of a required targeting design degrades the loadout instead of throwing). Builds its own fixtures, +// the same convention every earlier cut's test file establishes. +public sealed class FireControlCut6cTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrolcut6c-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public FireControlCut6cTests() => Directory.CreateDirectory(_root); + + private readonly List _openCaches = new List(); + + public void Dispose() + { + foreach (var c in _openCaches) c.Dispose(); + Directory.Delete(_root, true); + } + + 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 = .2f, + TargetGearInfoThreshold = .8f, + FiringArc = 170, + CommitHorizon = .5f, + SchematicCellSize = 1f, + UnaidedAccuracy = .05f, + UnaidedTracking = 10f, + AgentMinHitProbability = 0f, + BeamResolveInterval = .1f + }; + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + private static Shape SolidShape(int w, int h) + { + var shape = new Shape(w, h); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + // ---- 6c.1: a shooter/target engagement, resolution-parameterised, the same shape FireAuthorityTests' + // and FireControlCut5Tests' own Build helpers use. ---- + + private sealed class Engagement + { + public ItemManager Items; + public Zone Zone; + public Ship Shooter; + public Ship Target; + public EquippedItem WeaponItem; + public InstantWeapon Weapon; + } + + private Engagement Build(GameplaySettings settings, float resolution, float targetRange = 100, float range = 200) + { + var hullShape = SolidShape(5, 5); + 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(10), Range = Constant(range), 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(1f), Resolution = Constant(resolution), Precision = Constant(0f), Tracking = Constant(1000f) + } } + }); + cache.FlushAsync().Wait(); + + var ledger = new ProvenanceLedger(); + ledger.Lots[1] = new Lot { Origin = new Attributed(), Quality = 1 }; + ledger.Lots[2] = new Lot { Origin = new Attributed(), Quality = 1 }; + ledger.Lots[3] = new Lot { Origin = new Attributed(), Quality = 1 }; + ledger.Lots[4] = new Lot { Origin = new Attributed(), Quality = 1 }; + for (var i = 5; i <= 12; 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(e => e.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 = 9 }; + Assert.True(target.TryEquip(targetGun, new int2(0, 0))); + + zone.Entities.Add(shooter); + zone.Entities.Add(target); + shooter.Activate(); + target.Activate(); + + shooter.Position = float3.zero; + target.Position = float3(0, 0, targetRange); + shooter.Target.Value = target; + shooter.SetIff(target, true); + + zone.Update(0f); // warm-up: resolves the targeting system's stats before HitProbability reads them + + return new Engagement { Items = items, Zone = zone, Shooter = shooter, Target = target, WeaponItem = weaponItem, Weapon = weapon }; + } + + // 6c.1 (operator ruling 2026-09-19): Resolution is a benefit -- higher stays better -- so two identical + // engagements differing only in Resolution must have the HIGHER-Resolution one score the higher (or + // equal, at saturation) HitProbability at every info level between detection and full, strictly higher + // at a level where neither has yet saturated. Mutation: read Resolution as the ceiling directly instead + // of taking its reciprocal (the shipped Cut 6a behaviour) -- that inverts the relationship, so the low- + // Resolution engagement scores higher and this test goes red. + [Fact] + public void HigherResolutionYieldsHigherOrEqualHitProbability() + { + var settings = TestSettings(); + var low = Build(settings, resolution: 2f); + var high = Build(settings, resolution: 4f); + + foreach (var info in new[] { .15f, .2f, .3f, .5f, .75f, .99f }) + { + low.Shooter.EntityInfoGathered[low.Target] = info; + high.Shooter.EntityInfoGathered[high.Target] = info; + var pLow = FireControl.HitProbability(low.Weapon, low.Shooter, low.Target); + var pHigh = FireControl.HitProbability(high.Weapon, high.Shooter, high.Target); + Assert.True(pHigh >= pLow - 1e-5f, $"at info {info}: expected higher Resolution (4) to score >= lower Resolution (2), got pHigh={pHigh} pLow={pLow}"); + } + + // Neither design is saturated at info .3 (ceilings are .55 and .325 respectively, per the spec's own + // worked numbers), so the higher-Resolution engagement must be strictly ahead here. + low.Shooter.EntityInfoGathered[low.Target] = .3f; + high.Shooter.EntityInfoGathered[high.Target] = .3f; + var pLowMid = FireControl.HitProbability(low.Weapon, low.Shooter, low.Target); + var pHighMid = FireControl.HitProbability(high.Weapon, high.Shooter, high.Target); + Assert.True(pHighMid > pLowMid, $"expected strictly higher at info .3, got pHigh={pHighMid} pLow={pLowMid}"); + } + + // 6c.2: a galaxy that contains no seller of the one targeting design in the catalog still generates an + // armed loadout instead of throwing InvalidLoadoutException, and the resulting entity resolves the + // unaided fallback (Cut 5.1's floor), not a targeting system it was never able to equip. + // Mutation: restore `required: true` on the targeting-system RandomProduct call in + // LoadoutGenerator.FillInterior (the shipped Cut 6a behaviour) -- that throws instead of degrading. + [Fact] + public void NoSellerDegradesToUnaidedInsteadOfThrowing() + { + string Run() => Path.Combine(_root, "run.cc"); + string Player() => Path.Combine(_root, "player.cc"); + + CultRecordRef maker, targetingMaker; + using (var seedCache = AetheriaStores.Open(Catalog, catalogWritable: true)) + { + seedCache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + maker = seedCache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" }); + targetingMaker = seedCache.Upsert(new Faction { Name = "Targeting Maker", ShortName = "TGM" }); + + var hullShape = SolidShape(5, 5); + var hull = seedCache.Upsert(new HullData + { + Name = "Armed", HullType = HullType.Ship, Shape = hullShape, Price = 100, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } } + }); + var gun = seedCache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, Behaviors = { new InstantWeaponData() } }); + var cargo = seedCache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = new Shape(), Price = 5 }); + var capacitor = seedCache.Upsert(new GearData { Name = "Cap", Hardpoint = HardpointType.Tool, Shape = new Shape(), Price = 1, Behaviors = { new CapacitorData() } }); + var targeting = seedCache.Upsert(new GearData { Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Price = 1, Behaviors = { new TargetingSystemData() } }); + + // Everything but the targeting system is sold by Maker, who IS in the galaxy. Targeting is sold + // only by Targeting Maker, who is NOT -- the single point of failure 6c.2 fixes. + foreach (var (name, design, factionMaker) in new[] + { + ("Armed by Maker", hull.Key, maker), ("Gun by Maker", gun.Key, maker), + ("Crate by Maker", cargo.Key, maker), ("Cap by Maker", capacitor.Key, maker), + ("Targeting by Targeting Maker", targeting.Key, targetingMaker) + }) + seedCache.Upsert(new FactionProductData { Name = name, Design = new CultRecordRef(design), Manufacturer = factionMaker }); + seedCache.FlushAsync().Wait(); + } + + // RunSave.Commit needs a run store to write SavedGame/SavedZone into (a catalog-only cache is "home" + // to neither), the same three-store shape AetheriaStores.Open(Catalog, Run, Player) gives the game + // in every build (RunSaveTests.Open). + var cache = AetheriaStores.Open(Catalog, Run(), Player()); + _openCaches.Add(cache); + + // A minimal one-zone galaxy whose faction roster excludes Targeting Maker entirely, the same + // SavedGame/Galaxy round trip RunSaveTests uses to build a real Galaxy without standing up full + // procedural generation. + var game = new SavedGame + { + Factions = new[] { maker }, + Relationships = new[] { FactionRelationship.Neutral }, + HomeZones = new Dictionary { { 0, 0 } }, + BossZones = new Dictionary(), + DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], + Exit = -1 + }; + var zones = new[] + { + new SavedZone { Name = "Zone 0", Position = float2(0, 0), AdjacentZones = Array.Empty(), Factions = new[] { 0 }, Owner = 0, Contents = null } + }; + RunSave.Commit(cache, game, zones, new ProvenanceLedger()); + var galaxy = new Galaxy(cache, cache.GetGlobal(), _ => { }); + Assert.False(galaxy.ContainsFaction(targetingMaker)); + + var random = new Random(1u); + var settings = TestSettings(); + var log = new List(); + var items = new ItemManager(cache, new ProvenanceLedger(), settings, log.Add); + var generator = new LoadoutGenerator(ref random, items, galaxy, null, null, .5f); + + var pack = generator.GenerateShipLoadout(candidate => candidate.Name == "Armed"); + + Assert.NotNull(pack); // must not have thrown InvalidLoadoutException + Assert.DoesNotContain(pack.Equipment, e => (cache.Get(e.item.Data) as GearData)?.Behaviors.Any(b => b is TargetingSystemData) ?? false); + Assert.Contains(log, l => l.Contains("targeting", StringComparison.OrdinalIgnoreCase)); + + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test", Owner = null }, null); + var entity = EntitySerializer.Unpack(items, zone, pack); + zone.Entities.Add(entity); + entity.Activate(); + zone.Update(0f); + + Assert.Null(entity.GetBehavior()); + Assert.Equal(settings.UnaidedAccuracy, FireControl.Accuracy(entity), 4); + Assert.Equal(settings.UnaidedTracking, FireControl.Tracking(entity), 4); + } +} diff --git a/tests/mutation_tests_fire_control_cut6c.sh b/tests/mutation_tests_fire_control_cut6c.sh new file mode 100644 index 000000000..2caeb8aa8 --- /dev/null +++ b/tests/mutation_tests_fire_control_cut6c.sh @@ -0,0 +1,237 @@ +#!/usr/bin/env bash +# Mutation tests for docs/fire-control-cut.md's Cut 6c ("the formula gets fixed, and the single point of +# failure"). +# +# Two mutations, each against tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs: +# +# 1. 6c.1 HigherResolutionYieldsHigherOrEqualHitProbability -- FireControl.cs's HitProbability reads +# Resolution as the sensor ceiling directly again (the shipped Cut 6a behaviour), instead of taking its +# reciprocal. That inverts the direction the operator ruling fixed: a higher-Resolution design would +# score lower than a cheaper one at low info, the exact defect 6c.1 exists to kill. +# 2. 6c.2 NoSellerDegradesToUnaidedInsteadOfThrowing -- LoadoutGenerator.FillInterior's targeting-system +# RandomProduct call goes back to `required: true` and the null case throws InvalidLoadoutException +# again, instead of degrading to an unaided entity and logging the gap. +# +# 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. +# +# Usage: +# tests/mutation_tests_fire_control_cut6c.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" +LOADOUT_GENERATOR_CS="$REPO_ROOT/Assets/Scripts/ServerShared/LoadoutGenerator.cs" + +# --- byte-exact backup/restore: preserves line endings exactly, no text-mode translation. Same convention +# Cut 5's harness established (5b.3): a restore that is not verified is a restore that can lie. --- +declare -A ORIGINALS +declare -A ORIGINAL_HASH +FILES=("$FIRE_CONTROL_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 FILE -- restores one file from its recorded backup, then re-hashes it and aborts the +# whole script (not just this mutation) if the restore did not reproduce the pre-mutation hash exactly. +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 -- re-hashes every target file against its pre-mutation baseline and prints an explicit +# PASS/FAIL verdict. Called once explicitly at the bottom of a normal run, and again from the EXIT/INT/TERM +# trap as the safety net for every abnormal exit. (A SIGKILL of the whole process group is the one +# termination this cannot see at all -- that gap is closed by re-checking independently after the fact.) +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" +} + +# A dedicated, isolated artifacts path -- see Cut 5's harness for why (stale prebuilt CultLib assemblies from +# an unrelated earlier session's default-path build produced one observed spurious control failure). +ARTIFACTS_PATH="$(mktemp -d)" + +# run_test TEST_FQN -> 0 (passed) or 1 (failed/errored) +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 NAME FILE ANCHOR MUTATED TEST EXPECT("red"|"green") +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" # restore this file immediately, before judging, so a crash still leaves a clean tree + + 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: a byte-identical round trip through this script's own replace_unique path, proving the +# anchor/replace/restore mechanism is transparent before any real mutation is trusted. --- +check_mutation \ + "control (no-op round trip)" \ + "$FIRE_CONTROL_CS" \ + 'var pSensor = saturate(unlerp(settings.TargetDetectionInfoThreshold, demandCeiling, info));' \ + 'var pSensor = saturate(unlerp(settings.TargetDetectionInfoThreshold, demandCeiling, info));' \ + "FireControlCut6cTests.HigherResolutionYieldsHigherOrEqualHitProbability" \ + "green" + +# --- 6c.1: Resolution is a benefit, so HitProbability must take its reciprocal to derive the sensor ceiling, +# not read Resolution as that ceiling directly. Mutation: restore the shipped Cut 6a reading. --- +check_mutation \ + "6c.1 HitProbability must take Resolution's reciprocal, not read it as the ceiling directly" \ + "$FIRE_CONTROL_CS" \ + $' var demandCeiling = settings.TargetDetectionInfoThreshold +\r\n (1f - settings.TargetDetectionInfoThreshold) / max(Resolution(source), 1e-3f);\r\n var pSensor = saturate(unlerp(settings.TargetDetectionInfoThreshold, demandCeiling, info));' \ + ' var pSensor = saturate(unlerp(settings.TargetDetectionInfoThreshold, Resolution(source), info));' \ + "FireControlCut6cTests.HigherResolutionYieldsHigherOrEqualHitProbability" \ + "red" + +# --- 6c.2: a galaxy with no available targeting-system seller must degrade the loadout, not throw. Mutation: +# restore `required: true` on the RandomProduct call and the InvalidLoadoutException throw. --- +check_mutation \ + "6c.2 FillInterior must degrade to unaided fire on no targeting seller, not throw" \ + "$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 _));\r\n if (targetingData == null)\r\n {\r\n ItemManager.Log("No targeting system available for armed entity; it will fire unaided.");\r\n }\r\n else\r\n {' \ + $' var (targetingProduct, targetingData) = RandomProduct(2, item =>\r\n item.Behaviors.Any(b => b is TargetingSystemData) &&\r\n item.Shape.FitsWithin(emptyShape, out _, out _), required: true);\r\n if (targetingData == null)\r\n {\r\n throw new InvalidLoadoutException("No compatible targeting system found for entity!");\r\n }\r\n else\r\n {' \ + "FireControlCut6cTests.NoSellerDegradesToUnaidedInsteadOfThrowing" \ + "red" + +echo "" +verify_tree_clean # explicit call: the tree-clean verdict is part of THIS run's own summary, not only + # something printed later at exit (the trap's own call is a no-op after this one runs -- + # see TREE_VERDICT_DONE above -- and remains the safety net for an interrupted run). + +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/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 1cd7d3b21..f0d22306a 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -23,7 +23,7 @@ public static class Program case "census": return Census(); case "station-fit": return StationFit(); case "hardpoint-fit": return HardpointFit(); - case "loadout": return Loadout(args.Skip(1).FirstOrDefault()); + case "loadout": return Loadout(args.Skip(1).ToArray()); case "save": return Save(); case "factions": return Factions(); case "dangling": return Dangling(args.Skip(1).ToArray()); @@ -34,8 +34,9 @@ public static class Program case "roles-migrate": return RolesMigrate(args.Contains("apply")); case "firing-arc-migrate": return FiringArcMigrate(args.Contains("apply")); case "targeting-catalog": return TargetingCatalog(args.Contains("apply")); + case "targeting-catalog-6c": return TargetingCatalog6c(args.Contains("apply")); default: - Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [apply]"); return 1; } } @@ -742,26 +743,75 @@ public static class Program } // Runs the real LoadoutGenerator against every hull, so a generation failure reproduces here instead of on a - // flight to a populated sector. No galaxy, so this covers placement, roles and products but NOT availability - // filtering or distance weighting, which need a real galaxy. Seeded: a failure repeats. - private static int Loadout(string seedArgument) + // flight to a populated sector. No galaxy by default, so this covers placement, roles and products but NOT + // availability filtering or distance weighting, which need a real galaxy. Seeded: a failure repeats. + // + // Cut 6c, 6c.2 verification: "exclude-sellers Short1,Short2,..." builds a minimal one-zone Galaxy (the same + // SavedGame/Galaxy round trip FireControlCut6cTests uses) whose faction roster is every catalog faction + // EXCEPT the named ones, so IsAvailable actually rejects their products instead of the null-Galaxy "every + // product is on offer" shortcut this command otherwise takes. That is the one way to reproduce the single + // point of failure 6c.2 fixed: a null-galaxy run can never exercise Galaxy.ContainsFaction at all. + private static int Loadout(string[] args) { - var db = AetherDb.Open(); + var seedArgument = args.FirstOrDefault(a => !a.StartsWith("exclude-sellers")); + var excludeArg = args.FirstOrDefault(a => a.StartsWith("exclude-sellers")); var seed = uint.TryParse(seedArgument, out var parsed) ? parsed : 1u; + var db = AetherDb.Open(); 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() }; + + Galaxy galaxy = null; + CultCache galaxyCache = null; + if (excludeArg != null) + { + var excludedShortNames = excludeArg.Contains(':') + ? excludeArg.Substring(excludeArg.IndexOf(':') + 1).Split(',', StringSplitOptions.RemoveEmptyEntries) + : Array.Empty(); + var excluded = new HashSet(excludedShortNames); + + // A second, scratch-run-store cache over the SAME catalog file, read-only on the catalog side -- + // RunSave.Commit only ever touches run-store record types (SavedGame, SavedZone, ProvenanceLedger), + // but it needs a store that is "home" to them, which the plain read-only db.Cache above is not. + // The scratch run.cc lives in the OS temp directory, never under GameData, so this command cannot + // leave behind or corrupt a real save. Factions are looked up through THIS cache instance, not + // db.Cache -- CultCache.RefOf needs the document to be one this specific instance's identity map + // tracks, and two Open() calls over the same file do not share object identity. + var scratchRun = Path.Combine(Path.GetTempPath(), $"aetherdb-loadout-exclude-{Guid.NewGuid():N}.cc"); + galaxyCache = AetheriaStores.Open(Path.Combine(db.Root, "GameData", "Aetheria.cc"), runPath: scratchRun); + var includedFactions = galaxyCache.GetAll().Where(f => !excluded.Contains(f.ShortName)).ToArray(); + Console.WriteLine($"Excluding sellers [{string.Join(", ", excluded)}] -- galaxy carries {includedFactions.Length} of {galaxyCache.GetAll().Count()} factions.\n"); + + var game = new SavedGame + { + Factions = includedFactions.Select(f => galaxyCache.RefOf(f)).ToArray(), + Relationships = includedFactions.Select(_ => FactionRelationship.Neutral).ToArray(), + HomeZones = new Dictionary { { 0, 0 } }, + BossZones = new Dictionary(), + DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], + Exit = -1 + }; + var zones = new[] + { + new SavedZone { Name = "Zone 0", Position = new float2(0, 0), AdjacentZones = Array.Empty(), Factions = new[] { 0 }, Owner = 0, Contents = null } + }; + RunSave.Commit(galaxyCache, game, zones, new ProvenanceLedger()); + galaxy = new Galaxy(galaxyCache, galaxyCache.GetGlobal(), _ => { }); + } + var log = new List(); var itemManager = new ItemManager(db.Cache, new ProvenanceLedger(), settings, log.Add); var failures = 0; + var targetingGaps = 0; foreach (var hull in db.Cache.GetAll().OrderBy(h => h.HullType).ThenBy(h => h.Name)) { var random = new Random(seed); - var generator = new LoadoutGenerator(ref random, itemManager, null, null, null, .5f); + var generator = new LoadoutGenerator(ref random, itemManager, galaxy, null, null, .5f); log.Clear(); string outcome; try @@ -774,6 +824,7 @@ public static class Program }; outcome = pack == null ? "NO LOADOUT (nothing suitable found)" : "ok"; if (pack == null) failures++; + if (pack != null && log.Any(l => l.Contains("targeting system available", StringComparison.OrdinalIgnoreCase))) targetingGaps++; } catch (Exception e) { @@ -785,7 +836,8 @@ public static class Program foreach (var line in log.Distinct()) Console.WriteLine($" {line}"); } - Console.WriteLine($"\n{failures} hulls failed to generate a loadout (seed {seed})"); + Console.WriteLine($"\n{failures} hulls failed to generate a loadout (seed {seed}), {targetingGaps} armed hulls generated with no targeting system (fired unaided)"); + galaxyCache?.Dispose(); return failures; } @@ -1234,4 +1286,114 @@ public static class Program Console.WriteLine($"\nLanded {newDesigns.Length} new designs and {newDesigns.Length + existingDesigns.Length} new products in Aetheria.cc"); return 0; } + + // Fire control Cut 6c (docs/fire-control-cut.md, "the formula gets fixed, and the single point of + // failure"). Two parts: + // + // 6c.1 (operator ruling 2026-09-19): FireControl.HitProbability now takes Resolution's reciprocal to + // derive the sensor-limiting info ceiling, so a bigger authored number is a bigger benefit, matching + // every other stat on this behaviour. Cut 6a's two designs were authored against the old (ceiling-read- + // directly) reading -- Targeting Computer at .3, Fire Control Array at .75 -- which is why the premium + // design scored strictly worse at low info. Re-authored on the new scale: 1-cell 2 (ceiling + // .1 + .9/2 = .55), 2-cell 4 (ceiling .1 + .9/4 = .325). Both clear the unaided ceiling of 1 by a wide + // margin (lower is better under the new reading), and the 2-cell design is unambiguously ahead of the + // 1-cell one at every info level, which was the whole point of the fix. + // + // 6c.2: NiteLife Energy was the only seller of both designs -- "at least the manufacturers that sell the + // capacitor" (Cut 2's letter) rather than the thematic sellers the roster actually names for targeting + // hardware (Cut 2's intent). Finch Cybernetics (passive sensors) and Lucent Media (active sensors, lasers) + // both get a product per design, so a galaxy that does not draw NiteLife still has two other chances to + // sell one. Brand names and flavour text are each manufacturer's own; the design stays dry and carries no + // manufacturer field (standing text policy). Role coverage matches the designs' own already-declared Roles + // (processor, array), same convention TargetingCatalog's newDesigns used above. + // + // Dry run unless passed "apply", same contract as the other *-migrate commands. + private static int TargetingCatalog6c(bool apply) + { + var db = AetherDb.Open(catalogWritable: apply); + + Faction FactionByShortName(string shortName) + { + var faction = db.Cache.GetAll().FirstOrDefault(f => f.ShortName == shortName); + if (faction == null) throw new InvalidOperationException($"No faction with short name \"{shortName}\"."); + return faction; + } + + GearData DesignByName(string name) + { + var design = db.Cache.GetAll().FirstOrDefault(i => i.Name == name); + if (design == null) throw new InvalidOperationException($"No design named \"{name}\"."); + return design; + } + + var targetingComputer = DesignByName("Targeting Computer"); + var fireControlArray = DesignByName("Fire Control Array"); + + var resolutionChanges = new (GearData Design, float OldResolution, float NewResolution)[] + { + (targetingComputer, targetingComputer.Behaviors.OfType().Single().Resolution.Max, 2f), + (fireControlArray, fireControlArray.Behaviors.OfType().Single().Resolution.Max, 4f), + }; + + var newProducts = new (GearData Design, string ProductName, Faction Maker, string ProductDescription, (string Role, float Mean, float Dev)[] Roles)[] + { + (targetingComputer, "Panopticon", FactionByShortName("Finch"), + "Sees everything, judges nothing. Well, mostly nothing. (new text)", + new[] { ("processor", .5f, .13f), ("array", .58f, .12f) }), + (fireControlArray, "Panopticon Prime", FactionByShortName("Finch"), + "The upgrade nobody at Finch will admit they needed until they had it. (new text)", + new[] { ("processor", .68f, .11f), ("array", .75f, .10f) }), + (targetingComputer, "ClapBack", FactionByShortName("Lucent"), + "Your target won't clock it until the killcam. (new text)", + new[] { ("processor", .6f, .16f), ("array", .48f, .15f) }), + (fireControlArray, "ClapBack Ultra", FactionByShortName("Lucent"), + "Now with main-character energy built in. (new text)", + new[] { ("processor", .78f, .14f), ("array", .65f, .13f) }), + }; + + Console.WriteLine("Resolution re-authored to the reciprocal-reading scale (6c.1):"); + foreach (var (design, oldResolution, newResolution) in resolutionChanges) + Console.WriteLine($" {design.Name,-20} {oldResolution,6:0.##} -> {newResolution,4:0.##}"); + + Console.WriteLine("\nNew products (6c.2, thematic sellers alongside NiteLife):"); + foreach (var (design, productName, maker, _, roles) in newProducts) + Console.WriteLine($" {design.Name} -> \"{productName}\" by {maker.ShortName}, roles [{string.Join(", ", roles.Select(r => r.Role))}]"); + + if (!apply) + { + Console.WriteLine($"\nDry run. Pass \"apply\" to land {resolutionChanges.Length} Resolution changes and {newProducts.Length} new products."); + return 0; + } + + foreach (var (design, _, newResolution) in resolutionChanges) + { + var behavior = design.Behaviors.OfType().Single(); + behavior.Resolution = new PerformanceStat { Min = newResolution, Max = newResolution, Terms = new List() }; + } + + // Validate before staging, same contract as ShieldMigrate/TargetingCatalog above. + foreach (var (design, _, _) in resolutionChanges) CultRecordRefs.Validate(design); + + db.Cache.Commit(batch => + { + foreach (var (design, _, _) in resolutionChanges) + batch.Upsert(typeof(GearData), design, db.Cache.RefOf(design).Key); + + foreach (var (design, productName, maker, description, roles) in newProducts) + { + var product = new FactionProductData + { + Name = productName, + Description = description, + Design = new CultRecordRef(db.Cache.RefOf(design).Key), + Manufacturer = db.Cache.RefOf(maker), + Roles = roles.Select(r => new ProductRole { Role = r.Role, Mean = r.Mean, StandardDeviation = r.Dev }).ToList(), + }; + batch.Upsert(typeof(FactionProductData), product); + } + }); + + Console.WriteLine($"\nLanded {resolutionChanges.Length} Resolution changes and {newProducts.Length} new products in Aetheria.cc"); + return 0; + } }