Merge authored design roles: items stop being one-dimensional

32 of 51 designs declare roles, 183 stats point at one, 28 of 37 products
author matching role quality. Adds the validation that refuses a stat
naming a role its design lacks, and roles-migrate alongside the other
catalog tools. Product means are placeholders pending operator review.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-19 05:03:57 +02:00
commit 90e83234ed
7 changed files with 844 additions and 3 deletions

View file

@ -37,6 +37,8 @@ public static class AetheriaStores
StatValidation.ValidateStatModifiers(data.Name, data.Behaviors);
// Cut 6 (docs/stats-and-power-cut.md): a power request may not depend on power supply.
StatValidation.ValidateNoPowerSupplyOnRequest(data.Name, data.Behaviors);
// Cut 7 (docs/stats-and-power-cut.md): a stat naming a role its design lacks is refused.
StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors);
}
// Cut 2 (docs/stats-and-power-cut.md): a consumable's own StatModifierData needs the same check;
// consumables carry no heat response, so this is not folded into the loop above.
@ -44,6 +46,7 @@ public static class AetheriaStores
{
StatValidation.ValidateStatModifiers(data.Name, data.Behaviors);
StatValidation.ValidateNoPowerSupplyOnRequest(data.Name, data.Behaviors);
StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors);
}
return cache;
}
@ -81,11 +84,13 @@ public static class CultRecordRefs
StatValidation.ValidateHeatResponse(data);
StatValidation.ValidateStatModifiers(data.Name, data.Behaviors);
StatValidation.ValidateNoPowerSupplyOnRequest(data.Name, data.Behaviors);
StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors);
}
if (document is ConsumableItemData consumable)
{
StatValidation.ValidateStatModifiers(consumable.Name, consumable.Behaviors);
StatValidation.ValidateNoPowerSupplyOnRequest(consumable.Name, consumable.Behaviors);
StatValidation.ValidateRoleUsage(consumable.Name, consumable.Roles, consumable.Behaviors);
}
return new CultRecordRef<T>(cache.UpsertAsync(document).Result.Key);
}

View file

@ -755,6 +755,34 @@ public static class StatValidation
}
}
// Cut 7 (docs/stats-and-power-cut.md): "a stat naming a role its design lacks" must be refused, not silently
// fall back to the lot's own workmanship (Lot.QualityForRole already falls back for a role a lot never rolled
// -- that is the intended forward-compat path for an old lot meeting a newly-authored role. This is the other
// direction: a StatTerm naming a role the design itself never declared is an authoring mistake, not a lot
// predating the role, and must fail loudly rather than silently reading generic quality). Every PerformanceStat
// field on every behaviour is walked; only StatSource.Quality terms carry a Role at all (Evaluate ignores Role
// for every other source).
public static void ValidateRoleUsage(string ownerName, List<ItemRole> roles, IEnumerable<BehaviorData> behaviors)
{
var declared = new HashSet<string>((roles ?? new List<ItemRole>()).Select(r => r.Name));
foreach (var behavior in behaviors ?? Enumerable.Empty<BehaviorData>())
{
if (behavior == null) continue;
foreach (var field in behavior.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat)))
{
if (!(field.GetValue(behavior) is PerformanceStat stat) || stat.Terms == null) continue;
foreach (var term in stat.Terms)
{
if (term.Source != StatSource.Quality || string.IsNullOrEmpty(term.Role)) continue;
if (!declared.Contains(term.Role))
throw new InvalidOperationException(
$"{ownerName}: {behavior.GetType().Name}.{field.Name} names role \"{term.Role}\", " +
$"which this design does not declare (declared: {(declared.Count == 0 ? "none" : string.Join(", ", declared))})");
}
}
}
}
// Cut 6 (docs/stats-and-power-cut.md): "a stat that decides a power request may not depend on power supply,
// directly or through a modifier chain, and no stat may depend on itself." IPowerConsumer.PowerRequest(dt)
// never hands the bus a number it invented on the spot -- each implementation evaluates exactly one fixed

BIN
GameData/Aetheria.cc (Stored with Git LFS)

Binary file not shown.

View file

