A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Add an isolated typed project catalogue (Refs #1700) (#1963)
Eyal Golan5d1b54abf07d
diff --git a/changelog.d/1700-project-catalogue.md b/changelog.d/1700-project-catalogue.mdnew file mode 100644index 000000000..0c9d5cf4e--- /dev/null+++ b/changelog.d/1700-project-catalogue.md@@ -0,0 +1 @@+- Add a typed GDD 0.3 catalogue view for settled city project costs, work, effects and upkeep, isolated from gameplay.diff --git a/sim/Statecraft.Sim.Tests/Gdd03ProjectCatalogueTests.cs b/sim/Statecraft.Sim.Tests/Gdd03ProjectCatalogueTests.csnew file mode 100644index 000000000..c31c2b83f--- /dev/null+++ b/sim/Statecraft.Sim.Tests/Gdd03ProjectCatalogueTests.cs@@ -0,0 +1,195 @@+using System.Globalization;+using Statecraft.Sim;++// R-PROJ-001, R-PROJ-002, R-PROJ-003: detached catalogue contract only.+// Synthetic tests for the detached project catalogue contract.+public class Gdd03ProjectCatalogueTests+{+ static Content Input(string identity = SaveGame.Gdd03Ruleset)+ {+ var content = ContentLoader.Load(RealContentTests.ContentRoot());+ // Synthetic identity selection only; no scenario, region or facility binding.+ content.Eras = new() { new Era { Systems = new EraSystems { Loop = EraSystems.Gdd, Ruleset = identity } } };+ return content;+ }++ [Theory]+ [InlineData("he-IL")]+ [InlineData("en-US")]+ public void SettledDescriptorsRetainExactValuesAndProvenance(string locale)+ {+ var previous = CultureInfo.CurrentCulture;+ var previousUi = CultureInfo.CurrentUICulture;+ try+ {+ CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(locale);+ CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(locale);+ var c = Gdd03ProjectCatalogue.Read(Input());+ Assert.Equal(3m, c.BuilderSlots.Amount);+ Assert.Equal(1m, c.CityStarts.Amount);+ Assert.Equal(new[] { 1m, 1.5m, 3m }, new[] { c.OrdinaryOrNoviceRate.Amount, c.ApprenticeRate.Amount, c.ExpertRate.Amount });+ // content/gdd03-balance.yaml:524-667; GDD balance.md:78-84.+ var expected = new[] {+ ("maabara", 5m, 1m, 0.10m), ("permanent_housing", 15m, 3m, 0.25m),+ ("industry", 10m, 3m, 0.25m), ("reception_camp", 10m, 3m, 0.25m),+ ("training_centre", 10m, 3m, 0.50m), ("arms_workshop", 15m, 3m, 0.50m),+ ("military_camp", 12m, 3m, 0.50m)+ };+ Assert.Equal(expected.Select(x => x.Item1), c.Projects.Select(x => x.Key));+ foreach (var (key, cost, work, upkeep) in expected)+ {+ var p = Assert.Single(c.Projects, x => x.Key == key);+ Assert.Equal(cost, p.Cost.Amount); Assert.Equal(work, p.Work.Amount); Assert.Equal(upkeep, p.Upkeep.Amount);+ Assert.Equal("Default", p.Upkeep.Basis);+ Assert.Equal(key == "military_camp" ? "Default" : "Agreed", p.Cost.Basis);+ Assert.Equal(p.Cost.Basis, p.Work.Basis);+ Assert.Equal("values." + key + ".parts.upkeep", p.Upkeep.SourcePath);+ Assert.False(string.IsNullOrWhiteSpace(p.Upkeep.Note));+ }+ Assert.Equal(1m, c.Projects[0].Capacity!.Amount); Assert.Equal(-10m, c.Projects[0].ConditionPp!.Amount);+ Assert.Equal(3m, c.Projects[1].Capacity!.Amount); Assert.Equal(10m, c.Projects[1].ConditionPp!.Amount);+ Assert.Equal(1m, c.Projects[2].Capacity!.Amount);+ Assert.Equal(3m, c.Projects[3].Capacity!.Amount);+ Assert.Equal("reception.capacity", c.Projects[3].Capacity!.SourcePath.Substring("values.".Length));+ Assert.Equal(Gdd03ProjectCatalogue.CompletionEffect.MatchingTeacherCourseAndHousing, c.Projects[4].Effect);+ Assert.Null(c.Projects[4].Capacity);+ Assert.Equal("Default", c.Projects[3].StandaloneBasis); Assert.Equal("Default", c.Projects[4].StandaloneBasis);+ Assert.Equal(1m, c.Projects[5].Capacity!.Amount); Assert.Equal(5m, c.Projects[6].Capacity!.Amount);+ Assert.Equal(new[] {+ Gdd03ProjectCatalogue.CompletionEffect.OrdinaryHousing, Gdd03ProjectCatalogue.CompletionEffect.OrdinaryHousing,+ Gdd03ProjectCatalogue.CompletionEffect.IndustryJob, Gdd03ProjectCatalogue.CompletionEffect.ReceptionBeds,+ Gdd03ProjectCatalogue.CompletionEffect.MatchingTeacherCourseAndHousing,+ Gdd03ProjectCatalogue.CompletionEffect.WorkshopWorker, Gdd03ProjectCatalogue.CompletionEffect.MilitaryTrainees+ }, c.Projects.Select(x => x.Effect));+ Assert.DoesNotContain(c.Projects, x => x.Key == "winery" || x.Key == "housing_repair");+ }+ finally { CultureInfo.CurrentCulture = previous; CultureInfo.CurrentUICulture = previousUi; }+ }++ [Theory]+ [InlineData(SaveGame.LegacyRuleset)] [InlineData(SaveGame.GddRuleset)]+ [InlineData("GDD-0.3")] [InlineData("gdd-0.30")] [InlineData("future")]+ public void IdentityIsExactEvenWithCataloguePresent(string identity)+ {+ var input = Input(identity);+ input.Gdd03Balance = null; // Identity refusal precedes any data access.+ Assert.Throws<InvalidOperationException>(() => Gdd03ProjectCatalogue.Read(input));+ }++ [Fact]+ public void PresenceAloneCannotActivateAdapter()+ {+ var input = ContentLoader.Load(RealContentTests.ContentRoot());+ Assert.Equal(SaveGame.GddRuleset, input.Ruleset);+ Assert.Throws<InvalidOperationException>(() => Gdd03ProjectCatalogue.Read(input));+ }++ [Fact]+ public void MissingOrWrongCatalogueFailsClosed()+ {+ var input = Input(); input.Gdd03Balance = null;+ Assert.Throws<ContentException>(() => Gdd03ProjectCatalogue.Read(input));+ input = Input(); input.Gdd03Balance!.Ruleset = SaveGame.GddRuleset;+ Assert.Throws<ContentException>(() => Gdd03ProjectCatalogue.Read(input));+ input = Input(); input.Gdd03Balance!.Values.Remove("industry");+ Assert.Throws<ContentException>(() => Gdd03ProjectCatalogue.Read(input));+ }++ [Theory]+ [InlineData("deferred")] [InlineData("expression")] [InlineData("missing")]+ [InlineData("negative")] [InlineData("zero")] [InlineData("arity")]+ [InlineData("fractional_slots")] [InlineData("overflow_slots")]+ [InlineData("fractional_work")] [InlineData("condition_range")]+ [InlineData("tier_arity")] [InlineData("tier_order")] [InlineData("tier_zero")]+ [InlineData("provenance")] [InlineData("unknown_part")]+ [InlineData("null_part")] [InlineData("null_values")] [InlineData("upkeep_basis")]+ [InlineData("capacity_fraction")] [InlineData("standalone_expression")]+ public void MalformedOrUnsettledPartsAreRejected(string defect)+ {+ // All mutations below are test-only synthetic invalid data, never balance choices.+ var input = Input(); var values = input.Gdd03Balance!.Values;+ var cost = values["industry"].Parts["cost"];+ switch (defect)+ {+ case "deferred": cost.Basis = "Deferred"; cost.Values.Clear(); cost.Expression = "unresolved"; break;+ case "expression": cost.Values.Clear(); cost.Expression = "arbitrary formula"; break;+ case "missing": values["industry"].Parts.Remove("work"); break;+ case "negative": cost.Values[0] = -1m; break;+ case "zero": values["industry"].Parts["upkeep"].Values[0] = 0m; break;+ case "arity": cost.Values.Add(1m); break;+ case "fractional_slots": values["builder.slots_per_project"].Values[0] = 1.5m; break;+ case "overflow_slots": values["builder.slots_per_project"].Values[0] = decimal.MaxValue; break;+ case "fractional_work": values["industry"].Parts["work"].Values[0] = 1.5m; break;+ case "condition_range": values["maabara"].Parts["condition_pp"].Values[0] = -101m; break;+ case "tier_arity": values["builder.work_rate"].Values.RemoveAt(0); break;+ case "tier_order": values["builder.work_rate"].Values.Reverse(); break;+ case "tier_zero": values["builder.work_rate"].Values[0] = 0m; break;+ case "provenance": cost.Note = ""; break;+ case "unknown_part": values["industry"].Parts["typo"] = cost; break;+ case "null_part": values["industry"].Parts["cost"] = null!; break;+ case "null_values": cost.Values = null!; break;+ case "upkeep_basis": values["industry"].Parts["upkeep"].Basis = "Agreed"; break;+ case "capacity_fraction": values["reception.capacity"].Values[0] = 1.5m; break;+ case "standalone_expression": values["reception_camp"].Parts["standalone_application"].Expression = "evaluate this"; break;+ }+ Assert.Throws<ContentException>(() => Gdd03ProjectCatalogue.Read(input));+ }++ [Fact]+ public void SnapshotCopiesCatalogueWithoutFallbackOrMutableAliases()+ {+ var input = Input(); var cost = input.Gdd03Balance!.Values["industry"].Parts["cost"];+ cost.Values[0] = 7.25m; cost.Note = "test-only synthetic price";+ var result = Gdd03ProjectCatalogue.Read(input);+ cost.Values[0] = 9m;+ var industry = Assert.Single(result.Projects, x => x.Key == "industry");+ Assert.Equal(7.25m, industry.Cost.Amount); Assert.Equal("test-only synthetic price", industry.Cost.Note);+ Assert.Throws<NotSupportedException>(() => ((IList<Gdd03ProjectCatalogue.Project>)result.Projects).Clear());+ }++ // R-PROJ-001: every provenance field is copied from its own synthetic-labelled source, without aliases.+ [Fact] public void ProjectAndNumberProvenanceIsCopiedFromTheCorrectRows()+ {+ var input = Input(); var values = input.Gdd03Balance!.Values;+ foreach (var pair in values)+ {+ pair.Value.Note = "synthetic root " + pair.Key;+ foreach (var part in pair.Value.Parts) part.Value.Note = "synthetic part " + pair.Key + "." + part.Key;+ }+ var result = Gdd03ProjectCatalogue.Read(input);+ void Check(Gdd03ProjectCatalogue.Number number, string key, string? part = null)+ {+ Assert.Equal("values." + key + (part == null ? "" : ".parts." + part), number.SourcePath);+ Assert.Equal(part == null ? "synthetic root " + key : "synthetic part " + key + "." + part, number.Note);+ Assert.Equal(part == null ? values[key].Basis : values[key].Parts[part].Basis, number.Basis);+ }+ void Verify()+ {+ Check(result.BuilderSlots, "builder.slots_per_project"); Check(result.CityStarts, "construction.starts_per_turn");+ foreach (var rate in new[] { result.OrdinaryOrNoviceRate, result.ApprenticeRate, result.ExpertRate }) Check(rate, "builder.work_rate");+ foreach (var project in result.Projects)+ {+ var key = project.Key;+ Assert.Equal(key == "military_camp" ? "Default" : "Agreed", project.Basis);+ Assert.Equal("synthetic root " + key, project.Note);+ Check(project.Cost, key, "cost"); Check(project.Work, key, "work"); Check(project.Upkeep, key, "upkeep");+ if (project.ConditionPp != null) Check(project.ConditionPp, key, "condition_pp");+ if (project.Capacity != null)+ {+ if (key == "reception_camp") Check(project.Capacity, "reception.capacity");+ else if (key == "military_camp") Check(project.Capacity, "military.camp_capacity");+ else Check(project.Capacity, key, key == "industry" ? "job_slots" : key == "arms_workshop" ? "worker_slots" : "housing");+ }+ if (key == "reception_camp" || key == "training_centre")+ {+ Assert.Equal("Default", project.StandaloneBasis);+ Assert.Equal("synthetic part " + key + ".standalone_application", project.StandaloneNote);+ }+ else { Assert.Null(project.StandaloneBasis); Assert.Null(project.StandaloneNote); }+ }+ }+ Verify();+ foreach (var row in values.Values) { row.Note = "mutated synthetic note"; foreach (var part in row.Parts.Values) part.Note = "mutated synthetic note"; }+ Verify();+ }+}diff --git a/sim/Statecraft.Sim/Gdd03ProjectCatalogue.cs b/sim/Statecraft.Sim/Gdd03ProjectCatalogue.csnew file mode 100644index 000000000..9fbfafc3c--- /dev/null+++ b/sim/Statecraft.Sim/Gdd03ProjectCatalogue.cs@@ -0,0 +1,162 @@+using System;+using System.Collections.Generic;+using System.Linq;++namespace Statecraft.Sim+{+ /// <summary>Detached, immutable view of settled city-project design data. This is not a+ /// project service or loop switch. Only synthetic callers use it until integration is approved.+ /// Winery, repair pricing and operational construction are deliberately absent.</summary>+ public sealed class Gdd03ProjectCatalogue+ {+ public enum CompletionEffect+ {+ OrdinaryHousing, IndustryJob, ReceptionBeds, MatchingTeacherCourseAndHousing,+ WorkshopWorker, MilitaryTrainees+ }++ public sealed class Number+ {+ public decimal Amount { get; }+ public string Basis { get; }+ public string Note { get; }+ public string SourcePath { get; }+ internal Number(decimal amount, Gdd03DesignValue source, string path)+ { Amount = amount; Basis = source.Basis; Note = source.Note; SourcePath = path; }+ }++ public sealed class Project+ {+ public string Key { get; }+ public string Basis { get; }+ public string Note { get; }+ public Number Cost { get; }+ public Number Work { get; }+ public Number Upkeep { get; }+ public CompletionEffect Effect { get; }+ // Capacity meaning comes from Effect; centres have a qualitative effect, no invented count.+ public Number? Capacity { get; }+ public Number? ConditionPp { get; }+ // Symbolic provenance only; no standalone pioneer operation is implemented.+ public string? StandaloneBasis { get; }+ public string? StandaloneNote { get; }+ internal Project(string key, Gdd03DesignValue row, Number cost, Number work, Number upkeep,+ CompletionEffect effect, Number? capacity, Number? condition, Gdd03DesignValue? standalone)+ {+ Key = key; Basis = row.Basis; Note = row.Note; Cost = cost; Work = work; Upkeep = upkeep;+ Effect = effect; Capacity = capacity; ConditionPp = condition;+ StandaloneBasis = standalone?.Basis; StandaloneNote = standalone?.Note;+ }+ }++ public IReadOnlyList<Project> Projects { get; }+ public Number BuilderSlots { get; }+ public Number CityStarts { get; }+ public Number OrdinaryOrNoviceRate { get; }+ public Number ApprenticeRate { get; }+ public Number ExpertRate { get; }++ private Gdd03ProjectCatalogue(List<Project> projects, Number slots, Number starts, Number[] rates)+ {+ Projects = projects.AsReadOnly(); BuilderSlots = slots; CityStarts = starts;+ OrdinaryOrNoviceRate = rates[0]; ApprenticeRate = rates[1]; ExpertRate = rates[2];+ }++ // R-PROJ-001..003 describe the future consumer; this adapter performs no state mutation.+ public static Gdd03ProjectCatalogue Read(Content content)+ {+ if (content == null) throw new ArgumentNullException(nameof(content));+ // Check the full identity before touching data: IsGdd and catalogue presence are insufficient.+ if (content.Ruleset != SaveGame.Gdd03Ruleset)+ throw new InvalidOperationException("Project catalogue access requires exact gdd-0.3 identity.");+ var catalogue = content.Gdd03Balance;+ if (catalogue == null || catalogue.Ruleset != SaveGame.Gdd03Ruleset || catalogue.Values == null)+ throw Error("values", "requires the gdd-0.3 balance catalogue; no old-project fallback");++ Gdd03DesignValue Root(string key)+ {+ if (!catalogue.Values.TryGetValue(key, out var row) || row == null)+ throw Error("values." + key, "settled project catalogue row required");+ row.Validate("values." + key);+ return row;+ }+ Number Scalar(string key, bool whole = false) =>+ ReadNumber(Root(key), "values." + key, "Agreed", whole);+ // Shared readers own numeric validation; projects additionally require copied provenance.+ Gdd03DesignValue Provenance(string key)+ {+ if (!catalogue.Values.TryGetValue(key, out var row) || row == null || string.IsNullOrWhiteSpace(row.Note))+ throw Error("values." + key, "design basis/provenance required");+ return row;+ }+ Number SharedNumber(string key, decimal amount) => new Number(amount, Provenance(key), "values." + key);++ var slots = Scalar("builder.slots_per_project", true);+ var starts = Scalar("construction.starts_per_turn", true);+ var builderRates = Gdd03CraftArithmetic.ReadBuilderRates(catalogue);+ var rateRow = Provenance("builder.work_rate");+ const string ratePath = "values.builder.work_rate";+ // Project-only layer over the shared three nonnegative Agreed rates: positive and ordered.+ if (builderRates.Any(x => x <= 0) || builderRates[0] > builderRates[1] || builderRates[1] > builderRates[2])+ throw Error(ratePath, "requires three positive ordered Agreed ordinary-or-novice/apprentice/expert rates");+ var rates = builderRates.Select(x => new Number(x, rateRow, ratePath)).ToArray();++ Project Descriptor(string key, CompletionEffect effect, string? capacityPart = null,+ Number? capacity = null, bool condition = false, bool standalone = false)+ {+ var row = Root(key); var path = "values." + key;+ var basis = key == "military_camp" ? "Default" : "Agreed";+ var expected = new List<string> { "cost", "work", "upkeep" };+ if (capacityPart != null) expected.Add(capacityPart);+ if (condition) expected.Add("condition_pp");+ if (standalone) expected.Add("standalone_application");+ if (row.Basis != basis || row.Values.Count != 0 || !string.IsNullOrEmpty(row.Expression)+ || !expected.OrderBy(x => x, StringComparer.Ordinal).SequenceEqual(row.Parts.Keys.OrderBy(x => x, StringComparer.Ordinal)))+ throw Error(path, "requires the settled labelled project parts; no inferred or extra fields");+ Number Part(string name, string partBasis, bool whole = false, bool pp = false) =>+ ReadNumber(row.Parts[name], path + ".parts." + name, partBasis, whole, pp);+ Gdd03DesignValue? application = null;+ if (standalone)+ {+ application = row.Parts["standalone_application"];+ if (application.Basis != "Default" || application.Values.Count != 0 || application.Parts.Count != 0+ || application.Expression != "same cost/work")+ throw Error(path + ".parts.standalone_application", "requires the symbolic Default same cost/work provenance");+ }+ return new Project(key, row, Part("cost", basis), Part("work", basis, true), Part("upkeep", "Default"),+ effect, capacityPart != null ? Part(capacityPart, "Agreed", true) : capacity,+ condition ? Part("condition_pp", "Agreed", true, true) : null, application);+ }++ // Source order is explicit and deterministic, never Dictionary iteration order.+ var projects = new List<Project> {+ Descriptor("maabara", CompletionEffect.OrdinaryHousing, "housing", condition: true),+ Descriptor("permanent_housing", CompletionEffect.OrdinaryHousing, "housing", condition: true),+ Descriptor("industry", CompletionEffect.IndustryJob, "job_slots"),+ Descriptor("reception_camp", CompletionEffect.ReceptionBeds,+ capacity: SharedNumber("reception.capacity", content.RequirePopulationInteger("reception.capacity")), standalone: true),+ Descriptor("training_centre", CompletionEffect.MatchingTeacherCourseAndHousing, standalone: true),+ Descriptor("arms_workshop", CompletionEffect.WorkshopWorker, "worker_slots"),+ Descriptor("military_camp", CompletionEffect.MilitaryTrainees,+ capacity: SharedNumber("military.camp_capacity", Gdd03MilitaryCatalogue.ReadCampCapacity(catalogue)))+ };+ return new Gdd03ProjectCatalogue(projects, slots, starts, rates);+ }++ private static Number ReadNumber(Gdd03DesignValue row, string path, string basis, bool whole, bool pp = false)+ {+ if (row.Basis != basis || row.Values.Count != 1 || row.Parts.Count != 0 || !string.IsNullOrEmpty(row.Expression))+ throw Error(path, "requires one settled labelled number; Deferred and symbolic quantities are not executable");+ var amount = row.Values[0];+ // Percentage points use the standard [-100,100] unit range, not an initial condition default.+ if (pp ? amount < -100m || amount > 100m : amount <= 0)+ throw Error(path, pp ? "condition effect must be within percentage-point bounds" : "requires a positive quantity");+ if (whole && (decimal.Truncate(amount) != amount || amount > int.MaxValue || amount < int.MinValue))+ throw Error(path, "requires a whole quantity representable as an integer");+ return new Number(amount, row, path);+ }++ private static ContentException Error(string path, string message) =>+ new ContentException(Gdd03BalanceCatalogue.FileName, path, message);+ }+}