@ -0,0 +1,202 @@
# Cut 7 (Roles Authored): Operator Review
Generated by `dotnet run --project tools/AetherDb -- roles-migrate` (dry run captures this exact table; `apply`
landed it in `GameData/Aetheria.cc`). Regenerate with `roles-migrate` any time the catalog changes — this file is
a snapshot for review, not a second source of truth.
Role vocabulary is small and shared within a kind: the same handful of part names cover every design of that
kind, not one bespoke name per item. A stat is only pointed at a role when it both carries a `Quality` term and
actually varies with quality (`Min != Max`) — Cut 1's flat placeholder stats (`Min == Max`, a harmless leftover
`Heat^1` term) have no observable role-vs-workmanship difference, so pointing a role at one would be authoring
fiction, not content.
Product role means below are almost all **generic placeholders** (deterministic per product+role, not hand-tuned)
flagged "needs operator review" — the one exception is Arctica/Alakrita, where `docs/item-provenance-target.md`
already states a brand identity ("optimizing for heat efficiency"). Every other product is waiting on the
operator to decide who is actually good at what; right now they only differ from each other by an arbitrary seed,
not by authored intent.
## Designs and their roles, by item kind
### AetherDrive
| Design | Roles | Stat → role |
|---|---|---|
| Traction | coupling, rotor | `AetherDriveData.MaximumRpm` → rotor · `AetherDriveData.Torque` → rotor · `AetherDriveData.CouplingEfficiency` → coupling · `AetherDriveData.EnergyDraw` → coupling · `AetherDriveData.PassiveCoupling` → coupling |
**Role meanings:** *rotor* — the spinning core that produces RPM and torque. *coupling* — how efficiently that
output couples into drive and how much bleeds off passively.
### CargoBay, ControlModule, DockingBay, Hull/Station, Hull/Turret — no roles
SafeStuff II, Store-All Enterprise Edition, Store-All Plus, Store-All Plus Mini (CargoBay); Cockpit 2x2, Turret
Control Module (ControlModule); Medium Docking Bay (DockingBay); Zenith (Hull/Station); Turret (Hull/Turret).
**Why:** none of these kinds' behaviours read `StatSource.Quality` at all today (cargo capacity, docking, cockpit
draw and hull cross-section on these particular designs are flat or non-quality stats) — there is no per-part
distinction for a role to express yet. Generic quality stays. Turret's own `ReflectorData.CrossSection` is present
but authored flat (`Heat^1`, no `Quality` term), unlike LonginusX's.
### Hull/Ship
| Design | Roles | Stat → role |
|---|---|---|
| LonginusX | plating | `ReflectorData.CrossSection` → plating |
**Role meaning:** *plating* — the hull's armor/stealth coating, which is what actually governs radar cross-section.
### Radiator
| Design | Roles | Stat → role |
|---|---|---|
| Arctica | fins, pump, reservoir | `Emissivity`→fins · `WasteHeat`→fins · `PumpedHeat`→pump · `EnergyUsage`→pump · `ThermalMass`→reservoir |
| cold like my heart | fins, pump, reservoir | same five fields, same roles |
| OK Disperser | fins, pump, reservoir | same five fields, same roles |
| Iapyx | reservoir | `ThermalMass`→reservoir only (Emissivity/PumpedHeat/WasteHeat/EnergyUsage are authored flat, `Heat^1`, no Quality term) |
| Skiron | reservoir | same as Iapyx |
**Role meanings:** *fins* — the radiating surface (emissivity, waste heat). *pump* — the coolant pump (heat moved,
its own energy cost). *reservoir* — the thermal mass of the coolant loop itself.
### Reactor
| Design | Roles | Stat → role |
|---|---|---|
| Core Power | core, regulator | `Efficiency`→core · `OverloadEfficiency`→regulator · `ThrottlingFactor`→regulator (Charge authored flat here) |
| Manhattan | core, regulator | `Charge`→core · `Efficiency`→core · `OverloadEfficiency`→regulator · `ThrottlingFactor`→regulator |
| MoveOnPro | core, regulator | same four |
| Notorious | core, regulator | same four |
| Vulcan | core, regulator | same four |
**Role meanings:** *core* — the primary reaction chamber (raw charge and efficiency). *regulator* — the safety and
throttling electronics (overload behaviour, throttling).
MoveOnPro also carries a `StatModifierData.Modifier` (Quality-termed) — left at generic quality: it modifies an
external stat rather than the reactor's own part, so no reactor role fits it.
### Sensors
| Design | Roles | Stat → role |
|---|---|---|
| not if i see you first | emitter, receiver | `Sensitivity`→receiver · `PingBoost`,`PingEnergy`,`PingVisibility`,`PingRange`,`PingCooldown`→emitter |
| The Bat | emitter, receiver | `Sensitivity`→receiver · `PingBoost`,`PingVisibility`,`PingRange`,`PingCooldown`→emitter (`PingEnergy` authored flat here) |
| Tractor Beam | *(none)* | dead design (S1, Cut 1 findings): every field is flat, nothing to point |
**Role meanings:** *receiver* — passive sensitivity. *emitter* — the active ping subsystem (boost, cost,
visibility, range, cooldown).
### Thruster
| Design | Roles | Stat → role |
|---|---|---|
| deep space burnout | injector, nozzle | `Thrust`→nozzle · `Visibility`→nozzle · `Heat`→injector (`EnergyUsage` authored flat 0/0, no terms) |
| Large Drive | *(none)* | every field authored flat (`Heat^1`/`Quality^1` but `Min == Max` throughout) |
**Role meanings:** *nozzle* — exhaust output and plume (thrust, visibility). *injector* — fuel/power feed, whose
byproduct is heat.
### Tool
Tool is not a shared kind the way a laser or radiator is — each design is its own bespoke gadget, so roles are
authored per design rather than from one shared field map.
| Design | Roles | Stat → role |
|---|---|---|
| Industrial Thermostatic Heater | heating element | `EnergyDrawData.EnergyDraw`→heating element · `HeatData.Heat`→heating element |
| PotaT+- | converter, storage cell | `CapacitorData.Capacity`→storage cell · `CapacitorData.Efficiency`→converter |
| Assembly Line, Deep Ore Extractor, Refinery, Shipyard, Surface Ore Extractor | *(none)* | carry no `PerformanceStat` behaviour at all in the current catalog |
### Weapon/Ballistic
| Design | Roles | Stat → role |
|---|---|---|
| 6k Shooter | barrel, feed mechanism | `Damage`,`Range`,`Velocity`→barrel · `Heat`,`Visibility`,`Spread`→feed mechanism |
| Earp | barrel, feed mechanism | same shape as 6k Shooter |
| ClearPath | barrel, feed mechanism | `Damage`,`Range`,`Velocity`→barrel · `Cooldown`,`Energy`,`Heat`,`Visibility`,`Spread`→feed mechanism |
| DeathCluster | barrel, feed mechanism | same shape as ClearPath |
| pretty pretty bang bang | barrel, feed mechanism | same shape as ClearPath (charged weapon, same field names) |
| Autocannon | *(none)* | dead design (S1, Cut 1 findings): every field flat |
**Role meanings:** *barrel* — the part that decides damage, range and muzzle velocity. *feed mechanism* — cycling:
rate of fire, spread, heat and signature it generates, and (where authored) its energy cost.
### Weapon/Energy
| Design | Roles | Stat → role |
|---|---|---|
| CShot RainbowLite Lazer | focusing array, power coupling | `Damage`,`Range`→focusing array · `Cooldown`,`Energy`,`Heat`,`Visibility`,`Spread`→power coupling |
| ColdFire | focusing array, power coupling | same shape |
| Spectra | focusing array, power coupling | same shape |
| FastBlast+- | focusing array, power coupling | `Damage`,`Range`,`Velocity`→focusing array · `Cooldown`,`Heat`,`Visibility`,`Spread`→power coupling |
| ChargeBlast SG | focusing array, power coupling | `Damage`,`Range`,`Velocity`→focusing array · `ChargeTime`,`ChargeHeat`,`Cooldown`,`Visibility`,`Spread`→power coupling |
| ChargeBlast+- | focusing array, power coupling | same shape as ChargeBlast SG |
| plight | focusing array, power coupling | `Damage`,`Range`→focusing array · `ChargeTime`,`ChargeEnergy`,`ChargeHeat`,`Cooldown`,`Heat`,`Visibility`→power coupling |
**Role meanings:** *focusing array* — the beam optics that decide damage, range and velocity. *power coupling* —
everything about how the weapon draws, stores and discharges energy (including charge-up on charged lasers) and
the heat/signature that produces.
### Weapon/Launcher
| Design | Roles | Stat → role |
|---|---|---|
| GT 3K | guidance system, thruster, warhead | `Damage`,`DamageSpread`→warhead · `LockSpeed`,`SensorImpact`,`LockAngle`,`DirectionImpact`,`Decay`,`Range`,`Cooldown`,`Energy`,`Heat`,`Visibility`→guidance system · `Thrust`,`MissileVelocity`,`Velocity`→thruster |
| pswarm | guidance system, thruster, warhead | `Damage`,`DamageSpread`→warhead · `Cooldown`,`Range`,`Energy`,`Heat`,`Visibility`→guidance system · `Thrust`,`MissileVelocity`,`Velocity`→thruster |
| scorched void policy | guidance system, thruster, warhead | same shape as pswarm |
| LRMM72, SRMM72 | *(none)* | dumbfire volleys authored fully flat: every field `Heat^1`, nothing varies |
**Role meanings:** *warhead* — payload (damage, damage spread, penetration). *guidance system* — the seeker
(lock speed/angle, sensor and direction sensitivity, decay, targeting range, cooldown, its own energy/heat/
signature). *thruster* — the missile's own motor (thrust, flight/missile velocity).
## Product role quality authored
37 products exist; 28 got role-quality entries this pass (the rest sell a design that authored no role, or are
one of the two-missile launchers left flat). All means/deviations are **generic placeholders** except Arctica's
`fins`, and every row below needs an operator pass to become real brand identity rather than an arbitrary seed.
| Product (= design; content pass to split brand vs. design names is separate scope) | Role | Mean | Dev | Basis |
|---|---|---|---|---|
| Arctica | fins | 0.78 | 0.07 | **lore**: Alakrita brands on heat efficiency (`item-provenance-target.md`) |
| Arctica | pump | 0.47 | 0.11 | generic — needs review |
| Arctica | reservoir | 0.53 | 0.14 | generic — needs review |
| cold like my heart | fins, pump, reservoir | 0.54 / 0.74 / 0.73 | 0.17 / 0.17 / 0.09 | generic — needs review |
| OK Disperser | fins, pump, reservoir | 0.61 / 0.57 / 0.59 | 0.14 / 0.10 / 0.18 | generic — needs review |
| Iapyx | reservoir | 0.61 | 0.17 | generic — needs review |
| Skiron | reservoir | 0.64 | 0.16 | generic — needs review |
| Manhattan | core, regulator | 0.48 / 0.63 | 0.08 / 0.12 | generic — needs review |
| MoveOnPro | core, regulator | 0.62 / 0.46 | 0.15 / 0.15 | generic — needs review |
| Notorious | core, regulator | 0.65 / 0.46 | 0.15 / 0.17 | generic — needs review |
| Vulcan | core, regulator | 0.75 / 0.58 | 0.12 / 0.16 | generic — needs review |
| not if i see you first | emitter, receiver | 0.71 / 0.75 | 0.09 / 0.18 | generic — needs review |
| The Bat | emitter, receiver | 0.45 / 0.57 | 0.09 / 0.16 | generic — needs review |
| deep space burnout | injector, nozzle | 0.64 / 0.67 | 0.12 / 0.14 | generic — needs review |
| Traction | coupling, rotor | 0.69 / 0.65 | 0.10 / 0.10 | generic — needs review |
| LonginusX | plating | 0.48 | 0.13 | generic — needs review |
| PotaT+- | converter, storage cell | 0.67 / 0.53 | 0.17 / 0.11 | generic — needs review |
| 6k Shooter | barrel, feed mechanism | 0.59 / 0.46 | 0.14 / 0.14 | generic — needs review |
| ClearPath | barrel, feed mechanism | 0.71 / 0.57 | 0.10 / 0.10 | generic — needs review |
| DeathCluster | barrel, feed mechanism | 0.65 / 0.68 | 0.17 / 0.11 | generic — needs review |
| Earp | barrel, feed mechanism | 0.73 / 0.68 | 0.13 / 0.10 | generic — needs review |
| pretty pretty bang bang | barrel, feed mechanism | 0.51 / 0.63 | 0.10 / 0.09 | generic — needs review |
| CShot RainbowLite Lazer | focusing array, power coupling | 0.71 / 0.54 | 0.16 / 0.11 | generic — needs review |
| ChargeBlast SG | focusing array, power coupling | 0.51 / 0.54 | 0.09 / 0.10 | generic — needs review |
| ChargeBlast+- | focusing array, power coupling | 0.45 / 0.51 | 0.17 / 0.18 | generic — needs review |
| ColdFire | focusing array, power coupling | 0.68 / 0.58 | 0.10 / 0.13 | generic — needs review |
| FastBlast+- | focusing array, power coupling | 0.74 / 0.61 | 0.11 / 0.13 | generic — needs review |
| Spectra | focusing array, power coupling | 0.75 / 0.63 | 0.09 / 0.13 | generic — needs review |
| GT 3K | guidance system, thruster, warhead | 0.69 / 0.63 / 0.58 | 0.15 / 0.17 / 0.16 | generic — needs review |
| scorched void policy | guidance system, thruster, warhead | 0.61 / 0.61 / 0.68 | 0.08 / 0.12 / 0.15 | generic — needs review |
**Not authored (no product sells the design, so nothing to author):** Core Power, Industrial Thermostatic Heater,
pswarm, plight (all previously flagged "no product sells" in the Cut 1 census; still true here).
## O7 — what the operator should actually do with this
Everything above the "generic — needs review" line is mechanically correct (verified: `census`'s new
"(product, role) pairs where a sold, role-bearing design authors no matching spread" check reports 0, and two
products of one design with different means resolve a role-termed stat to different, deterministic values —
`RoleAuthoringTests.TwoProductsOfOneDesignWithDifferentRoleMeansResolveDifferentValues`). What it is *not* is
real market segmentation: every design still has exactly one product, so nothing yet demonstrates "a second
product with a role pumped up." That is next scope, and it needs the operator's judgment on which manufacturer
is good at what — this table is the jumping-off point, not the destination.

View file

@ -0,0 +1,119 @@
using System;
using System.IO;
using System.Linq;
using CultMath;
using GameCult.Caching;
using Xunit;
// Cut 7 (docs/stats-and-power-cut.md): designs declare roles, stats name the role they read, and products author
// per-role quality. Two rules pinned here that StatsReadTheLot (LoadoutTests.cs) and CreateLotFillsRolesFromProductSpread
// (LoadoutTests.cs) do not already cover: a stat naming a role its design lacks is refused at Upsert, and two
// products of one design with different role means resolve to different values through the same stat.
public sealed class RoleAuthoringTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-roles-" + Guid.NewGuid().ToString("N"));
private string Catalog => Path.Combine(_root, "Aetheria.cc");
public RoleAuthoringTests() => Directory.CreateDirectory(_root);
public void Dispose() => Directory.Delete(_root, true);
private GameplaySettings Settings() => new GameplaySettings
{
DefaultEntitySettings = new EntitySettings(),
Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } },
QualityPriceModifier = new ExponentialLerp()
};
// The rule the ruling names directly: "validation already refuses a stat naming a role its design lacks."
// A term reading StatSource.Quality with Role "ghost" on a design that declares no roles at all must not
// reach disk -- silently falling back to Lot.Quality (Lot.QualityForRole's own behaviour for an unmatched
// role) would hide the authoring mistake instead of naming it.
[Fact]
public void UpsertRefusesAStatNamingARoleItsDesignLacks()
{
using var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
var ghost = new GearData
{
Name = "Ghost Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10,
Behaviors =
{
new EnergyDrawData
{
EnergyDraw = new PerformanceStat
{
Min = 0, Max = 1,
Terms = { new StatTerm { Source = StatSource.Quality, Exponent = 1, Role = "ghost" } }
}
}
}
};
var ex = Assert.Throws<InvalidOperationException>(() => cache.Upsert(ghost));
Assert.Contains("ghost", ex.Message);
}
// The positive control for the same rule: a stat naming a role the design DOES declare must not throw --
// otherwise UpsertRefusesAStatNamingARoleItsDesignLacks could be passing because Upsert refuses every
// role-bearing stat, not because it distinguishes declared from undeclared.
[Fact]
public void UpsertAcceptsAStatNamingADeclaredRole()
{
using var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
var lensed = new GearData
{
Name = "Lensed Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10,
Roles = { new ItemRole { Name = "lens" } },
Behaviors =
{
new EnergyDrawData
{
EnergyDraw = new PerformanceStat
{
Min = 0, Max = 1,
Terms = { new StatTerm { Source = StatSource.Quality, Exponent = 1, Role = "lens" } }
}
}
}
};
cache.Upsert(lensed); // must not throw
}
// F4/Cut 7: "a market segment is a second product with a role raised" -- two products of the same design,
// differing only in one role's Mean, must mint lots that resolve a role-termed stat to different values.
// Zero StandardDeviation on both keeps the roll deterministic, so this cannot pass by coincidence.
[Fact]
public void TwoProductsOfOneDesignWithDifferentRoleMeansResolveDifferentValues()
{
using var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
var makerRef = cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" });
var lensGear = cache.Upsert(new GearData
{
Name = "Lensed", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10,
Roles = { new ItemRole { Name = "lens" } }
});
var cheapProduct = cache.Upsert(new FactionProductData
{
Name = "Lensed Economy", Design = new CultRecordRef<CraftedItemData>(lensGear.Key), Manufacturer = makerRef,
Roles = { new ProductRole { Role = "lens", Mean = .3f, StandardDeviation = 0 } }
});
var premiumProduct = cache.Upsert(new FactionProductData
{
Name = "Lensed Premium", Design = new CultRecordRef<CraftedItemData>(lensGear.Key), Manufacturer = makerRef,
Roles = { new ProductRole { Role = "lens", Mean = .9f, StandardDeviation = 0 } }
});
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
var cheapLot = items.CreateLot(cache.GetAll<FactionProductData>().Single(p => p.Name == "Lensed Economy"));
var premiumLot = items.CreateLot(cache.GetAll<FactionProductData>().Single(p => p.Name == "Lensed Premium"));
var cheapInstance = (EquippableItem) items.CreateInstance(cheapLot);
var premiumInstance = (EquippableItem) items.CreateInstance(premiumLot);
var stat = new PerformanceStat { Min = 0, Max = 1, Terms = { new StatTerm { Source = StatSource.Quality, Exponent = 1, Role = "lens" } } };
var cheapValue = items.Evaluate(stat, cheapInstance);
var premiumValue = items.Evaluate(stat, premiumInstance);
Assert.Equal(.3f, cheapValue, 3);
Assert.Equal(.9f, premiumValue, 3);
Assert.NotEqual(cheapValue, premiumValue);
}
}

View file

@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Mutation tests for docs/stats-and-power-cut.md's Cut 7 ("Roles authored") -- this repository's own Cut 8,
following Cut 7's brownout work (mutation_tests_stats_power_cut7.py). This is the content cut: designs declare
roles, stats name the role they read, and products author per-role quality so two products of one design differ
by being good at different parts. Three rules are pinned here:
1. ValidateRoleUsage (ItemData.cs) must refuse a StatSource.Quality term naming a role its design does not
declare -- and must not refuse one naming a role the design DOES declare (two mutations, opposite
directions, so neither "always refuse" nor "never refuse" can pass both).
2. Lot.QualityForRole (Provenance.cs) must resolve the matching RoleFill's own quality, not fall back to the
lot's workmanship quality regardless of role.
3. ItemManager.CreateLot (ItemManager.cs) must roll each role's quality from that product's own ProductRole
mean/deviation, not a fixed default -- so two products of one design with different means mint lots that
resolve a role-termed stat to different values.
A no-op control mutation proves the read/replace/restore path is transparent.
Usage:
python tests/mutation_tests_stats_power_cut8.py --cultlib-root <path-to-CultLib-45c2f40-worktree>
Only touches files under this repository; every mutation is reversed before the script exits, including on
failure.
"""
from __future__ import annotations
import argparse
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
TEST_PROJECT = REPO_ROOT / "tests" / "Aetheria.Shared.Tests"
@dataclass
class Mutation:
rule: str
file: str
anchor: str
mutated: str
test: str
expect: str # "red" (mutant must be killed) or "green" (the no-op control)
MUTATIONS: list[Mutation] = [
# --- No-op control: proves the anchor/replace/restore mechanism is transparent ---
Mutation(
rule="control (no-op round trip)",
file="Assets/Scripts/ServerShared/ItemData.cs",
anchor=" if (!declared.Contains(term.Role))",
mutated=" if (!declared.Contains(term.Role))",
test="RoleAuthoringTests.UpsertRefusesAStatNamingARoleItsDesignLacks",
expect="green",
),
# --- ValidateRoleUsage must actually refuse an undeclared role, not merely appear to. Weakening the check to
# --- "never refuse" is the failure the ruling names directly: "validation already refuses a stat naming a
# --- role its design lacks." ---
Mutation(
rule="ValidateRoleUsage must refuse a StatSource.Quality term naming a role its design does not declare",
file="Assets/Scripts/ServerShared/ItemData.cs",
anchor=" if (!declared.Contains(term.Role))",
mutated=" if (false)",
test="RoleAuthoringTests.UpsertRefusesAStatNamingARoleItsDesignLacks",
expect="red",
),
# --- The opposite direction: a check that refuses every role-bearing stat, declared or not, would also pass
# --- the mutation above. This mutant refuses everything, and must kill the positive control instead. ---
Mutation(
rule="ValidateRoleUsage must not refuse a StatSource.Quality term naming a role the design DOES declare",
file="Assets/Scripts/ServerShared/ItemData.cs",
anchor=" if (!declared.Contains(term.Role))",
mutated=" if (true)",
test="RoleAuthoringTests.UpsertAcceptsAStatNamingADeclaredRole",
expect="red",
),
# --- Lot.QualityForRole must resolve the named role's own RoleFill, not fall back to the lot's workmanship
# --- regardless of which role (or none) a term names. Commenting out the match makes every role read the
# --- same number StatsReadTheLot's "noRole" case reads, collapsing the very distinction Cut 7 exists to buy. ---
Mutation(
rule="QualityForRole must resolve the matching RoleFill, not fall back to workmanship for every role",
file="Assets/Scripts/ServerShared/Provenance.cs",
anchor=" foreach (var fill in Roles)\n if (fill.Role == role) return fill.Quality;",
mutated=" foreach (var fill in Roles)\n if (false) return fill.Quality;",
test="LoadoutTests.StatsReadTheLot",
expect="red",
),
# --- ItemManager.CreateLot must roll each role from that product's own declared mean, not a constant. This
# --- is the mechanism "products author quality, designs author roles" depends on: without it, authoring a
# --- ProductRole spread on a design's role would do nothing at mint time. ---
Mutation(
rule="CreateLot must roll a role's quality from the product's own ProductRole.Mean, not a fixed default",
file="Assets/Scripts/ServerShared/ItemManager.cs",
anchor=" Quality = clamp(Random.NextGaussian(build.Mean, build.StandardDeviation), .01f, 1)",
mutated=" Quality = clamp(Random.NextGaussian(.5f, build.StandardDeviation), .01f, 1)",
test="LoadoutTests.CreateLotFillsRolesFromProductSpread",
expect="red",
),
# --- The same rule, proved the way the operator's market-segmentation ruling states it: two products of one
# --- design with different role means must mint lots that resolve a role-termed stat to different values. ---
Mutation(
rule="Two products of one design with different role means must resolve a role-termed stat differently",
file="Assets/Scripts/ServerShared/ItemManager.cs",
anchor=" Quality = clamp(Random.NextGaussian(build.Mean, build.StandardDeviation), .01f, 1)",
mutated=" Quality = clamp(Random.NextGaussian(.5f, build.StandardDeviation), .01f, 1)",
test="RoleAuthoringTests.TwoProductsOfOneDesignWithDifferentRoleMeansResolveDifferentValues",
expect="red",
),
]
def replace_unique(path: Path, anchor: str, mutated: str) -> None:
original = path.read_text(encoding="utf-8")
count = original.count(anchor)
if count != 1:
raise SystemExit(f"{path}: anchor must occur exactly once, found {count}\n---\n{anchor}")
path.write_text(original.replace(anchor, mutated), encoding="utf-8")
def run_test(cultlib_root: str, test: str) -> tuple[int, str]:
proc = subprocess.run(
["dotnet", "test", str(TEST_PROJECT), f"-p:CultLibRoot={cultlib_root}",
"--filter", f"FullyQualifiedName~{test}"],
capture_output=True, text=True, timeout=300,
)
return proc.returncode, proc.stdout + proc.stderr
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--cultlib-root", required=True)
args = parser.parse_args()
failures: list[str] = []
originals: dict[str, str] = {}
for m in MUTATIONS:
if m.file not in originals:
originals[m.file] = (REPO_ROOT / m.file).read_text(encoding="utf-8")
def restore_all() -> None:
for file, text in originals.items():
(REPO_ROOT / file).write_text(text, encoding="utf-8")
try:
for m in MUTATIONS:
print(f"\n=== {m.rule} (expect {m.expect}) ===")
path = REPO_ROOT / m.file
replace_unique(path, m.anchor, m.mutated)
code, output = run_test(args.cultlib_root, m.test)
passed = "Passed!" in output and code == 0
if m.expect == "green":
if not passed:
failures.append(f"{m.rule}: expected green (test passing), got failure\n{output[-2000:]}")
else:
print(f"OK: {m.test} passed under a no-op mutation, as expected")
else:
if passed:
failures.append(f"{m.rule}: expected red (mutant killed), but {m.test} still passed")
else:
print(f"OK: {m.test} went red under the mutation, as expected")
# Restore this file immediately so the next mutation starts from a clean tree.
path.write_text(originals[m.file], encoding="utf-8")
finally:
restore_all()
if failures:
print("\n=== FAILURES ===")
for f in failures:
print(f"- {f}")
return 1
print("\nAll mutations behaved as declared.")
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -31,8 +31,9 @@ public static class Program
case "settings-dump": return SettingsDump();
case "shield-migrate": return ShieldMigrate(args.Contains("apply"));
case "brownout-migrate": return BrownoutMigrate(args.Contains("apply"));
case "roles-migrate": return RolesMigrate(args.Contains("apply"));
default:
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply], shield-migrate [apply], brownout-migrate [apply]");
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply]");
return 1;
}
}
@ -91,6 +92,29 @@ public static class Program
string.Join(", ", product.Roles.Select(r => $"{r.Role} {r.Mean:0.00}±{r.StandardDeviation:0.00}")));
if (authored.Length == 0) Console.WriteLine(" none yet: add roles to a design, then set each product's means");
// Cut 7 (docs/stats-and-power-cut.md): "adding a role to a shipped design changes nothing for existing
// lots... but a newly minted lot from a product with no spread for that role rolls new ProductRole() --
// mean .5 ... The census is where that is caught, and the two must land together." A design's roles and
// a selling product's role spread can drift independently (a role added after the product was authored,
// or a product added after roles landed), so every sold, role-bearing design is checked against every
// product that actually sells it, not only the ones this run's roles-migrate happened to touch.
var roleGaps = 0;
foreach (var item in items.Where(i => i.Roles != null && i.Roles.Count > 0))
{
var design = db.Cache.RefOf(item).Key;
var sellers = products.Where(p => p.Design.Key.Equals(design)).ToArray();
foreach (var product in sellers)
{
var covered = new HashSet<string>((product.Roles ?? new List<ProductRole>()).Select(r => r.Role));
var missing = item.Roles.Select(r => r.Name).Where(r => !covered.Contains(r)).ToArray();
if (missing.Length == 0) continue;
roleGaps++;
Console.WriteLine($" GAP: {product.Name} sells {item.Name} but authors no spread for: {string.Join(", ", missing)}" +
" -- a newly minted lot rolls the ProductRole default (mean .5) for these, not this maker's own quality");
}
}
Console.WriteLine($"\n{roleGaps} (product, role) pairs where a sold, role-bearing design's product authors no matching spread");
// Brand() picks the first (maker, design) product in record-key order; more than one means the choice is
// arbitrary rather than authored, which the rule until segment bands exist forbids.
var duplicateBrands = products
@ -109,6 +133,287 @@ public static class Program
return 0;
}
// Cut 7 (docs/stats-and-power-cut.md): "products author quality, designs author roles." Zero designs
// declared a role and zero products authored role quality before this command; every field->role table below
// is the one place that content is decided, so the operator reviews a legible table instead of hand-picking
// through 51 catalog records. Field names are matched against the concrete behaviour Type they appear on, not
// by name alone, so "Range" on a launcher's guidance system and "Range" on a mining tool never collide.
//
// A stat is only worth pointing at a role if it actually varies with Quality *and* the value moves (Min !=
// Max) -- Cut 1's flat placeholder stats (min == max, a bare "Heat^1" term the migration used as a harmless
// non-empty Terms list) carry no observable role-vs-workmanship difference, so authoring a role there would
// be authoring fiction. Fields the maps below do not mention keep generic quality; the report says why.
private static readonly Dictionary<string, string> BallisticWeaponRoles = new Dictionary<string, string>
{
["Damage"] = "barrel", ["Range"] = "barrel", ["Velocity"] = "barrel", ["Penetration"] = "barrel",
["Cooldown"] = "feed mechanism", ["Spread"] = "feed mechanism", ["Heat"] = "feed mechanism",
["Visibility"] = "feed mechanism", ["Energy"] = "feed mechanism",
};
private static readonly Dictionary<string, string> EnergyWeaponRoles = new Dictionary<string, string>
{
["Damage"] = "focusing array", ["Range"] = "focusing array", ["Velocity"] = "focusing array",
["Penetration"] = "focusing array",
["Energy"] = "power coupling", ["Heat"] = "power coupling", ["ChargeTime"] = "power coupling",
["ChargeEnergy"] = "power coupling", ["ChargeHeat"] = "power coupling", ["Cooldown"] = "power coupling",
["Spread"] = "power coupling", ["Visibility"] = "power coupling",
};
private static readonly Dictionary<string, string> LauncherRoles = new Dictionary<string, string>
{
["Damage"] = "warhead", ["Penetration"] = "warhead", ["DamageSpread"] = "warhead",
["LockSpeed"] = "guidance system", ["SensorImpact"] = "guidance system", ["LockAngle"] = "guidance system",
["DirectionImpact"] = "guidance system", ["Decay"] = "guidance system", ["Range"] = "guidance system",
["Cooldown"] = "guidance system", ["Spread"] = "guidance system", ["Visibility"] = "guidance system",
["Energy"] = "guidance system", ["Heat"] = "guidance system",
["Thrust"] = "thruster", ["MissileVelocity"] = "thruster", ["Velocity"] = "thruster",
};
private static readonly Dictionary<string, string> RadiatorRoles = new Dictionary<string, string>
{
["Emissivity"] = "fins", ["WasteHeat"] = "fins",
["PumpedHeat"] = "pump", ["EnergyUsage"] = "pump",
["ThermalMass"] = "reservoir",
};
private static readonly Dictionary<string, string> ReactorRoles = new Dictionary<string, string>
{
["Charge"] = "core", ["Efficiency"] = "core",
["OverloadEfficiency"] = "regulator", ["ThrottlingFactor"] = "regulator",
};
private static readonly Dictionary<string, string> SensorRoles = new Dictionary<string, string>
{
["Sensitivity"] = "receiver",
["PingBoost"] = "emitter", ["PingEnergy"] = "emitter", ["PingRange"] = "emitter",
["PingVisibility"] = "emitter", ["PingCooldown"] = "emitter",
};
private static readonly Dictionary<string, string> ThrusterRoles = new Dictionary<string, string>
{
["Thrust"] = "nozzle", ["Visibility"] = "nozzle",
["Heat"] = "injector", ["EnergyUsage"] = "injector",
};
private static readonly Dictionary<string, string> AetherDriveRoles = new Dictionary<string, string>
{
["MaximumRpm"] = "rotor", ["Torque"] = "rotor",
["CouplingEfficiency"] = "coupling", ["PassiveCoupling"] = "coupling", ["EnergyDraw"] = "coupling",
};
private static readonly Dictionary<string, string> HullShipRoles = new Dictionary<string, string>
{
["CrossSection"] = "plating",
};
// Tool designs are not a shared kind the way a laser or a radiator is -- each is its own bespoke gadget, so
// its role map is keyed by design name rather than by behaviour field, same as the census already treats
// "Tool" as a catch-all HardpointType. A design with no entry here carries no field with a natural role
// (Assembly Line, Deep Ore Extractor, Refinery, Shipyard, Surface Ore Extractor carry no PerformanceStat
// behaviour at all in the current catalog).
private static readonly Dictionary<string, Dictionary<string, string>> ToolRolesByDesign =
new Dictionary<string, Dictionary<string, string>>
{
["Industrial Thermostatic Heater"] = new Dictionary<string, string>
{
["EnergyDraw"] = "heating element", ["Heat"] = "heating element",
},
["PotaT+-"] = new Dictionary<string, string>
{
["Capacity"] = "storage cell", ["Efficiency"] = "converter",
},
};
private static string KindOf(EquippableItemData item) =>
item is HullData hull ? $"Hull/{hull.HullType}"
: item is DockingBayData ? "DockingBay"
: item is CargoBayData ? "CargoBay"
: item is WeaponItemData weapon ? $"Weapon/{weapon.HardpointType}"
: item.HardpointType.ToString();
// The field->role map for one design, or null when its kind carries no per-part behaviour stat at all
// (CargoBay, DockingBay, ControlModule, Hull/Station, Hull/Turret -- none of their behaviours read
// StatSource.Quality today, so there is no natural role to author and the report says so per design).
private static Dictionary<string, string> RoleMapFor(EquippableItemData item, string kind) => kind switch
{
"Weapon/Ballistic" => BallisticWeaponRoles,
"Weapon/Energy" => EnergyWeaponRoles,
"Weapon/Launcher" => LauncherRoles,
"Radiator" => RadiatorRoles,
"Reactor" => ReactorRoles,
"Sensors" => SensorRoles,
"Thruster" => ThrusterRoles,
"AetherDrive" => AetherDriveRoles,
_ when kind == "Hull/Ship" => HullShipRoles,
"Tool" => ToolRolesByDesign.TryGetValue(item.Name, out var byName) ? byName : null,
_ => null,
};
private sealed record RoleAuthoring(
EquippableItemData Item, string Kind, List<(string Behavior, string Field, string Role)> StatsAssigned,
List<string> RolesDeclared, string SkipReason);
// The content pass itself: declares roles on designs, points each design's own StatTerm.Role at the role that
// governs it, and authors matching ProductRole quality on every product that sells a now-rolegetting design.
// Dry run unless passed "apply", which alone opens the catalog writable; every record must derive cleanly or
// nothing is written, the same all-or-nothing contract ShieldMigrate and BrownoutMigrate already use. Prints
// the operator review table (grouped by item kind) either way.
private static int RolesMigrate(bool apply)
{
var db = AetherDb.Open(catalogWritable: apply);
var items = db.Cache.GetAll<EquippableItemData>().ToArray();
var products = db.Cache.GetAll<FactionProductData>().ToArray();
var changedDesigns = new List<(object Document, CultRecordKey Key)>();
var changedProducts = new List<(object Document, CultRecordKey Key)>();
var report = new List<RoleAuthoring>();
foreach (var item in items.OrderBy(i => KindOf(i)).ThenBy(i => i.Name, StringComparer.Ordinal))
{
var kind = KindOf(item);
var map = RoleMapFor(item, kind);
if (map == null)
{
report.Add(new RoleAuthoring(item, kind, new List<(string, string, string)>(), new List<string>(),
"kind carries no behaviour reading StatSource.Quality; generic quality stays"));
continue;
}
var rolesUsed = new SortedSet<string>(StringComparer.Ordinal);
var assigned = new List<(string Behavior, string Field, string Role)>();
foreach (var behavior in item.Behaviors ?? new List<BehaviorData>())
{
if (behavior == null) continue;
foreach (var field in behavior.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat)))
{
if (!(field.GetValue(behavior) is PerformanceStat stat) || stat.Terms == null) continue;
if (stat.Min == stat.Max) continue; // flat: no observable role-vs-workmanship difference
var qualityTerm = stat.Terms.FirstOrDefault(t => t.Source == StatSource.Quality);
if (qualityTerm == null || !string.IsNullOrEmpty(qualityTerm.Role)) continue;
if (!map.TryGetValue(field.Name, out var role)) continue;
qualityTerm.Role = role;
rolesUsed.Add(role);
assigned.Add((behavior.GetType().Name, field.Name, role));
}
}
if (rolesUsed.Count == 0)
{
report.Add(new RoleAuthoring(item, kind, assigned, new List<string>(),
"no quality-bearing, non-flat stat matched this kind's role map"));
continue;
}
item.Roles = rolesUsed.Select(r => new ItemRole { Name = r }).ToList();
report.Add(new RoleAuthoring(item, kind, assigned, item.Roles.Select(r => r.Name).ToList(), null));
changedDesigns.Add((item, db.Cache.RefOf(item).Key));
}
// Products author quality for every role their design now declares. A design's Roles may also include
// roles authored on an earlier pass (none exist yet, but the loop is idempotent either way): every sold
// product is checked against the full current Roles list, not just what changed this run.
var productAuthoring = new List<(FactionProductData Product, string Design, List<(string Role, float Mean, float Dev, string Basis)> Added)>();
var byDesign = items.ToDictionary(i => db.Cache.RefOf(i).Key, i => i);
foreach (var product in products.OrderBy(p => p.Name, StringComparer.Ordinal))
{
if (!byDesign.TryGetValue(product.Design.Key, out var design) || design.Roles == null || design.Roles.Count == 0)
continue;
var existing = new HashSet<string>((product.Roles ?? new List<ProductRole>()).Select(r => r.Role));
var added = new List<(string, float, float, string)>();
foreach (var role in design.Roles)
{
if (existing.Contains(role.Name)) continue;
var (mean, dev, basis) = AuthorProductRole(db, product, design.Name, role.Name);
product.Roles.Add(new ProductRole { Role = role.Name, Mean = mean, StandardDeviation = dev });
added.Add((role.Name, mean, dev, basis));
}
if (added.Count == 0) continue;
productAuthoring.Add((product, design.Name, added));
changedProducts.Add((product, db.Cache.RefOf(product).Key));
}
PrintRolesReport(report, productAuthoring);
var totalDesigns = report.Count(r => r.SkipReason == null);
var totalStats = report.Sum(r => r.StatsAssigned.Count);
Console.WriteLine($"\n{totalDesigns} designs authored roles ({report.Count - totalDesigns} left at generic quality), " +
$"{totalStats} stats pointed at a role, {changedProducts.Count} products authored role quality.");
if (changedDesigns.Count == 0 && changedProducts.Count == 0) return 0;
if (!apply)
{
Console.WriteLine($"\nDry run. Pass \"apply\" to land {changedDesigns.Count} design(s) and {changedProducts.Count} product(s).");
return 0;
}
db.Cache.Commit(batch =>
{
foreach (var (document, key) in changedDesigns) batch.Upsert(document.GetType(), document, key);
foreach (var (document, key) in changedProducts) batch.Upsert(document.GetType(), document, key);
});
Console.WriteLine($"Landed {changedDesigns.Count} design(s) and {changedProducts.Count} product(s) in Aetheria.cc");
return 0;
}
// A stable (process-independent) hash: string.GetHashCode() is randomized per process, which would make a dry
// run and the later "apply" run author different numbers for the same product. Deterministic FNV-1a instead.
private static uint StableHash(string s)
{
unchecked
{
var h = 2166136261u;
foreach (var c in s) { h ^= c; h *= 16777619u; }
return h;
}
}
// Alakrita's Arctica is the one product the lore already speaks for (docs/item-provenance-target.md: "Arctica
// is Alakrita branding, by the name I presume they're optimizing for heat efficiency"): its radiating fins get
// a real premium and tight quality control, everything else on it stays near the design-wide default. Every
// other product has no established brand identity yet, so its means and deviations are derived deterministically
// from (product name, role) -- reproducible across a dry run and the later apply, and varied enough that two
// products of one design will not coincide by construction -- and are named as generic in the report rather
// than presented as lore. The operator review (O7) is exactly where a real identity replaces a generic one.
private static (float Mean, float Dev, string Basis) AuthorProductRole(AetherDb db, FactionProductData product, string designName, string role)
{
var maker = db.Cache.Get(product.Manufacturer)?.Name;
if (designName == "Arctica" && maker == "Alakrita" && role == "fins")
return (.78f, .07f, "lore: Alakrita brands on heat efficiency (item-provenance-target.md)");
var hash = StableHash($"{product.Name}|{role}");
var mean = .45f + (hash % 1000) / 1000f * .3f; // [.45, .75)
var dev = .08f + (hash / 1000 % 1000) / 1000f * .1f; // [.08, .18)
return (mean, dev, "generic: no established brand identity, needs operator review");
}
private static void PrintRolesReport(List<RoleAuthoring> report,
List<(FactionProductData Product, string Design, List<(string Role, float Mean, float Dev, string Basis)> Added)> productAuthoring)
{
Console.WriteLine("=== Cut 7: roles authored, by item kind ===");
foreach (var kindGroup in report.GroupBy(r => r.Kind).OrderBy(g => g.Key, StringComparer.Ordinal))
{
Console.WriteLine($"\n-- {kindGroup.Key} --");
foreach (var r in kindGroup.OrderBy(r => r.Item.Name, StringComparer.Ordinal))
{
if (r.SkipReason != null)
{
Console.WriteLine($" {r.Item.Name,-28} (none) -- {r.SkipReason}");
continue;
}
Console.WriteLine($" {r.Item.Name,-28} roles: {string.Join(", ", r.RolesDeclared)}");
foreach (var (behavior, field, role) in r.StatsAssigned)
Console.WriteLine($" {behavior}.{field,-18} -> {role}");
}
}
Console.WriteLine("\n=== Cut 7: product role quality authored ===");
foreach (var (product, design, added) in productAuthoring.OrderBy(p => p.Product.Name, StringComparer.Ordinal))
{
Console.WriteLine($" {product.Name,-28} ({design})");
foreach (var (role, mean, dev, basis) in added)
Console.WriteLine($" {role,-18} mean {mean:0.00} dev {dev:0.00} {basis}");
}
}
private static HashSet<GameCult.Caching.CultRecordKey> SoldDesigns(IEnumerable<FactionProductData> products) =>
new HashSet<GameCult.Caching.CultRecordKey>(products.Select(p => p.Design.Key));